Skip to content

Commit

Permalink
Add support for parent directory expiration
Browse files Browse the repository at this point in the history
  • Loading branch information
monder committed Aug 15, 2016
1 parent a28332e commit 35ee9ec
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ var flags struct {
etcdAddress string
cidr string
format string
expireDir string
interval time.Duration
}

func init() {
pflag.StringVarP(&flags.etcdAddress, "etcd-endpoint", "e", "http://172.16.28.1:2379", "an etcd address in the cluster")
pflag.StringVar(&flags.cidr, "cidr", "0.0.0.0/0", "cidr to match the ip")
pflag.StringVarP(&flags.format, "format", "f", "$ip", "format of the etcd key value. '$ip' will be replace by container's ip address")
pflag.StringVar(&flags.expireDir, "expireDir", "", "set expiration TTLs for all items under that directory, not only the leaf node")
pflag.DurationVarP(&flags.interval, "interval", "i", time.Minute, "refresh interval")
pflag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage:\n %s /key/in/etcd\n\nFlags:\n", os.Args[0])
Expand Down Expand Up @@ -53,21 +55,49 @@ func main() {

value := strings.Replace(flags.format, "$ip", ip, -1)

_, err = etcd.Set(context.Background(), pflag.Arg(0), value, &client.SetOptions{TTL: 2 * flags.interval})
_, err = etcd.Set(context.Background(), pflag.Arg(0), value, &client.SetOptions{})
if err != nil {
log.Fatal(err)
}

ticker := time.NewTicker(flags.interval)

for {
_, err = etcd.Set(context.Background(), pflag.Arg(0), "", &client.SetOptions{Refresh: true, TTL: 2 * flags.interval})
if err != nil {
log.Fatal(err)
path := pflag.Arg(0)
keepRoot := flags.expireDir
if keepRoot == "" {
keepRoot = path[0:strings.LastIndex(path, "/")]
}
if !strings.HasSuffix(keepRoot, "/") {
keepRoot += "/"
}
currentPath := "/"
if strings.HasPrefix(path, keepRoot) {
path = path[len(keepRoot):]
currentPath = keepRoot
} else {
keepRoot = currentPath
path = path[len(currentPath):]
}

for _, s := range strings.SplitAfter(path, "/") {
currentPath += s
fmt.Printf("Setting ttl for %s (dir: %s)\n", currentPath, strings.HasSuffix(currentPath, "/"))
_, err = etcd.Set(context.Background(), currentPath, "", &client.SetOptions{
Refresh: true,
PrevExist: client.PrevExist,
TTL: 2 * flags.interval,
Dir: strings.HasSuffix(currentPath, "/"),
})
if err != nil {
log.Fatal(err)
}
}

select {
case <-sigc:
etcd.Delete(context.Background(), pflag.Arg(0), nil)
//TODO clear empty dirs
os.Exit(0)
case <-ticker.C:
}
Expand Down

0 comments on commit 35ee9ec

Please sign in to comment.