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
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…]
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.

documentación

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.

documentación

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-root-service

Este servicio representa el PID 1.


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