Script reacting to Docker events

Next, we will write a script to monitor changes in the Docker cluster and then do a print out when a node is updated:

#!/usr/bin/env gorun
package main

import (
"context"
"fmt"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
)

func main() {
ctx := context.Background()

cli, err := client.NewClient(client.DefaultDockerHost, "1.30", nil, nil)
if err != nil {
panic(err)
}

filter := filters.NewArgs(filters.Arg("type", "node"))
ch, _ := cli.Events(ctx, types.EventsOptions{
Filters: filter,
})

for {

fmt.Println("Waiting for event ...")
message := <-ch
action := message.Action

switch action {
case "create":
fmt.Println(" - New node added.")
case "update":
fmt.Println(" - Node updated.")
case "remove":
fmt.Println(" - Node removed.")
}

}

}

This is also a script executed by gorun. The script starts by creating a Docker client CLI pointing to the local socket, /var/run/docker.sock.

Then it creates a filter, the filter variable. This filter makes the event emitter select only the type of events we are interested in, in this case, when the type of events is node. This is equivalent to passing --filter type=node to the command line. The cli.Events method will return a Go channel for retrieving messages. A message is then retrieved inside the for loop. The program will be automatically blocked if the message is not available in the channel. So the script just becomes a single-thread style and easy to program.

Inside the loop, we can manipulate information inside the message, for example, checking the action of a certain event. Normally, most types of event contain three possible actions, create, update, and remove. For a node, create means there is a new node added to the cluster. The update action means something has changed on a certain node. The remove action means the node is removed from the cluster.

Just save this script to ./node-event, then chmod +x it.

$ chmod +x ./node-event
The chmod command will change executable bits of the script. With these bits, the Linux system will be able to detect that the file should be executed. Then, it will tell gorun to take care of that execution.

Try changing some properties of the current working node. We may observe that the text - Node updated. will be printed out.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset