exitdir

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2022 License: Apache-2.0 Imports: 7 Imported by: 2

README

ExitDir

ExitDir is a library to signal a process should exit via the filesystem.

Usage

To use this library, on the leader process:

package main

import "chainguard.dev/exitdir"

func main() {
	// Signal the other processes should exit via a new file in `EXIT_DIR`.
	defer exitdir.Exit();
	// ...rest of implementation. 
}

And then one or more follower processes:

package main

import (
	"context"
	
	"chainguard.dev/exitdir"
)

func main() {
	// Decorate a context with ExitDir awareness. ExitDir will cancel the
	// returned context when a new file in `EXIT_DIR` is created.
	ctx := exitdir.Aware(context.Background())
	// ...rest of implementation using `ctx` for lifecycle control.
}

Process Demo

This functionally is shown locally by using a temp directory and two processes:

export EXIT_DIR=`mktemp -d`
go run ./cmd/follower &
go run ./cmd/leader

Results in:

$ export EXIT_DIR=`mktemp -d`
$ go run ./cmd/follower &
[1] 83528
$ go run ./cmd/leader
[Leader] Doing work...
[Follower] Tick 0
[Follower] Tick 1
[Follower] Tick 2
[Follower] Tick 3
[Leader] Exiting...
[Follower] Exiting...
[1]+  Done                    go run ./cmd/follower
$

Kubernetes Demo

Often in Kubernetes a job with multiple containers need to solve a problem of signaling when to exit. If not coordinated, a resulting hung job looks like a failure, but in-fact was successful except one container never exited.

ko apply -f - <<EOF
apiVersion: batch/v1
kind: Job
metadata:
  name: example
spec:
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: leader
          image: ko://chainguard.dev/exitdir/cmd/leader
          env:
            - name: EXIT_DIR
              value: "/var/exitdir"
          volumeMounts:
            - name: exit-dir
              mountPath: "/var/exitdir"
        - name: follower
          image: ko://chainguard.dev/exitdir/cmd/follower
          env:
            - name: EXIT_DIR
              value: "/var/exitdir"
          volumeMounts:
            - name: exit-dir
              mountPath: "/var/exitdir"
      volumes:
        - name: exit-dir
          emptyDir: {}
EOF

We can see the job finished:

% kubectl get job
NAME      COMPLETIONS   DURATION   AGE
example   1/1           8s         17s

And finding the pod, we can view the logs of each container:

$ kubectl logs example-78fm7 leader
[Leader] Doing work...
[Leader] Exiting...
$  kubectl logs example-78fm7 follower
[Follower] Tick 0
[Follower] Tick 1
[Follower] Tick 2
[Follower] Tick 3
[Follower] Exiting...

Documentation

Overview

Example (Aware_exit)
package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"chainguard.dev/exitdir"
)

func main() {
	tempdir, err := ioutil.TempDir(os.TempDir(), "example_aware_exit*")
	if err != nil {
		log.Fatal(err)
	}
	defer os.Remove(tempdir)
	if err := os.Setenv("EXIT_DIR", tempdir); err != nil {
		panic(err)
	}

	time.Sleep(1 * time.Millisecond)

	go func() {
		ctx := exitdir.Aware(context.Background())
		ticker := time.NewTicker(5 * time.Millisecond)
		for i := 0; true; i++ {
			select {
			case <-ctx.Done():
				fmt.Println("[Follower] Exiting...")
				return
			case <-ticker.C:
				fmt.Println("[Follower] Tick", i)
			}
		}
	}()

	fmt.Println("[Leader] Doing work...")
	time.Sleep(13 * time.Millisecond)
	fmt.Println("[Leader] Exiting...")
	if err := exitdir.Exit(); err != nil {
		panic(err)
	}
	time.Sleep(1 * time.Millisecond)

}
Output:

[Leader] Doing work...
[Follower] Tick 0
[Follower] Tick 1
[Leader] Exiting...
[Follower] Exiting...

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Aware

func Aware(ctx context.Context) context.Context

Aware watches for an exitFile and will cancel the returned context if `EXIT_DIR` has been set on the environment, otherwise context is returned.

func Exit

func Exit() error

Exit creates an exitFile if `EXIT_DIR` has been set on the environment.

Types

This section is empty.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL