Skip to content

Instantly share code, notes, and snippets.

@wsong
Last active October 4, 2017 21:51
Show Gist options
  • Save wsong/129690610bf58bad6c241e1598c9d6d6 to your computer and use it in GitHub Desktop.
Save wsong/129690610bf58bad6c241e1598c9d6d6 to your computer and use it in GitHub Desktop.
Task cleaner for Swarmkit
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/ca"
"github.com/docker/swarmkit/manager"
"google.golang.org/grpc"
)
func main() {
if len(os.Args) < 2 {
fmt.Printf("must pass in node address with port (e.g. 123.123.123.123:2377) as the first argument")
return
}
dryRun := false
if len(os.Args) > 2 && os.Args[2] == "--dry-run" {
fmt.Printf("Performing a dry run\n\n")
dryRun = true
}
nodeCertPaths := ca.CertPaths{
Cert: "/var/lib/docker/swarm/certificates/swarm-node.crt",
Key: "/var/lib/docker/swarm/certificates/swarm-node.key",
}
certPaths := ca.CertPaths{
Cert: "/var/lib/docker/swarm/certificates/swarm-root-ca.crt",
Key: "/var/lib/docker/swarm/certificates/swarm-root-ca.key",
}
rootCA, err := ca.GetLocalRootCA(certPaths)
if err != nil {
fmt.Printf("could not load CA: %s\n", err)
return
}
var unlockKey []byte
krw := ca.NewKeyReadWriter(nodeCertPaths, unlockKey, &manager.RaftDEKData{})
securityConfig, err := ca.LoadSecurityConfig(context.TODO(), rootCA, krw, false)
if err != nil {
fmt.Printf("could not load security config: %s\n", err)
return
}
grpcOptions := []grpc.DialOption{
grpc.WithBackoffMaxDelay(8 * time.Second),
grpc.WithTransportCredentials(securityConfig.ClientTLSCreds),
grpc.WithTimeout(2 * time.Second),
}
cc, err := grpc.Dial(os.Args[1], grpcOptions...)
if err != nil {
fmt.Printf("failed to dial to grpc: %s\n", err)
return
}
controlClient := api.NewControlClient(cc)
r, err := controlClient.ListTasks(context.TODO(), &api.ListTasksRequest{})
if err != nil {
fmt.Printf("failed to list tasks: %s\n", err)
return
}
targetStates := []api.TaskState{
api.TaskStateShutdown,
api.TaskStateFailed,
api.TaskStateRejected,
api.TaskStateOrphaned,
}
for _, task := range r.Tasks {
isInTargetState := false
for _, s := range targetStates {
if task.Status.State == s {
isInTargetState = true
break
}
}
if !isInTargetState {
continue
}
if dryRun {
fmt.Printf("DRY RUN: Removing task %s in state %s\n", task.ID, task.Status.State)
} else {
fmt.Printf("Removing task %s in state %s\n", task.ID, task.Status.State)
_, err := controlClient.RemoveTask(context.TODO(), &api.RemoveTaskRequest{TaskID: task.ID})
if err != nil {
fmt.Printf("failed to remove task %s: %s\n", task.ID, err)
return
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment