Next: , Previous: , Up: Definición de servicios   [Contents][Index]


11.19.4 Servicios de Shepherd

El módulo (gnu services shepherd) proporciona una forma de definir servicios gestionados por GNU Shepherd, que es el sistema de inicio—el primer proceso que se inicia cuando el sistema arranca, también conocido como PID 1 (see Introduction in The GNU Shepherd Manual).

Los servicios en Shepherd pueden depender de otros servicios. Por ejemplo, el daemon SSH puede tener que arrancarse tras el arranque del daemon syslog, lo cual a su vez puede suceder únicamente tras el montaje de todos los sistemas de archivos. El sistema operativo simple definido previamente (see Uso de la configuración del sistema) genera un grafo de servicios como este:

Grafo típico de servicios de shepherd.

En realidad puede generar dicho grafo para cualquier definición de sistema operativo mediante el uso de la orden guix system shepherd-graph (see guix system shepherd-graph).

%shepherd-root-service es un objeto de servicio que representa el PID 1, del tipo shepherd-root-service-type; puede ser extendido proporcionandole listas de objetos <shepherd-service>.

Tipo de datos: shepherd-service

El tipo de datos que representa un servicio gestionado por Shepherd.

provision

Una lista de símbolos que indican lo que proporciona el servicio.

Esto son nombres que pueden proporcionarse a herd start, herd status y órdenes similares (see Invoking herd in The GNU Shepherd Manual). See Defining Services in The GNU Shepherd Manual, para más detalles.

requirement (predeterminada: '())

Lista de símbolos que indican los servicios Shepherd de los que este depende.

one-shot? (predeterminado: #f)

Si este servicio es one-shot. Los servicios “one-shot” finalizan inmediatamente después de que su acción start se complete. See Slots of services in The GNU Shepherd Manual, para más información.

respawn? (predeterminado: #t)

Indica si se debe reiniciar el servicio cuando se para, por ejemplo cuando el proceso subyacente muere.

respawn-limit (default: #f)

Set a limit on how many times and how frequently a service may be restarted by Shepherd before it is disabled. See Defining Services in The GNU Shepherd Manual, for details.

respawn-delay (default: #f)

When true, this is the delay in seconds before restarting a failed service.

start (default: #~(const #t))
stop (predeterminado: #~(const #f))

Los campos start y stop hacen referencia a las características de Shepherd de arranque y parada de procesos respectivamente (see Service De- and Constructors in The GNU Shepherd Manual). Se proporcionan como expresiones-G que se expandirán en el archivo de configuración de Shepherd (see Expresiones-G).

actions (predeterminadas: '())

Esta es la lista de objetos shepherd-action (véase a continuación) que definen las acciones permitidas por el servicio, además de las acciones estándar start y stop. Las acciones que se listan aquí estarán disponibles como ordenes de herd:

herd acción servicio [parámetros…]
free-form (default: #f)

When set, this field replaces the start, stop, and actions fields. It is meant to be used when the service definition comes from some other source, typically the service collection provided by the Shepherd proper (see Service Collection in The GNU Shepherd Manual).

For example, the snippet below defines a service for the Shepherd’s built-in REPL (read-eval-print loop) service (see REPL Service in The GNU Shepherd Manual):

(shepherd-service
  (provision '(repl))
  (modules '((shepherd service repl)))
  (free-form #~(repl-service)))

In this case, the service object is returned by the repl-service procedure of the Shepherd, so all the free-form G-expression does is call that procedure. Note that the provision field must be consistent with the actual service provision.

auto-start? (predeterminado: #t)

Determina si Shepherd debe iniciar este servicio de manera automática. Si es #f el servicio debe iniciarse manualmente con herd start.

documentation

Una cadena de documentación, que se mostrará al ejecutar:

herd doc nombre-del-servicio

donde nombre-del-servicio es uno de los símbolos en provision (see Invoking herd in The GNU Shepherd Manual).

modules (predeterminados: %default-modules)

Esta es la lista de módulos que deben estar dentro del ámbito cuando start y stop son evaluados.

The example below defines a Shepherd service that spawns syslogd, the system logger from the GNU Networking Utilities (see syslogd in GNU Inetutils):

(let ((config (plain-file "syslogd.conf" "…")))
  (shepherd-service
    (documentation "Run the syslog daemon (syslogd).")
    (provision '(syslogd))
    (requirement '(user-processes))
    (start #~(make-forkexec-constructor
               (list #$(file-append inetutils "/libexec/syslogd")
                     "--rcfile" #$config)
               #:pid-file "/var/run/syslog.pid"))
    (stop #~(make-kill-destructor))))

Key elements in this example are the start and stop fields: they are staged code snippets that use the make-forkexec-constructor procedure provided by the Shepherd and its dual, make-kill-destructor (see Service De- and Constructors in The GNU Shepherd Manual). The start field will have shepherd spawn syslogd with the given option; note that we pass config after --rcfile, which is a configuration file declared above (contents of this file are omitted). Likewise, the stop field tells how this service is to be stopped; in this case, it is stopped by making the kill system call on its PID. Code staging is achieved using G-expressions: #~ stages code, while #$ “escapes” back to host code (see Expresiones-G).

Tipo de datos: shepherd-action

Este es el tipo de datos que define acciones adicionales implementadas por un servicio Shepherd (vea previamente).

name

Símbolo que nombra la acción.

documentation

Esta es una cadena de documentación para la acción. Puede verse ejecutando:

herd doc servicio action acción
procedure

Debe ser una expresión-G que evalúa a un procedimiento de al menos un parámetro, el cual es el “valor de ejecución” del servicio (see Slots of services in The GNU Shepherd Manual).

El siguiente ejemplo define una acción llamada di-hola que saluda amablemente a la usuaria:

(shepherd-action
  (name 'di-hola)
  (documentation "¡Di hola!")
  (procedure #~(lambda (running . args)
                 (format #t "¡Hola, compa! parámetros: ~s\n"
                         args)
                 #t)))

Asumiendo que esta acción se añade al servicio ejemplo, puede ejecutar:

# herd di-hola ejemplo
¡Hola, compa! parámetros: ()
# herd di-hola ejemplo a b c
¡Hola, compa! parámetros: ("a" "b" "c")

Esta, como puede ver, es una forma un tanto sofisticada de decir hola. See Defining Services in The GNU Shepherd Manual, para más información sobre acciones.

Procedure: shepherd-configuration-action

Return a configuration action to display file, which should be the name of the service’s configuration file.

It can be useful to equip services with that action. For example, the service for the Tor anonymous router (see tor-service-type) is defined roughly like this:

(let ((torrc (plain-file "torrc" )))
  (shepherd-service
    (provision '(tor))
    (requirement '(user-processes loopback syslogd))

    (start #~(make-forkexec-constructor
              (list #$(file-append tor "/bin/tor") "-f" #$torrc)
              #:user "tor" #:group "tor"))
    (stop #~(make-kill-destructor))
    (actions (list (shepherd-configuration-action torrc)))
    (documentation "Run the Tor anonymous network overlay.")))

Thanks to this action, administrators can inspect the configuration file passed to tor with this shell command:

cat $(herd configuration tor)

This can come in as a handy debugging tool!

Variable: shepherd-root-service-type

El tipo de servicio para el “servicio raíz” de Shepherd—es decir, PID 1.

This is the service type that extensions target when they want to create shepherd services (see Tipos de servicios y servicios, for an example). Each extension must pass a list of <shepherd-service>. Its value must be a shepherd-configuration, as described below.

Data Type: shepherd-configuration

This data type represents the Shepherd’s configuration.

shepherd (default: shepherd)

The Shepherd package to use.

services (default: '())

A list of <shepherd-service> to start. You should probably use the service extension mechanism instead (see Servicios de Shepherd).

The following example specifies the Shepherd package for the operating system:

(operating-system
  ;; ...
  (services (append (list openssh-service-type))
            ;; ...
            %desktop-services)
  ;; ...
  ;; Use own Shepherd package.
  (essential-services
   (modify-services (operating-system-default-essential-services
                     this-operating-system)
     (shepherd-root-service-type config => (shepherd-configuration
                                            (inherit config)
                                            (shepherd my-shepherd))))))
Variable: shepherd-transient-service-type

This service type represents the Shepherd’s transient service, which lets you spawn commands in the background and interact with them as regular Shepherd service; it is similar to systemd-run.

For example, the command below spawns rsync in the background, in an environment where the SSH_AUTH_SOCK environment variable has the given value:

herd spawn transient -E SSH_AUTH_SOCK=$SSH_AUTH_SOCK -- \
  rsync -e ssh -vur . backup.example.org:

See Transient Service Maker in The GNU Shepherd Manual, for more info on the transient service.

Variable: shepherd-timer-service-type

This is the service type representing the Shepherd’s timer service, which lets you schedule the execution of commands, similar to the venerable at command. Here is an example:

herd schedule timer at 07:00 -- mpg123 Music/alarm.mp3

See Timer Service in The GNU Shepherd Manual, for more info on the timer service.

Variable: shepherd-system-log-service-type

This service implements a system log, reading messages applications send to /dev/log and writing them to files or terminals according to user-defined rules. It provides functionality traditionally implemented by syslogd programs.

The value of services of this type must be a system-log-configuration record, as described below.

Data Type: system-log-configuration

Available system-log-configuration fields are:

provision (default: (system-log syslogd)) (type: list-of-symbols)

The name(s) of the system log service.

requirement (default: (root-file-system)) (type: list-of-symbols)

Dependencies of the system log service.

kernel-log-file (type: gexp-or-string-or-false)

File from which kernel messages are read, /dev/kmsg by default.

message-destination (default: #f) (type: gexp-or-false)

This gexp must evaluate to a procedure that, when passed a log message, returns the list of files to write it to; #f is equivalent to using (default-message-destination-procedure). See System Log Service in The GNU Shepherd Manual, for information on how to write that procedure.

date-format (type: gexp-or-string)

String or string-valued gexp specifying how to format timestamps in log file. It must be a valid string for strftime (see Time in GNU Guile Reference Manual), including delimiting space—e.g., "%c " for a format identical to that of traditional syslogd implementations.

history-size (type: gexp-or-integer)

Number of logging messages kept in memory for the purposes of making them available to herd status system-log.

max-silent-time (type: gexp-or-integer)

Time after which a mark is written to log files if nothing was logged during that time frame.

Variable: %shepherd-root-service

Este servicio representa el PID 1.


Next: Complex Configurations, Previous: Referencia de servicios, Up: Definición de servicios   [Contents][Index]