Creating New LaunchDaemons and StartupItems

Creating New LaunchDaemons and StartupItems

In this section we are focusing on the use of launchd and SystemStarter to manage daemons that are started when the machine boots up and/or are started later as needed. You will use the same procedure you used to create a scheduled job with launchd , but with a different configuration in the . plist file. Before starting in on the next task, go back and review "Scheduling jobs using launchd ," earlier in this chapter.

To create a LaunchDaemon that starts at boot time and runs continuously:

1.
Create the configuration file /Library/LaunchDaemons/ filename

For example:

 sudo vi /Library/LaunchDaemons/  calculatord.plist 

The actual filename can be pretty much anything you like, but we suggest you use the .plist extension since the file will be in the plist format. For example, chat-service.plist is better than chat-service.

2.
Set the OnDemand property to false .

This means including the following in your file:

 <key>OnDemand</key> <false/> 

Figure 11.33 shows a sample launchd configuration file that will cause launchd to start up the Calculator application at boot time and keep it running all the timenote that the OnDemand property is set to false . The default is true , so if you leave that property out of the file, then launchd will not launch your daemon at boot time; instead it will wait for a "demand." See the next task for more on this.

Figure 11.33. A sample launchd configuration file that keeps the Calculator application running all the time ( OnDemand set to false ).
 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd > <plist version="1.0"> <dict>           <key>Label</key>           <string>com.apple.calculator</string>           <key>ProgramArguments</key>           <array>                  <string>/Applications/Calculator.app/Contents/MacOS/Calculator</string>           </array>           <key>OnDemand</key>           <false/> </dict> </plist> 

If you want the new daemon to run right away (as opposed to waiting for the next reboot), you may load the configuration file using launchctl :

launchctl load / path /to/file

For example:

 launchctl load /Library/  LaunchDaemons/calculatord.plist 

If you used the sample code from Figure 11.33, then the Calculator application will launch immediately, and if you quit it, launchd will promptly launch it again. To stop the daemon, you use launchctl to unload the configuration:

launchctl unload /path/to/file

For example:

 launchctl unload /Library/  LaunchDaemons/calculatord.plist 

More on launchd

For more details and examples of using launchd , check out the following two articles online: "launchd in Depth" (www.afp548.com/article.php?story=20050620071558293) and "All About launchd Items and How to Make One Yourself" (www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself). Also see the Apple document "Creating Launch-On-Demand Daemons" (http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/LaunchOnDemandDaemons.html) and read the portion of the launchd.plist man page that describes the Socket property.


Tips

  • If your daemon must run as root, or if you have it switching to a different user (via the UserName property in the configuration file), then you must run launchctl as root or reboot the machine:

    sudo launchctl load /path/to/file

  • Review the man page for launchd.plist files:

    man launchd.plist

    and pay special attention to the EXPECTATIONS section at the beginning. There is a list of things that the daemon you are configuring should and should not do. Also, the man page has the complete list of the XML properties you can use in the configuration file. (Table 11.5 lists many of them, but the man page has the complete list.)


Looking at StartupItems

A StartupItem consists of a directory containing at least two files: the actual system-startup program (usually a script) that has the same name as the directory and should handle arguments of start and stop , and a file named StartupParameters.plist. Figure 11.34 is the script /System/Library/StartupItems/Apache/Apache which is used by SystemStarter to start the Apache Web server at boot time. Figure 11.35 shows the StartupParameters.plist file for the Apache Web server ( /System/Library/StartupItems/Apache/StartupParameters.plist ). The StartupParameters.plist file may be in one of two formatseither the legacy NeXT-style format (shown in Figure 11.34) or in the newer , recommended XML format described in the plist man page (shown in the next task).

Figure 11.34. The StartupItems script /System/Library/StartupItems/Apache/Apache used by SystemStarter to start the Apache Web server at boot time.
 #!/bin/sh ## # Apache HTTP Server ## . /etc/rc.common StartService () {        if [ "${WEBSERVER:=-NO-}" = "-YES-" ]; then        echo "Starting Apache web server"        if [ ! -e /etc/httpd/httpd.conf ] ; then                  cp -p /etc/httpd/httpd.conf.default /etc/httpd/httpd.conf        fi        apachectl start        if [ "${WEBPERFCACHESERVER:=-NO-}" = "-YES-" ]; then             if [ -x /usr/sbin/webperfcachectl ]; then                  echo "Starting web performance cache server"                  /usr/sbin/webperfcachectl start        fi        fi   fi } StopService () {        if [ -x /usr/sbin/webperfcachectl ]; then             echo "Stopping web performance cache server"             /usr/sbin/webperfcachectl stop        fi        echo "Stopping Apache web server"        apachectl stop } RestartService () {        if [ "${WEBSERVER:=-NO-}" = "-YES-" ]; then             echo "Restarting Apache web server"             apachectl restart             if [ "${WEBPERFCACHESERVER:=-NO-}" = "-YES-" ]; then             if [ -x /usr/sbin/webperfcachectl ]; then                  echo "Restarting web performance cache server"                  /usr/sbin/webperfcachectl restart        fi   fi   else   StopService   fi } RunService "" 

Figure 11.35. StartupParameters.plist file for the Apache Web server StartupItem: /System/Library/StartupItems/Apache/StartupParameters.plist .
 {   Description   = "Apache web server";   Provides      = ("Web Server");   Uses          = ("Disks", "NFS"); } 

