Skip to content

Commit

Permalink
use zerolog to implement log levels
Browse files Browse the repository at this point in the history
  • Loading branch information
shinebayar-g committed Jan 27, 2023
1 parent bf31f76 commit 0ecd17c
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 46 deletions.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.19
require (
github.com/docker/docker v20.10.23+incompatible
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/rs/zerolog v1.29.0
)

require (
Expand All @@ -14,6 +15,8 @@ require (
github.com/docker/go-units v0.5.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/moby/term v0.0.0-20221105221325-4eb28fa6025c // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
Expand Down
23 changes: 15 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,26 +1,33 @@
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg=
github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE=
github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68=
github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v20.10.21+incompatible h1:UTLdBmHk3bEY+w8qeO5KttOhy6OmXWsl/FEet9Uswog=
github.com/docker/docker v20.10.21+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker v20.10.23+incompatible h1:1ZQUUYAdh+oylOT85aA2ZcfRp22jmLhoaEcVEfK8dyA=
github.com/docker/docker v20.10.23+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/moby/term v0.0.0-20221105221325-4eb28fa6025c h1:RC8WMpjonrBfyAh6VN/POIPtYD5tRAq0qMqCRjQNK+g=
github.com/moby/term v0.0.0-20221105221325-4eb28fa6025c/go.mod h1:9OcmHNQQUTbk4XCffrLgN1NEKc2mh5u++biHVrvHsSU=
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
Expand All @@ -36,6 +43,9 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w=
github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
Expand All @@ -56,8 +66,6 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU=
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw=
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand All @@ -67,9 +75,10 @@ golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand All @@ -81,8 +90,6 @@ golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgw
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.3.0 h1:SrNbZl6ECOS1qFzgTdQfWXZM9XBkiA6tkFrH9YSTPHM=
golang.org/x/tools v0.3.0/go.mod h1:/rWhSS2+zyEVwoJf8YAX6L2f0ntZ7Kn/mGgAWcipA5k=
golang.org/x/tools v0.5.0 h1:+bSpV5HIeWkuvgaMfI3UmKRThoTA5ODJTUd8T17NO+4=
golang.org/x/tools v0.5.0/go.mod h1:N+Kgy78s5I24c24dU8OfWNEotWjutIs8SnJvn5IDq+k=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
Expand Down
36 changes: 36 additions & 0 deletions logger/setup.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package logger

import (
"os"
"strconv"
"time"

"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

func SetupLogger() {
zerolog.CallerMarshalFunc = func(pc uintptr, file string, line int) string {
short := file
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
short = file[i+1:]
break
}
}
file = short
return file + ":" + strconv.Itoa(line)
}
log.Logger = log.With().Caller().Logger().Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339})
var logLevel zerolog.Level
logLevelEnv := os.Getenv("LOG_LEVEL")
var err error
if logLevelEnv != "" {
logLevel, err = zerolog.ParseLevel(logLevelEnv)
}
if err != nil {
log.Error().Err(err).Msg("couldn't parse LOG_LEVEL.")
logLevel = zerolog.InfoLevel
}
zerolog.SetGlobalLevel(logLevel)
}
16 changes: 9 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"context"
"log"
"time"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/events"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/patrickmn/go-cache"
"github.com/rs/zerolog/log"
"github.com/shinebayar-g/ufw-docker-automated/logger"
"github.com/shinebayar-g/ufw-docker-automated/ufwhandler"
)

Expand All @@ -36,23 +37,24 @@ func reconnect() (*context.Context, *client.Client) {
var err error
for {
time.Sleep(5 * time.Second)
log.Println("ufw-docker-automated: Trying to reconnect..")
log.Info().Msg("ufw-docker-automated: Trying to reconnect..")
ctx, client, err = createClient()
if err == nil {
break
}
}
log.Println("ufw-docker-automated: Reconnected to the Docker Engine.")
log.Info().Msg("ufw-docker-automated: Reconnected to the Docker Engine.")
return ctx, client
}

func main() {
logger.SetupLogger()
ctx, client, err := createClient()
if err != nil {
log.Println("ufw-docker-automated: Client error:", err)
log.Error().Err(err).Msg("ufw-docker-automated: Client error.")
ctx, client = reconnect()
} else {
log.Println("ufw-docker-automated: Connected to the Docker Engine.")
log.Info().Msg("ufw-docker-automated: Connected to the Docker Engine.")
}
createChannel := make(chan *types.ContainerJSON)
deleteChannel := make(chan string)
Expand All @@ -70,7 +72,7 @@ func main() {
if msg.Action == "start" {
container, err := client.ContainerInspect(*ctx, msg.ID)
if err != nil {
log.Println("ufw-docker-automated: Couldn't inspect container:", err)
log.Error().Err(err).Msg("ufw-docker-automated: Couldn't inspect container.")
continue
}
createChannel <- &container
Expand All @@ -80,7 +82,7 @@ func main() {
}
case err := <-errors:
if err != nil {
log.Println("ufw-docker-automated: Event error:", err)
log.Error().Err(err).Msg("ufw-docker-automated: Event error.")
ctx, client = reconnect()
go ufwhandler.Sync(ctx, createChannel, client)
messages, errors = streamEvents(ctx, client)
Expand Down
12 changes: 6 additions & 6 deletions ufwhandler/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import (
"bufio"
"bytes"
"context"
"log"
"os/exec"
"regexp"
"strings"

"github.com/docker/docker/client"
"github.com/rs/zerolog/log"
)

func isValidRule(rule string) bool {
Expand All @@ -30,7 +30,7 @@ func Cleanup(ctx *context.Context, client *client.Client) {
err := cmd.Run()

if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
log.Error().Err(err).Msg("ufw error: " + stderr.String())
} else {
scanner := bufio.NewScanner(strings.NewReader(stdout.String()))
for scanner.Scan() {
Expand All @@ -52,7 +52,7 @@ func Cleanup(ctx *context.Context, client *client.Client) {
for containerID, rules := range ufwRuleMap {
container, err := client.ContainerInspect(*ctx, containerID)
if err != nil || !container.State.Running {
log.Println("ufw-docker-automated: ContainerID='" + containerID + "' doesn't seem to be running. Cleaning up ufw rules.")
log.Error().Err(err).Msg("ufw-docker-automated: ContainerID='" + containerID + "' doesn't seem to be running. Cleaning up ufw rules.")
clean(rules)
}
}
Expand All @@ -61,17 +61,17 @@ func Cleanup(ctx *context.Context, client *client.Client) {
func clean(rules []string) {
for _, rule := range rules {
cmd := exec.Command("sh", "-c", "sudo ufw route delete "+rule[10:]) // trimming first couple of words "ufw route " to fit delete command
log.Println("ufw-docker-automated: Deleting rule:", rule)
log.Info().Msg("ufw-docker-automated: Deleting rule: " + rule)

var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()

if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
log.Error().Err(err).Msg("ufw error: " + stderr.String())
} else {
log.Println("ufw:", stdout.String())
log.Info().Msg("ufw: " + stdout.String())
}
}
}
Expand Down
22 changes: 11 additions & 11 deletions ufwhandler/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ package ufwhandler
import (
"bytes"
"fmt"
"log"
"net"
"os/exec"
"strconv"
"strings"

"github.com/docker/docker/api/types"
"github.com/patrickmn/go-cache"
"github.com/rs/zerolog/log"
)

func checkIP(ip string) bool {
Expand All @@ -33,7 +33,7 @@ func CreateUfwRule(ch <-chan *types.ContainerJSON, c *cache.Cache) {
if ip, ok := container.NetworkSettings.Networks[networkMode]; ok {
containerIP = ip.IPAddress
} else {
log.Println("ufw-docker-automated: Couldn't detect the container IP address.")
log.Error().Msg("ufw-docker-automated: Couldn't detect the container IP address.")
continue
}
}
Expand Down Expand Up @@ -88,17 +88,17 @@ func CreateUfwRule(ch <-chan *types.ContainerJSON, c *cache.Cache) {

for _, rule := range ufwRules {
cmd := exec.Command("sudo", "ufw", "route", "allow", "proto", rule.Proto, "from", rule.CIDR, "to", containerIP, "port", rule.Port, "comment", containerName+":"+containerID+rule.Comment)
log.Println("ufw-docker-automated: Adding inbound rule:", cmd)
log.Info().Msg("ufw-docker-automated: Adding inbound rule: " + cmd.String())

var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()

if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
log.Error().Err(err).Msg("ufw error: " + stderr.String())
} else {
log.Println("ufw:", stdout.String())
log.Info().Msg("ufw: " + stdout.String())
}
}

Expand Down Expand Up @@ -154,17 +154,17 @@ func CreateUfwRule(ch <-chan *types.ContainerJSON, c *cache.Cache) {
} else {
cmd = exec.Command("sudo", "ufw", "route", "allow", "from", containerIP, "to", rule.CIDR, "port", rule.Port, "comment", containerName+":"+containerID+rule.Comment)
}
log.Println("ufw-docker-automated: Adding outbound rule:", cmd)
log.Info().Msg("ufw-docker-automated: Adding outbound rule: " + cmd.String())

var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()

if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
log.Error().Err(err).Msg("ufw error: " + stderr.String())
} else {
log.Println("ufw:", stdout.String())
log.Info().Msg("ufw: " + stdout.String())
}
}

Expand All @@ -173,17 +173,17 @@ func CreateUfwRule(ch <-chan *types.ContainerJSON, c *cache.Cache) {

// Handle deny all out
cmd := exec.Command("sudo", "ufw", "route", "deny", "from", containerIP, "to", "any", "comment", containerName+":"+containerID)
log.Println("ufw-docker-automated: Adding outbound rule:", cmd)
log.Info().Msg("ufw-docker-automated: Adding outbound rule: " + cmd.String())

var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()

if err != nil || stderr.String() != "" {
log.Println("ufw error:", err, stderr.String())
log.Error().Err(err).Msg("ufw error: " + stderr.String())
} else {
log.Println("ufw:", stdout.String())
log.Info().Msg("ufw: " + stdout.String())
}
}
}
Expand Down
Loading

0 comments on commit 0ecd17c

Please sign in to comment.