Skip to content

Commit

Permalink
Merge pull request #34 from thisisommore/thisisommore/issue23
Browse files Browse the repository at this point in the history
Gracefully reconnect to socket on error, fix #23
  • Loading branch information
shinebayar-g authored Nov 3, 2021
2 parents ec45d84 + 45b355e commit 461dce7
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os/exec"
"strconv"
"strings"
"time"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
Expand Down Expand Up @@ -126,18 +127,27 @@ func handleUfwRule(ch <-chan ufwEvent) {
}
}

func main() {
ctx := context.Background()
func createClient() *client.Client {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
panic(err)
}
return cli
}

func addFilters(cli *client.Client, ctx *context.Context) (<-chan events.Message, <-chan error) {
_, cancelContext := context.WithCancel(*ctx)
cancelContext()
filter := filters.NewArgs()
filter.Add("type", "container")
filter.Add("type", "network")
return cli.Events(*ctx, types.EventsOptions{Filters: filter})
}

messages, errors := cli.Events(ctx, types.EventsOptions{Filters: filter})
func main() {
cli := createClient()
ctx := context.Background()
messages, errors := addFilters(cli, &ctx)

ch := make(chan ufwEvent)
go handleUfwRule(ch)
Expand All @@ -160,6 +170,10 @@ func main() {
case err := <-errors:
if err != nil {
fmt.Println("ufw-docker-automated: Received an error:", err)
time.Sleep(3 * time.Second)
fmt.Println("ufw-docker-automated: reconnecing")
cli = createClient()
messages, errors = addFilters(cli, &ctx)
}
}
}
Expand Down

0 comments on commit 461dce7

Please sign in to comment.