StartupItems provided by Apple are in /System/Library/StartupItems , and StartupItems added by users (that's you) should go in /Library/StartupItems . You must be logged in as an admin user or root to create a new StartupItem.

To create a new StartupItem:

1.
Create a new directory inside /Library/StartupItems .

The new directory should have the same name as the service you are installing. For example, if you are installing the MySQL database engine, then you would call the directory MySQL :

mkdir -p /Library/StartupItems/MySQL

The -p option is necessary because the directory /Library/StartupItems may not already exist, and adding the -p tells mkdir to create the entire path.

2.
Create a file named StartupParameters.plist file (for property list ) in the new directory.

The filename must be StartupParameters.plist.

Figure 11.36 shows an annotated version of a StartupParameters.plist file for the MySQL database engine. This example uses the XML format documented in the plist man page.

Figure 11.36. Example of a StartupParameters. plist file for the MySQL database server.

3.
Create the startup script itself.

The best way to learn how to do this is to copy an existing Startup script and modify it. Look at the various scripts in the subdirectories of /System/Library/StartupItems/ your script might be able to be a modified copy of one of those. Figure 11.37 is a code listing of a startup script for the MySQL database engine, but it could be adapted for many purposes. (Review Chapter 9.)

Figure 11.37. Example of a StartupItem script for the MySQL database server. This would be installed as /System/Library/StartupItems/MySQL/MySQL .
 #!/bin/sh # # /Library/StartupItems/MySQL/MySQL # # A script to automatically start up MySQL on system bootup # for Mac OS X. This is actually just a wrapper script around # the standard mysql.server init script, which is included in # the binary distribution. # # (c) 2003 MySQL AB # Written by Lenz Grimmer <lenz@mysql.com> # # Suppress the annoying ": unbound variable" error when no option # was given if [ -z  ] ; then         echo "Usage: 
 #!/bin/sh # # /Library/StartupItems/MySQL/MySQL # # A script to automatically start up MySQL on system bootup # for Mac OS X. This is actually just a wrapper script around # the standard mysql.server init script, which is included in # the binary distribution. # # (c) 2003 MySQL AB # Written by Lenz Grimmer <lenz@mysql.com> # # Suppress the annoying "$1: unbound variable" error when no option # was given if [ -z $1 ] ; then echo "Usage: $0 [startstoprestart] " exit 1 fi # Source the common setup functions for startup scripts test -r /etc/rc.common  exit 1 . /etc/rc.common # The path to the mysql.server init script. The official MySQL # Mac OS X packages are being installed into /usr/local/mysql. SCRIPT="/usr/local/mysql/support-files/mysql.server" StartService () { if [ "${MYSQL:=-NO-}" = "-YES-" ] ; then ConsoleMessage "Starting MySQL database server" $SCRIPT start > /dev/null 2>&1 fi } StopService () { ConsoleMessage "Stopping MySQL database server" $SCRIPT stop > /dev/null 2>&1 } RestartService () { ConsoleMessage "Restarting MySQL database server" $SCRIPT restart > /dev/null 2>&1 } if test -x $SCRIPT ; then RunService "$1" else ConsoleMessage "Could not find MySQL startup script!" fi 
[startstoprestart] " exit 1 fi # Source the common setup functions for startup scripts test -r /etc/rc.common exit 1 . /etc/rc.common # The path to the mysql.server init script. The official MySQL # Mac OS X packages are being installed into /usr/local/mysql. SCRIPT="/usr/local/mysql/support-files/mysql.server" StartService () { if [ "${MYSQL:=-NO-}" = "-YES-" ] ; then ConsoleMessage "Starting MySQL database server" $SCRIPT start > /dev/null 2>&1 fi } StopService () { ConsoleMessage "Stopping MySQL database server" $SCRIPT stop > /dev/null 2>&1 } RestartService () { ConsoleMessage "Restarting MySQL database server" $SCRIPT restart > /dev/null 2>&1 } if test -x $SCRIPT ; then RunService "" else ConsoleMessage "Could not find MySQL startup script!" fi

4.
Notice the line

. /etc/rc.common

This appears in all of the Apple-provided StartupItem scripts, and you should probably use it as well. It executes the file /etc/rc.common . The file /etc/rc.common is another shell script that defines several functions, including the RunService function used in Figure 11.37.

The /etc/rc.common script ends by executing /etc/hostconfig yet another shell script that simply defines a bunch of variables used by the various Apple-supplied StartupItem scripts. Our example in Figure 11.36 uses a variable called MYSQL to determine if the service is supposed to run or not, the StartupItem script for the Apache Web server ( /System/Library/StartupItems/Apache/Apache ; see Figure 11.34) checks WEBSERVER variables, and so on.

5.
Notice how our example in Figure 11.37 defines separate functions called StartService , StopService , and RestartService .

The StartService function is the one that actually runs the service with the line

$SCRIPT start > /dev/null 2>&1

The SCRIPT variable is defined to be the full path to the executable for the servicein this case:

 SCRIPT="/usr/local/mysql/support-files/  mysql.server 

Inside the StartService function is an if statement that looks like this:

if [ "${MYSQL:=-NO-}" = "-YES-" ]

That is a somewhat advanced shell script trick that is checking if "${MYSQL:=-NO-}" is the same as -YES- .

The tricky part is "${MYSQL:=-NO-}" that means "Get the value of $MYSQL , or if there is no value, then use -NO- ." The value of $MYSQL is going to come from /etc/hostconfig more about that in the next step.

6.
Edit /etc/hostconfig to add a variable for your new service.

The /etc/hostconfig script just holds a bunch of variables that are normally set by the various tools in System Preferences (referred to as "control panels" in /etc/hostconfig ). Figure 11.38 is an example of a typical /etc/hostconfig file.

Figure 11.38. A typical /etc/hostconfig file. Yours will look different.
 ## # /etc/hostconfig ## # This file is maintained by the system control panels ## # Network configuration HOSTNAME=-AUTOMATIC- ROUTER=-AUTOMATIC- # Services AFPSERVER=-YES- AUTHSERVER=-NO- AUTOMOUNT=-YES- CUPS=-YES- IPFORWARDING=-NO- IPV6=-YES- MAILSERVER=-AUTOMATIC- NETINFOSERVER=-AUTOMATIC- NFSLOCKS=-AUTOMATIC- NISDOMAIN=-NO- RPCSERVER=-AUTOMATIC- TIMESYNC=-YES- QTSSERVER=-NO- WEBSERVER=-NO- SMBSERVER=-NO- DNSSERVER=-NO- COREDUMPS=-NO- VPNSERVER=-NO- SNMPSERVER=-NO- CHATSERVER=-NO- SPOTLIGHT=-YES- CRASHREPORTER=-YES- ARDAGENT=-YES- ENCRYPTSWAP=-NO- 

7.
Using our example from Figure 11.37, you would want to add the following line to /etc/hostconfig :

MYSQL=-YES-

The idea here is that your new StartupItem script is always going to be executed at boot time by SystemStarter with an argument of start , so you want an easy way to disable it. By having a single place for all StartupItem scripts to check, you can quickly see which ones are enabled and disabled.

8.
Test the script from the command line to see that your new service starts up. Depending on the nature of your service, you might need to test it as root (using sudo ):

 sudo /Library/StartupItems/   MyService/MyService  start 

For example:

 sudo /Library/StartupItems/  MySQL/MySQL start 

9.
Reboot the machine for further confirmation.

Tips

  • Apple's official documentation for creating new StartupItems is available via a link on http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/ (that's one long URL!).

  • You'll need to decide what should go in the Requires entry of the StartupParameters.plist. Have a look at the different StartupParameters.plist files in each of the subdirectories of /System/Library/StartupItems/ and see what is in the Provides entry for each item. You can see all the Provides entries with the following command line:

     grep Provides /System/Library/  StartupItems/*/*.plist 

    or

     find /System/Library/StartupItems -  name "*plist  xargs grep  Provides 


Setting the Hostname

If your machine is being used as a server on the Internet, you usually want it to be identified by a fully qualified domain name , or FQDN . You've already seen FQDNs, although you might not have known that's what they were called. The URL www.peachpit.com is an FQDN, as is mail.yahoo.com. If your machine has been assigned a FQDN, it may be able to figure out its hostname by itself, but it may not. The hostname command shows what your machine thinks its FQDN or hostname is. See Chapter 14, "Installing and Configuring Servers," for a more detailed discussion of FQDNs, including how to tell your machine which hostname (or FQDN) to use. The really short version of how to do it is that you edit the HOSTNAME enTRy /etc/hostconfig .


Webmina GUI Tool for System Administration

Webmin is a Web-based interface for Unix system administration that allows you to use a Web browser to perform a large variety of tasks , such as managing users and groups, managing servers such as database servers, setting up cron jobs, and much more. The basic Webmin package provides one set of features, and others are available as additional modules from Shoutcast administration, MRTG network traffic grapher , and others.

As of this writing, the latest version of Webmin (1.221) will work with Mac OS X 10.4 but does not yet provide support for launchd . So you can use it to create cron jobs but not launchd agents . Webmin is an actively maintained project with many developers contributing to it, so we expect upcoming versions to add more support for new Mac OS X features.

Webmin installs its own tiny Web server that uses the HTTPS protocol if possible. HTTPS is the HTTP protocol plus Secure Socket Layer; it causes all data sent to or from the Web server to be encrypted. This greatly reduces the risk of a packet-sniffing attack (see Chapter 12), which could intercept the Webmin user name and password, giving the attacker the equivalent of root access.

In order for Webmin to use SSL, you must install the Perl module called Net::SSLeay . Chapter 13 describes how to do this. If you do not install Net::SSLeay , you may still use Webmin, but any use of it when the Web browser is on another machine is vulnerable to packet-sniffing attacks.

Before installing Webmin, be sure to check out http://webmin.com/changes.html. Also read Chapter 13, in particular the section "Manually Installing from Source Code," which goes into more detail about the basic installation procedures you should use.




Unix for Mac OS X 10. 4 Tiger. Visual QuickPro Guide
Unix for Mac OS X 10.4 Tiger: Visual QuickPro Guide (2nd Edition)
ISBN: 0321246683
EAN: 2147483647
Year: 2004
Pages: 161
Authors: Matisse Enzer

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net