Last active
March 13, 2017 14:24
-
-
Save deedubs/c1a6a978764ae45149f380734dd5987d to your computer and use it in GitHub Desktop.
This small CLI tool runs over all the files in a directory, looks at there contents, and checks for a corresponding running docker container. If it doesn't exist the file is removed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"flag" | |
"io/ioutil" | |
"log" | |
"os" | |
"path" | |
"regexp" | |
"fmt" | |
"github.com/docker/docker/api/types" | |
"github.com/docker/docker/client" | |
) | |
var cniPath *string | |
func main() { | |
cniPath = flag.String("cni.path", "./test", "Path to lookup CNI IP Assigments") | |
flag.Parse() | |
cli, err := client.NewEnvClient() | |
if err != nil { | |
log.Fatal("Unable to connect to docker agent", err.Error()) | |
} | |
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{Quiet: true}) | |
if err != nil { | |
log.Fatal("Unable to list Containers", err.Error()) | |
} | |
assignmentFiles, err := ioutil.ReadDir(*cniPath) | |
if err != nil { | |
log.Fatal("Unable to list assigned IPs", err.Error()) | |
} | |
for _, assignment := range assignmentFiles { | |
assignmentFile := assignment.Name() | |
assignmentFileContents, err := ioutil.ReadFile(path.Join(*cniPath, assignmentFile)) | |
if err != nil { | |
log.Fatal("Unable to open assignment file", err.Error()) | |
} | |
isIPAddress, err := regexp.MatchString("\\d+.\\d+.\\d+.\\d+", assignmentFile) | |
if isIPAddress != true { | |
continue | |
} | |
containerID := string(assignmentFileContents) | |
for _, container := range containers { | |
if container.ID == containerID { | |
fmt.Println("Container found. Assignment active") | |
} else { | |
fmt.Println("Container " + containerID + " not found. Removing assigned IP") | |
os.Remove(path.Join(*cniPath, assignmentFile)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment