Sparrow is very efficient in writing scripts to automate system management using Raku and Bash, in today's post I am going to show an example ...

Deploy configuration file and restart service upon changes

Let's create a simple plugin that enable / disable some configuration flags in service configuration file and if any changes occur reload a service. Format of flags in configuration file is following:

var=true|false

Here is an example of configuration file:

config.txt

debug=true
sentry=false
tls=false

Usually services are managed as systemd units, so service reload could be used to reload service configuration.

#!bash

# create root directory for plugin source code
# for convenience 

mkdir -p service-config-reload
cd service-config-reload

Now inside plugin root directory:

hook.raku:

#!raku

my $cfg-orig = config()<path>.IO.slurp();

my $cfg = $cfg-orig;

for config()<enable><> -> $f {
   $cfg ~~ s/<?wb> "$f=" \S+ /$f=true/;
}

for config()<disable><> -> $f {
   $cfg ~~ s/<?wb> "$f=" \S+ /$f=false/;
}

set_stdout($cfg);

if $cfg ne $cfg-orig {
   set_stdout("config changed");
   config()<path>.IO.spurt($cfg);
   run_task "service_restart", %(
       service => config()<service>,
       path => config()<path>,
   );
}
mkdir -p tasks/service_restart/

tasks/service_restart/task.bash

#!bash

sudo service $service reload

In real life applications services might have a linter capability where before configuration is applied it's checked and if any error occur application of changes is terminated:

#!bash

set -e
sudo /usr/bin/$service --check $path
sudo service $service reload

Publish plugin

Packaging scenario as a plugin allow other to use it.

sparrow.json

{
  "name" : "service-config-reload",
  "description" : "Deploy configuration file and restart service upon changes",
  "version" : "0.0.1",
  "category" : "linux",
  "url" : "https://github.com/melezhik/sparrow-plugins/tree/master/service-config-reload"
}

This last command will upload plugin to local Sparrow repository (see this doc for more details)

#!bash

s6 --upload

Use of plugins

Anywhere in Raku scenario, just do this:

#!raku

use Sparrow6::DSL;

task-run "apply and reload", "service-config-reload", %(
   :path<config.txt>,
   :service<app>,
   enable => <tls sentry>, # enable TLS and use of Sentry for production
   disable => <debug>, # disable debug mode for production 
)

Thanks for reading!

PS

Source code of the plugin could be found here - https://github.com/melezhik/sparrow-plugins/tree/master/service-config-reload

Author Of article : Alexey Melezhik Read full article