diff --git a/go.mod b/go.mod index 812b3446d..68d0d5007 100644 --- a/go.mod +++ b/go.mod @@ -6,12 +6,12 @@ require ( github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 github.com/cilium/ipam v0.0.0-20220824141044-46ef3d556735 github.com/go-faker/faker/v4 v4.2.0 - github.com/go-kit/log v0.2.1 github.com/go-logr/logr v1.3.0 github.com/go-swagger/go-swagger v0.30.4 github.com/google/gops v0.3.27 github.com/google/uuid v1.4.0 github.com/gorilla/websocket v1.5.1 + github.com/grafana/pyroscope-go v1.0.4 github.com/mdlayher/arp v0.0.0-20220221190821-c37aaafac7f9 github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 github.com/mdlayher/ndp v0.0.0-20200602162440-17ab9e3e5567 @@ -21,7 +21,6 @@ require ( github.com/onsi/gomega v1.30.0 github.com/pkg/errors v0.9.1 github.com/prometheus/client_golang v1.17.0 - github.com/pyroscope-io/client v0.7.1 github.com/sasha-s/go-deadlock v0.3.1 github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.8.0 @@ -58,7 +57,6 @@ require ( github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.3 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect - github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/go-logr/zapr v1.2.4 // indirect github.com/go-openapi/analysis v0.21.4 // indirect github.com/go-openapi/errors v0.20.4 // indirect @@ -79,8 +77,9 @@ require ( github.com/google/gnostic-models v0.6.8 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/gofuzz v1.2.0 // indirect - github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 // indirect + github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a // indirect github.com/gorilla/handlers v1.5.1 // indirect + github.com/grafana/pyroscope-go/godeltaprof v0.1.4 // indirect github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/huandu/xstrings v1.4.0 // indirect @@ -113,7 +112,6 @@ require ( github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 // indirect github.com/prometheus/common v0.44.0 // indirect github.com/prometheus/procfs v0.11.1 // indirect - github.com/pyroscope-io/godeltaprof v0.1.0 // indirect github.com/rogpeppe/go-internal v1.10.0 // indirect github.com/sagikazarmark/locafero v0.3.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect diff --git a/go.sum b/go.sum index 6f65985ac..4f2212b47 100644 --- a/go.sum +++ b/go.sum @@ -120,10 +120,6 @@ github.com/go-faker/faker/v4 v4.2.0/go.mod h1:F/bBy8GH9NxOxMInug5Gx4WYeG6fHJZ8Ol github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= -github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= -github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA= -github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -285,8 +281,8 @@ github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a h1:fEBsGL/sjAuJrgah5XqmmYsTLzJp/TO9Lhy39gkverk= +github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -303,6 +299,10 @@ github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB7 github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/grafana/pyroscope-go v1.0.4 h1:oyQX0BOkL+iARXzHuCdIF5TQ7/sRSel1YFViMHC7Bm0= +github.com/grafana/pyroscope-go v1.0.4/go.mod h1:0d7ftwSMBV/Awm7CCiYmHQEG8Y44Ma3YSjt+nWcWztY= +github.com/grafana/pyroscope-go/godeltaprof v0.1.4 h1:mDsJ3ngul7UfrHibGQpV66PbZ3q1T8glz/tK3bQKKEk= +github.com/grafana/pyroscope-go/godeltaprof v0.1.4/go.mod h1:1HSPtjU8vLG0jE9JrTdzjgFqdJ/VgN7fvxBNq3luJko= github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= @@ -452,10 +452,6 @@ github.com/prometheus/common v0.44.0 h1:+5BrQJwiBB9xsMygAB3TNvpQKOwlkc25LbISbrdO github.com/prometheus/common v0.44.0/go.mod h1:ofAIvZbQ1e/nugmZGz4/qCb9Ap1VoSTIO7x0VV9VvuY= github.com/prometheus/procfs v0.11.1 h1:xRC8Iq1yyca5ypa9n1EZnWZkt7dwcoRPQwX/5gwaUuI= github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/y0/p/ScXhY= -github.com/pyroscope-io/client v0.7.1 h1:yFRhj3vbgjBxehvxQmedmUWJQ4CAfCHhn+itPsuWsHw= -github.com/pyroscope-io/client v0.7.1/go.mod h1:4h21iOU4pUOq0prKyDlvYRL+SCKsBc5wKiEtV+rJGqU= -github.com/pyroscope-io/godeltaprof v0.1.0 h1:UBqtjt0yZi4jTxqZmLAs34XG6ycS3vUTlhEUSq4NHLE= -github.com/pyroscope-io/godeltaprof v0.1.0/go.mod h1:psMITXp90+8pFenXkKIpNhrfmI9saQnPbba27VIaiQE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= diff --git a/pkg/agent/eip.go b/pkg/agent/eip.go index 495a4a0a5..bec87a4d1 100644 --- a/pkg/agent/eip.go +++ b/pkg/agent/eip.go @@ -70,8 +70,7 @@ func (r *eip) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.R // newEipCtrl return a new egress ip controller func newEipCtrl(mgr manager.Manager, log logr.Logger, cfg *config.Config) error { - lw := logWrapper{log: log} - an, err := layer2.New(lw, cfg.FileConfig.AnnounceExcludeRegexp) + an, err := layer2.New(log, cfg.FileConfig.AnnounceExcludeRegexp) if err != nil { return err } @@ -95,44 +94,3 @@ func newEipCtrl(mgr manager.Manager, log logr.Logger, cfg *config.Config) error return nil } - -type logWrapper struct { - log logr.Logger -} - -func (lw logWrapper) Log(keyVals ...interface{}) error { - fields := make([]interface{}, 0, len(keyVals)/2) - var msgValue interface{} - var kind string - for i := 0; i < len(keyVals); i += 2 { - key, ok := keyVals[i].(string) - if !ok { - key = fmt.Sprintf("%v", keyVals[i]) - } - if key == "msg" { - msgValue = keyVals[i+1] - } else if key == "level" { - kind = fmt.Sprintf("%v", keyVals[i+1]) - } else { - fields = append(fields, key, keyVals[i+1]) - } - } - - var msg string - if msgValue != nil { - msg = fmt.Sprintf("%v", msgValue) - } - - switch kind { - case "debug": - lw.log.V(1).Info(msg, fields...) - case "warn": - lw.log.Info(msg, fields...) - case "error": - lw.log.Error(fmt.Errorf(msg), "", fields...) - default: - lw.log.Info(msg, fields...) - } - - return nil -} diff --git a/pkg/agent/police.go b/pkg/agent/police.go index 8189a378d..b2b50c7b4 100644 --- a/pkg/agent/police.go +++ b/pkg/agent/police.go @@ -184,26 +184,32 @@ func (r *policeReconciler) initApplyPolicy() error { } for _, table := range r.mangleTables { + table.UpdateChain(&iptables.Chain{Name: "EGRESSGATEWAY-REPLY-ROUTING"}) table.UpdateChain(&iptables.Chain{Name: "EGRESSGATEWAY-MARK-REQUEST"}) - chainMapRules := buildMangleStaticRule(baseMark) + chainMapRules := buildMangleStaticRule( + baseMark, + isEgressNode, + r.cfg.FileConfig.EnableGatewayReplyRoute, + uint32(r.cfg.FileConfig.GatewayReplyRouteMark), + ) for chain, rules := range chainMapRules { table.InsertOrAppendRules(chain, rules) } } // add forward rules for replay packet on gateway node, which should be enabled for spiderpool - if isEgressNode && r.cfg.FileConfig.EnableGatewayReplyRoute { - gatewayReplyRouteMark := r.cfg.FileConfig.GatewayReplyRouteMark - dev := r.cfg.FileConfig.VXLAN.Name - - for _, table := range r.mangleTables { - table.UpdateChain(&iptables.Chain{Name: "EGRESSGATEWAY-REPLY-ROUTING"}) - chainMapRules := buildReplyRouteIptables(uint32(gatewayReplyRouteMark), dev) - for chain, rules := range chainMapRules { - table.InsertOrAppendRules(chain, rules) - } - } - } + //if isEgressNode && r.cfg.FileConfig.EnableGatewayReplyRoute { + // gatewayReplyRouteMark := r.cfg.FileConfig.GatewayReplyRouteMark + // dev := r.cfg.FileConfig.VXLAN.Name + // + // for _, table := range r.mangleTables { + // table.UpdateChain(&iptables.Chain{Name: "EGRESSGATEWAY-REPLY-ROUTING"}) + // chainMapRules := buildReplyRouteIptables(uint32(gatewayReplyRouteMark), dev) + // for chain, rules := range chainMapRules { + // table.InsertOrAppendRules(chain, rules) + // } + // } + //} for _, table := range r.mangleTables { rules := make([]iptables.Rule, 0) @@ -236,6 +242,11 @@ func (r *policeReconciler) initApplyPolicy() error { Name: "EGRESSGATEWAY-MARK-REQUEST", Rules: rules, }) + table.UpdateChain(&iptables.Chain{ + Name: "EGRESSGATEWAY-REPLY-ROUTING", + Rules: buildPreroutingReplyRouting(r.cfg.FileConfig.VXLAN.Name, + uint32(r.cfg.FileConfig.GatewayReplyRouteMark)), + }) } for _, table := range r.natTables { @@ -741,36 +752,40 @@ func buildFilterStaticRule(base uint32) map[string][]iptables.Rule { return res } -func buildMangleStaticRule(base uint32) map[string][]iptables.Rule { - res := map[string][]iptables.Rule{ - "FORWARD": {{ +func buildMangleStaticRule(base uint32, + isEgressNode bool, + enableGatewayReplyRoute bool, replyMark uint32) map[string][]iptables.Rule { + + forward := []iptables.Rule{ + { Match: iptables.MatchCriteria{}.MarkMatchesWithMask(base, 0xff000000), Action: iptables.SetMaskedMarkAction{Mark: base, Mask: 0xffffffff}, Comment: []string{ "Accept for egress traffic from pod going to EgressTunnel", }, - }}, - "POSTROUTING": {{ - Match: iptables.MatchCriteria{}.MarkMatchesWithMask(base, 0xffffffff), - Action: iptables.AcceptAction{}, - Comment: []string{ - "Accept for egress traffic from pod going to EgressTunnel", - }, - }}, - "PREROUTING": {{ + }, + } + + postrouting := []iptables.Rule{{ + Match: iptables.MatchCriteria{}.MarkMatchesWithMask(base, 0xffffffff), + Action: iptables.AcceptAction{}, + Comment: []string{ + "Accept for egress traffic from pod going to EgressTunnel", + }, + }} + + prerouting := []iptables.Rule{ + { Match: iptables.MatchCriteria{}, Action: iptables.JumpAction{Target: "EGRESSGATEWAY-MARK-REQUEST"}, Comment: []string{ "Checking for EgressPolicy matched traffic", }, - }}, + }, } - return res -} -func buildReplyRouteIptables(base uint32, dev string) map[string][]iptables.Rule { - res := map[string][]iptables.Rule{ - "PREROUTING": { + if isEgressNode && enableGatewayReplyRoute { + prerouting = []iptables.Rule{ { Match: iptables.MatchCriteria{}, Action: iptables.JumpAction{Target: "EGRESSGATEWAY-REPLY-ROUTING"}, @@ -778,42 +793,57 @@ func buildReplyRouteIptables(base uint32, dev string) map[string][]iptables.Rule "egressGateway Reply datapath rule, rule is from the EgressGateway", }, }, - }, - "EGRESSGATEWAY-REPLY-ROUTING": { - { - Match: iptables.MatchCriteria{}.InInterface(dev), - Action: iptables.SetMaskedMarkAction{Mark: base, Mask: 0xffffffff}, - Comment: []string{ - "mark the traffic from the EgressGateway tunnel, rule is from the EgressGateway", - }, - }, - { - Match: iptables.MatchCriteria{}.MarkMatchesWithMask(base, 0xffffffff), - Action: iptables.SaveConnMarkAction{SaveMask: base}, - Comment: []string{ - "save mark to the connection, rule is from the EgressGateway", - }, - }, { - Match: iptables.MatchCriteria{}.ConntrackState("ESTABLISHED"), - Action: iptables.RestoreConnMarkAction{RestoreMask: 0}, + Match: iptables.MatchCriteria{}, + Action: iptables.JumpAction{Target: "EGRESSGATEWAY-MARK-REQUEST"}, Comment: []string{ - "label for restoring connections, rule is from the EgressGateway", + "Checking for EgressPolicy matched traffic", }, }, - }, - "POSTROUTING": {{ - Match: iptables.MatchCriteria{}.MarkMatchesWithMask(base, 0xffffffff), + } + postrouting = append(postrouting, iptables.Rule{ + Match: iptables.MatchCriteria{}.MarkMatchesWithMask(replyMark, 0xffffffff), Action: iptables.SetMaskedMarkAction{Mark: 0x00000000, Mask: 0xffffffff}, Comment: []string{ "clear the Mark of the inner package, rule is from the EgressGateway", }, - }}, + }) } + res := map[string][]iptables.Rule{ + "FORWARD": forward, + "POSTROUTING": postrouting, + "PREROUTING": prerouting, + } return res } +func buildPreroutingReplyRouting(vxlanName string, replyMark uint32) []iptables.Rule { + return []iptables.Rule{ + { + Match: iptables.MatchCriteria{}.InInterface(vxlanName), + Action: iptables.SetMaskedMarkAction{Mark: replyMark, Mask: 0xffffffff}, + Comment: []string{ + "mark the traffic from the EgressGateway tunnel, rule is from the EgressGateway", + }, + }, + { + Match: iptables.MatchCriteria{}.MarkMatchesWithMask(replyMark, 0xffffffff), + Action: iptables.SaveConnMarkAction{SaveMask: replyMark}, + Comment: []string{ + "save mark to the connection, rule is from the EgressGateway", + }, + }, + { + Match: iptables.MatchCriteria{}.ConntrackState("ESTABLISHED"), + Action: iptables.RestoreConnMarkAction{RestoreMask: 0}, + Comment: []string{ + "label for restoring connections, rule is from the EgressGateway", + }, + }, + } +} + // reconcilePolicy reconcile egress policy // watch update/delete events // - ipset diff --git a/pkg/layer2/announcer.go b/pkg/layer2/announcer.go index 1d8d4096f..f77b30089 100644 --- a/pkg/layer2/announcer.go +++ b/pkg/layer2/announcer.go @@ -6,6 +6,9 @@ // https://github.com/metallb/metallb // SPDX-License-Identifier:Apache-2.0 +// Changes: +// * replace logger library + package layer2 import ( @@ -15,15 +18,14 @@ import ( "strconv" "time" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "github.com/go-logr/logr" "github.com/spidernet-io/egressgateway/pkg/lock" ) // Announce is used to "announce" new IPs mapped to the node's MAC address. type Announce struct { - logger log.Logger + logger logr.Logger lock.RWMutex nodeInterfaces []string // current local interfaces' name list @@ -39,7 +41,7 @@ type Announce struct { } // New returns an initialized Announce. -func New(l log.Logger, excludeRegexp *regexp.Regexp) (*Announce, error) { +func New(l logr.Logger, excludeRegexp *regexp.Regexp) (*Announce, error) { ret := &Announce{ logger: l, nodeInterfaces: []string{}, @@ -65,12 +67,12 @@ func (a *Announce) interfaceScan() { } // updateInterfaces is used to scan network interfaces, update the arps and ndps lists in -// the Announce object to respond to ARP and NDP requests, and exclude some unnecessary +// the Announcement object to respond to ARP and NDP requests, and exclude some unnecessary // interfaces. func (a *Announce) updateInterfaces() { ifs, err := net.Interfaces() if err != nil { - level.Error(a.logger).Log("op", "getInterfaces", "error", err, "msg", "couldn't list interfaces") + a.logger.Error(err, "couldn't list interfaces", "op", "getInterfaces") return } @@ -83,15 +85,17 @@ func (a *Announce) updateInterfaces() { ifi := intf if (a.excludeRegexp != nil) && a.excludeRegexp.MatchString(ifi.Name) { - level.Debug(a.logger).Log("event", "announced interface to exclude", "interface", ifi.Name) + a.logger.V(1).Info("announced interface to exclude interface", "interface", ifi.Name) continue } curIfs = append(curIfs, ifi.Name) - l := log.With(a.logger, "interface", ifi.Name) + + l := a.logger.WithValues("interface", ifi.Name) + addrs, err := ifi.Addrs() if err != nil { - level.Error(l).Log("op", "getAddresses", "error", err, "msg", "couldn't get addresses for interface") + l.Error(err, "couldn't get addresses for interface", "op", "getAddresses") return } @@ -128,20 +132,20 @@ func (a *Announce) updateInterfaces() { if keepARP[ifi.Index] && a.arps[ifi.Index] == nil { resp, err := newARPResponder(a.logger, &ifi, a.shouldAnnounce) if err != nil { - level.Error(l).Log("op", "createARPResponder", "error", err, "msg", "failed to create ARP responder") + l.Error(err, "failed to create ARP responder", "op", "createARPResponder") continue } a.arps[ifi.Index] = resp - level.Info(l).Log("event", "createARPResponder", "msg", "created ARP responder for interface") + l.Info("created ARP responder for interface", "event", "createARPResponder") } if keepNDP[ifi.Index] && a.ndps[ifi.Index] == nil { resp, err := newNDPResponder(a.logger, &ifi, a.shouldAnnounce) if err != nil { - level.Error(l).Log("op", "createNDPResponder", "error", err, "msg", "failed to create NDP responder") + l.Error(err, "failed to create NDP responder", "op", "createNDPResponder") continue } a.ndps[ifi.Index] = resp - level.Info(l).Log("event", "createNDPResponder", "msg", "created NDP responder for interface") + l.Info("created NDP responder for interface", "event", "createNDPResponder") } } @@ -151,14 +155,14 @@ func (a *Announce) updateInterfaces() { if !keepARP[i] { client.Close() delete(a.arps, i) - level.Info(a.logger).Log("interface", client.Interface(), "event", "deleteARPResponder", "msg", "deleted ARP responder for interface") + a.logger.Info("deleted ARP responder for interface", "event", "deleteARPResponder", "interface", client.Interface()) } } for i, client := range a.ndps { if !keepNDP[i] { client.Close() delete(a.ndps, i) - level.Info(a.logger).Log("interface", client.Interface(), "event", "deleteNDPResponder", "msg", "deleted NDP responder for interface") + a.logger.Info("deleted NDP responder for interface", "event", "deleteNDPResponder", "interface", client.Interface()) } } } @@ -234,21 +238,23 @@ func (a *Announce) gratuitous(adv IPAdvertisement) { if ip.To4() != nil { for _, client := range a.arps { if !adv.matchInterface(client.intf) { - level.Debug(a.logger).Log("op", "gratuitousAnnounce", "skip interfaces", client.intf) + a.logger.V(1).Info("skip interfaces", "op", "gratuitousAnnounce", "interface", client.intf) continue } if err := client.Gratuitous(ip); err != nil { - level.Error(a.logger).Log("op", "gratuitousAnnounce", "error", err, "ip", ip, "msg", "failed to make gratuitous ARP announcement") + a.logger.Error(err, "failed to make gratuitous ARP announcement", + "op", "gratuitousAnnounce", "ip", ip) } } } else { for _, client := range a.ndps { if !adv.matchInterface(client.intf) { - level.Debug(a.logger).Log("op", "gratuitousAnnounce", "skip interfaces", client.intf) + a.logger.V(1).Info("skip interfaces", "op", "gratuitousAnnounce", "interface", client.intf) continue } if err := client.Gratuitous(ip); err != nil { - level.Error(a.logger).Log("op", "gratuitousAnnounce", "error", err, "ip", ip, "msg", "failed to make gratuitous NDP announcement") + a.logger.Error(err, "failed to make gratuitous NDP announcement", + "op", "gratuitousAnnounce", "ip", ip) } } } @@ -302,7 +308,9 @@ func (a *Announce) SetBalancer(name string, adv IPAdvertisement) { for _, client := range a.ndps { if err := client.Watch(adv.ip); err != nil { - level.Error(a.logger).Log("op", "watchMulticastGroup", "error", err, "ip", adv.ip, "interface", client.intf, "msg", "failed to watch NDP multicast group for IP, NDP responder will not respond to requests for this address") + a.logger.Error(err, "failed to watch NDP multicast group for IP, NDP responder will not respond to requests for this address", + "op", "watchMulticastGroup", "ip", adv.ip, "interface", client.intf, + ) } } } @@ -328,7 +336,9 @@ func (a *Announce) DeleteBalancer(name string) { for _, client := range a.ndps { if err := client.Unwatch(cur.ip); err != nil { - level.Error(a.logger).Log("op", "unwatchMulticastGroup", "error", err, "ip", cur.ip, "interface", client.intf, "msg", "failed to unwatch NDP multicast group for IP") + a.logger.Error(err, "failed to unwatch NDP multicast group for IP", + "op", "unwatchMulticastGroup", "ip", cur.ip, "interface", client.intf, + ) } } } diff --git a/pkg/layer2/arp.go b/pkg/layer2/arp.go index 75093f5b0..1e2cd0fb9 100644 --- a/pkg/layer2/arp.go +++ b/pkg/layer2/arp.go @@ -15,8 +15,7 @@ import ( "io" "net" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "github.com/go-logr/logr" "github.com/mdlayher/arp" "github.com/mdlayher/ethernet" ) @@ -24,7 +23,7 @@ import ( type announceFunc func(net.IP, string) dropReason type arpResponder struct { - logger log.Logger + logger logr.Logger intf string hardwareAddr net.HardwareAddr conn *arp.Client @@ -32,7 +31,7 @@ type arpResponder struct { announce announceFunc } -func newARPResponder(logger log.Logger, ifi *net.Interface, ann announceFunc) (*arpResponder, error) { +func newARPResponder(logger logr.Logger, ifi *net.Interface, ann announceFunc) (*arpResponder, error) { client, err := arp.Dial(ifi) if err != nil { return nil, fmt.Errorf("creating ARP responder for %q: %s", ifi.Name, err) @@ -106,17 +105,31 @@ func (a *arpResponder) processRequest() dropReason { // Ignore ARP requests that the announcer tells us to ignore. reason := a.announce(pkt.TargetIP, a.intf) if reason == dropReasonNotMatchInterface { - level.Debug(a.logger).Log("op", "arpRequestIgnore", "ip", pkt.TargetIP, "interface", a.intf, "reason", "notMatchInterface") + a.logger.V(1).Info("ignore ARP requests", + "op", "arpRequestIgnore", "ip", pkt.TargetIP, "interface", a.intf, "reason", "notMatchInterface") } if reason != dropReasonNone { return reason } stats.GotRequest(pkt.TargetIP.String()) - level.Debug(a.logger).Log("interface", a.intf, "ip", pkt.TargetIP, "senderIP", pkt.SenderIP, "senderMAC", pkt.SenderHardwareAddr, "responseMAC", a.hardwareAddr, "msg", "got ARP request for service IP, sending response") + a.logger.V(1).Info("got ARP request for service IP, sending response", + "interface", a.intf, + "ip", pkt.TargetIP, + "senderIP", pkt.SenderIP, + "senderMAC", pkt.SenderHardwareAddr, + "responseMAC", a.hardwareAddr, + ) if err := a.conn.Reply(pkt, a.hardwareAddr, pkt.TargetIP); err != nil { - level.Error(a.logger).Log("op", "arpReply", "interface", a.intf, "ip", pkt.TargetIP, "senderIP", pkt.SenderIP, "senderMAC", pkt.SenderHardwareAddr, "responseMAC", a.hardwareAddr, "error", err, "msg", "failed to send ARP reply") + a.logger.Error(err, "failed to send ARP reply", + "op", "arpReply", + "interface", a.intf, + "ip", pkt.TargetIP, + "senderIP", pkt.SenderIP, + "senderMAC", pkt.SenderHardwareAddr, + "responseMAC", a.hardwareAddr, + ) } else { stats.SentResponse(pkt.TargetIP.String()) } diff --git a/pkg/layer2/ndp.go b/pkg/layer2/ndp.go index b2f15c8c0..feda7adf7 100644 --- a/pkg/layer2/ndp.go +++ b/pkg/layer2/ndp.go @@ -14,13 +14,12 @@ import ( "io" "net" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "github.com/go-logr/logr" "github.com/mdlayher/ndp" ) type ndpResponder struct { - logger log.Logger + logger logr.Logger intf string hardwareAddr net.HardwareAddr conn *ndp.Conn @@ -31,7 +30,7 @@ type ndpResponder struct { solicitedNodeGroups map[string]int64 } -func newNDPResponder(logger log.Logger, ifi *net.Interface, ann announceFunc) (*ndpResponder, error) { +func newNDPResponder(logger logr.Logger, ifi *net.Interface, ann announceFunc) (*ndpResponder, error) { // Use link-local address as the source IPv6 address for NDP communications. conn, _, err := ndp.Dial(ifi, ndp.LinkLocal) if err != nil { @@ -144,17 +143,16 @@ func (n *ndpResponder) processRequest() dropReason { // Ignore NDP requests that the announcer tells us to ignore. reason := n.announce(ns.TargetAddress, n.intf) if reason == dropReasonNotMatchInterface { - level.Debug(n.logger).Log("op", "ndpRequestIgnore", "ip", ns.TargetAddress, "interface", n.intf, "reason", "notMatchInterface") + n.logger.V(1).Info("ignore NDP requests", "op", "ndpRequestIgnore", "ip", ns.TargetAddress, "interface", n.intf, "reason", "notMatchInterface") } if reason != dropReasonNone { return reason } stats.GotRequest(ns.TargetAddress.String()) - level.Debug(n.logger).Log("interface", n.intf, "ip", ns.TargetAddress, "senderIP", src, "senderLLAddr", nsLLAddr, "responseMAC", n.hardwareAddr, "msg", "got NDP request for service IP, sending response") - + n.logger.V(1).Info("got NDP request for service IP, sending response", "interface", n.intf, "ip", ns.TargetAddress, "senderIP", src, "senderLLAddr", nsLLAddr, "responseMAC", n.hardwareAddr) if err := n.advertise(src, ns.TargetAddress, false); err != nil { - level.Error(n.logger).Log("op", "ndpReply", "interface", n.intf, "ip", ns.TargetAddress, "senderIP", src, "senderLLAddr", nsLLAddr, "responseMAC", n.hardwareAddr, "error", err, "msg", "failed to send ARP reply") + n.logger.Error(err, "failed to send ARP reply", "op", "ndpReply", "interface", n.intf, "ip", ns.TargetAddress, "senderIP", src, "senderLLAddr", nsLLAddr, "responseMAC", n.hardwareAddr) } else { stats.SentResponse(ns.TargetAddress.String()) } diff --git a/pkg/profiling/manager.go b/pkg/profiling/manager.go index d1b895407..9693d7382 100644 --- a/pkg/profiling/manager.go +++ b/pkg/profiling/manager.go @@ -11,7 +11,7 @@ import ( "github.com/go-logr/logr" "github.com/google/gops/agent" - "github.com/pyroscope-io/client/pyroscope" + pyroscope "github.com/grafana/pyroscope-go" ) type GoPS struct { diff --git a/vendor/github.com/go-kit/log/.gitignore b/vendor/github.com/go-kit/log/.gitignore deleted file mode 100644 index 66fd13c90..000000000 --- a/vendor/github.com/go-kit/log/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Dependency directories (remove the comment below to include it) -# vendor/ diff --git a/vendor/github.com/go-kit/log/LICENSE b/vendor/github.com/go-kit/log/LICENSE deleted file mode 100644 index bb5bdb9cb..000000000 --- a/vendor/github.com/go-kit/log/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021 Go kit - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-kit/log/README.md b/vendor/github.com/go-kit/log/README.md deleted file mode 100644 index 806779465..000000000 --- a/vendor/github.com/go-kit/log/README.md +++ /dev/null @@ -1,156 +0,0 @@ -# package log - -[![Go Reference](https://pkg.go.dev/badge/github.com/go-kit/log.svg)](https://pkg.go.dev/github.com/go-kit/log) -[![Go Report Card](https://goreportcard.com/badge/go-kit/log)](https://goreportcard.com/report/go-kit/log) -[![GitHub Actions](https://github.com/go-kit/log/actions/workflows/test.yml/badge.svg)](https://github.com/go-kit/log/actions/workflows/test.yml) -[![Coverage Status](https://coveralls.io/repos/github/go-kit/log/badge.svg?branch=main)](https://coveralls.io/github/go-kit/log?branch=main) - -`package log` provides a minimal interface for structured logging in services. -It may be wrapped to encode conventions, enforce type-safety, provide leveled -logging, and so on. It can be used for both typical application log events, -and log-structured data streams. - -## Structured logging - -Structured logging is, basically, conceding to the reality that logs are -_data_, and warrant some level of schematic rigor. Using a stricter, -key/value-oriented message format for our logs, containing contextual and -semantic information, makes it much easier to get insight into the -operational activity of the systems we build. Consequently, `package log` is -of the strong belief that "[the benefits of structured logging outweigh the -minimal effort involved](https://www.thoughtworks.com/radar/techniques/structured-logging)". - -Migrating from unstructured to structured logging is probably a lot easier -than you'd expect. - -```go -// Unstructured -log.Printf("HTTP server listening on %s", addr) - -// Structured -logger.Log("transport", "HTTP", "addr", addr, "msg", "listening") -``` - -## Usage - -### Typical application logging - -```go -w := log.NewSyncWriter(os.Stderr) -logger := log.NewLogfmtLogger(w) -logger.Log("question", "what is the meaning of life?", "answer", 42) - -// Output: -// question="what is the meaning of life?" answer=42 -``` - -### Contextual Loggers - -```go -func main() { - var logger log.Logger - logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) - logger = log.With(logger, "instance_id", 123) - - logger.Log("msg", "starting") - NewWorker(log.With(logger, "component", "worker")).Run() - NewSlacker(log.With(logger, "component", "slacker")).Run() -} - -// Output: -// instance_id=123 msg=starting -// instance_id=123 component=worker msg=running -// instance_id=123 component=slacker msg=running -``` - -### Interact with stdlib logger - -Redirect stdlib logger to Go kit logger. - -```go -import ( - "os" - stdlog "log" - kitlog "github.com/go-kit/log" -) - -func main() { - logger := kitlog.NewJSONLogger(kitlog.NewSyncWriter(os.Stdout)) - stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) - stdlog.Print("I sure like pie") -} - -// Output: -// {"msg":"I sure like pie","ts":"2016/01/01 12:34:56"} -``` - -Or, if, for legacy reasons, you need to pipe all of your logging through the -stdlib log package, you can redirect Go kit logger to the stdlib logger. - -```go -logger := kitlog.NewLogfmtLogger(kitlog.StdlibWriter{}) -logger.Log("legacy", true, "msg", "at least it's something") - -// Output: -// 2016/01/01 12:34:56 legacy=true msg="at least it's something" -``` - -### Timestamps and callers - -```go -var logger log.Logger -logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr)) -logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) - -logger.Log("msg", "hello") - -// Output: -// ts=2016-01-01T12:34:56Z caller=main.go:15 msg=hello -``` - -## Levels - -Log levels are supported via the [level package](https://godoc.org/github.com/go-kit/log/level). - -## Supported output formats - -- [Logfmt](https://brandur.org/logfmt) ([see also](https://blog.codeship.com/logfmt-a-log-format-thats-easy-to-read-and-write)) -- JSON - -## Enhancements - -`package log` is centered on the one-method Logger interface. - -```go -type Logger interface { - Log(keyvals ...interface{}) error -} -``` - -This interface, and its supporting code like is the product of much iteration -and evaluation. For more details on the evolution of the Logger interface, -see [The Hunt for a Logger Interface](http://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide#1), -a talk by [Chris Hines](https://github.com/ChrisHines). -Also, please see -[#63](https://github.com/go-kit/kit/issues/63), -[#76](https://github.com/go-kit/kit/pull/76), -[#131](https://github.com/go-kit/kit/issues/131), -[#157](https://github.com/go-kit/kit/pull/157), -[#164](https://github.com/go-kit/kit/issues/164), and -[#252](https://github.com/go-kit/kit/pull/252) -to review historical conversations about package log and the Logger interface. - -Value-add packages and suggestions, -like improvements to [the leveled logger](https://godoc.org/github.com/go-kit/log/level), -are of course welcome. Good proposals should - -- Be composable with [contextual loggers](https://godoc.org/github.com/go-kit/log#With), -- Not break the behavior of [log.Caller](https://godoc.org/github.com/go-kit/log#Caller) in any wrapped contextual loggers, and -- Be friendly to packages that accept only an unadorned log.Logger. - -## Benchmarks & comparisons - -There are a few Go logging benchmarks and comparisons that include Go kit's package log. - -- [imkira/go-loggers-bench](https://github.com/imkira/go-loggers-bench) includes kit/log -- [uber-common/zap](https://github.com/uber-common/zap), a zero-alloc logging library, includes a comparison with kit/log diff --git a/vendor/github.com/go-kit/log/doc.go b/vendor/github.com/go-kit/log/doc.go deleted file mode 100644 index f744382fe..000000000 --- a/vendor/github.com/go-kit/log/doc.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package log provides a structured logger. -// -// Structured logging produces logs easily consumed later by humans or -// machines. Humans might be interested in debugging errors, or tracing -// specific requests. Machines might be interested in counting interesting -// events, or aggregating information for off-line processing. In both cases, -// it is important that the log messages are structured and actionable. -// Package log is designed to encourage both of these best practices. -// -// Basic Usage -// -// The fundamental interface is Logger. Loggers create log events from -// key/value data. The Logger interface has a single method, Log, which -// accepts a sequence of alternating key/value pairs, which this package names -// keyvals. -// -// type Logger interface { -// Log(keyvals ...interface{}) error -// } -// -// Here is an example of a function using a Logger to create log events. -// -// func RunTask(task Task, logger log.Logger) string { -// logger.Log("taskID", task.ID, "event", "starting task") -// ... -// logger.Log("taskID", task.ID, "event", "task complete") -// } -// -// The keys in the above example are "taskID" and "event". The values are -// task.ID, "starting task", and "task complete". Every key is followed -// immediately by its value. -// -// Keys are usually plain strings. Values may be any type that has a sensible -// encoding in the chosen log format. With structured logging it is a good -// idea to log simple values without formatting them. This practice allows -// the chosen logger to encode values in the most appropriate way. -// -// Contextual Loggers -// -// A contextual logger stores keyvals that it includes in all log events. -// Building appropriate contextual loggers reduces repetition and aids -// consistency in the resulting log output. With, WithPrefix, and WithSuffix -// add context to a logger. We can use With to improve the RunTask example. -// -// func RunTask(task Task, logger log.Logger) string { -// logger = log.With(logger, "taskID", task.ID) -// logger.Log("event", "starting task") -// ... -// taskHelper(task.Cmd, logger) -// ... -// logger.Log("event", "task complete") -// } -// -// The improved version emits the same log events as the original for the -// first and last calls to Log. Passing the contextual logger to taskHelper -// enables each log event created by taskHelper to include the task.ID even -// though taskHelper does not have access to that value. Using contextual -// loggers this way simplifies producing log output that enables tracing the -// life cycle of individual tasks. (See the Contextual example for the full -// code of the above snippet.) -// -// Dynamic Contextual Values -// -// A Valuer function stored in a contextual logger generates a new value each -// time an event is logged. The Valuer example demonstrates how this feature -// works. -// -// Valuers provide the basis for consistently logging timestamps and source -// code location. The log package defines several valuers for that purpose. -// See Timestamp, DefaultTimestamp, DefaultTimestampUTC, Caller, and -// DefaultCaller. A common logger initialization sequence that ensures all log -// entries contain a timestamp and source location looks like this: -// -// logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) -// -// Concurrent Safety -// -// Applications with multiple goroutines want each log event written to the -// same logger to remain separate from other log events. Package log provides -// two simple solutions for concurrent safe logging. -// -// NewSyncWriter wraps an io.Writer and serializes each call to its Write -// method. Using a SyncWriter has the benefit that the smallest practical -// portion of the logging logic is performed within a mutex, but it requires -// the formatting Logger to make only one call to Write per log event. -// -// NewSyncLogger wraps any Logger and serializes each call to its Log method. -// Using a SyncLogger has the benefit that it guarantees each log event is -// handled atomically within the wrapped logger, but it typically serializes -// both the formatting and output logic. Use a SyncLogger if the formatting -// logger may perform multiple writes per log event. -// -// Error Handling -// -// This package relies on the practice of wrapping or decorating loggers with -// other loggers to provide composable pieces of functionality. It also means -// that Logger.Log must return an error because some -// implementations—especially those that output log data to an io.Writer—may -// encounter errors that cannot be handled locally. This in turn means that -// Loggers that wrap other loggers should return errors from the wrapped -// logger up the stack. -// -// Fortunately, the decorator pattern also provides a way to avoid the -// necessity to check for errors every time an application calls Logger.Log. -// An application required to panic whenever its Logger encounters -// an error could initialize its logger as follows. -// -// fmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger := log.LoggerFunc(func(keyvals ...interface{}) error { -// if err := fmtlogger.Log(keyvals...); err != nil { -// panic(err) -// } -// return nil -// }) -package log diff --git a/vendor/github.com/go-kit/log/json_logger.go b/vendor/github.com/go-kit/log/json_logger.go deleted file mode 100644 index d0faed4f0..000000000 --- a/vendor/github.com/go-kit/log/json_logger.go +++ /dev/null @@ -1,91 +0,0 @@ -package log - -import ( - "encoding" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type jsonLogger struct { - io.Writer -} - -// NewJSONLogger returns a Logger that encodes keyvals to the Writer as a -// single JSON object. Each log event produces no more than one call to -// w.Write. The passed Writer must be safe for concurrent use by multiple -// goroutines if the returned Logger will be used concurrently. -func NewJSONLogger(w io.Writer) Logger { - return &jsonLogger{w} -} - -func (l *jsonLogger) Log(keyvals ...interface{}) error { - n := (len(keyvals) + 1) / 2 // +1 to handle case when len is odd - m := make(map[string]interface{}, n) - for i := 0; i < len(keyvals); i += 2 { - k := keyvals[i] - var v interface{} = ErrMissingValue - if i+1 < len(keyvals) { - v = keyvals[i+1] - } - merge(m, k, v) - } - enc := json.NewEncoder(l.Writer) - enc.SetEscapeHTML(false) - return enc.Encode(m) -} - -func merge(dst map[string]interface{}, k, v interface{}) { - var key string - switch x := k.(type) { - case string: - key = x - case fmt.Stringer: - key = safeString(x) - default: - key = fmt.Sprint(x) - } - - // We want json.Marshaler and encoding.TextMarshaller to take priority over - // err.Error() and v.String(). But json.Marshall (called later) does that by - // default so we force a no-op if it's one of those 2 case. - switch x := v.(type) { - case json.Marshaler: - case encoding.TextMarshaler: - case error: - v = safeError(x) - case fmt.Stringer: - v = safeString(x) - } - - dst[key] = v -} - -func safeString(str fmt.Stringer) (s string) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { - s = "NULL" - } else { - s = fmt.Sprintf("PANIC in String method: %v", panicVal) - } - } - }() - s = str.String() - return -} - -func safeError(err error) (s interface{}) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { - s = nil - } else { - s = fmt.Sprintf("PANIC in Error method: %v", panicVal) - } - } - }() - s = err.Error() - return -} diff --git a/vendor/github.com/go-kit/log/level/doc.go b/vendor/github.com/go-kit/log/level/doc.go deleted file mode 100644 index fd681dcf9..000000000 --- a/vendor/github.com/go-kit/log/level/doc.go +++ /dev/null @@ -1,33 +0,0 @@ -// Package level implements leveled logging on top of Go kit's log package. To -// use the level package, create a logger as per normal in your func main, and -// wrap it with level.NewFilter. -// -// var logger log.Logger -// logger = log.NewLogfmtLogger(os.Stderr) -// logger = level.NewFilter(logger, level.AllowInfo()) // <-- -// logger = log.With(logger, "ts", log.DefaultTimestampUTC) -// -// It's also possible to configure log level from a string. For instance from -// a flag, environment variable or configuration file. -// -// fs := flag.NewFlagSet("myprogram") -// lvl := fs.String("log", "info", "debug, info, warn, error") -// -// var logger log.Logger -// logger = log.NewLogfmtLogger(os.Stderr) -// logger = level.NewFilter(logger, level.Allow(level.ParseDefault(*lvl, level.InfoValue()))) // <-- -// logger = log.With(logger, "ts", log.DefaultTimestampUTC) -// -// Then, at the callsites, use one of the level.Debug, Info, Warn, or Error -// helper methods to emit leveled log events. -// -// logger.Log("foo", "bar") // as normal, no level -// level.Debug(logger).Log("request_id", reqID, "trace_data", trace.Get()) -// if value > 100 { -// level.Error(logger).Log("value", value) -// } -// -// NewFilter allows precise control over what happens when a log event is -// emitted without a level key, or if a squelched level is used. Check the -// Option functions for details. -package level diff --git a/vendor/github.com/go-kit/log/level/level.go b/vendor/github.com/go-kit/log/level/level.go deleted file mode 100644 index c641d9855..000000000 --- a/vendor/github.com/go-kit/log/level/level.go +++ /dev/null @@ -1,256 +0,0 @@ -package level - -import ( - "errors" - "strings" - - "github.com/go-kit/log" -) - -// ErrInvalidLevelString is returned whenever an invalid string is passed to Parse. -var ErrInvalidLevelString = errors.New("invalid level string") - -// Error returns a logger that includes a Key/ErrorValue pair. -func Error(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), ErrorValue()) -} - -// Warn returns a logger that includes a Key/WarnValue pair. -func Warn(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), WarnValue()) -} - -// Info returns a logger that includes a Key/InfoValue pair. -func Info(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), InfoValue()) -} - -// Debug returns a logger that includes a Key/DebugValue pair. -func Debug(logger log.Logger) log.Logger { - return log.WithPrefix(logger, Key(), DebugValue()) -} - -// NewFilter wraps next and implements level filtering. See the commentary on -// the Option functions for a detailed description of how to configure levels. -// If no options are provided, all leveled log events created with Debug, -// Info, Warn or Error helper methods are squelched and non-leveled log -// events are passed to next unmodified. -func NewFilter(next log.Logger, options ...Option) log.Logger { - l := &logger{ - next: next, - } - for _, option := range options { - option(l) - } - return l -} - -type logger struct { - next log.Logger - allowed level - squelchNoLevel bool - errNotAllowed error - errNoLevel error -} - -func (l *logger) Log(keyvals ...interface{}) error { - var hasLevel, levelAllowed bool - for i := 1; i < len(keyvals); i += 2 { - if v, ok := keyvals[i].(*levelValue); ok { - hasLevel = true - levelAllowed = l.allowed&v.level != 0 - break - } - } - if !hasLevel && l.squelchNoLevel { - return l.errNoLevel - } - if hasLevel && !levelAllowed { - return l.errNotAllowed - } - return l.next.Log(keyvals...) -} - -// Option sets a parameter for the leveled logger. -type Option func(*logger) - -// Allow the provided log level to pass. -func Allow(v Value) Option { - switch v { - case debugValue: - return AllowDebug() - case infoValue: - return AllowInfo() - case warnValue: - return AllowWarn() - case errorValue: - return AllowError() - default: - return AllowNone() - } -} - -// AllowAll is an alias for AllowDebug. -func AllowAll() Option { - return AllowDebug() -} - -// AllowDebug allows error, warn, info and debug level log events to pass. -func AllowDebug() Option { - return allowed(levelError | levelWarn | levelInfo | levelDebug) -} - -// AllowInfo allows error, warn and info level log events to pass. -func AllowInfo() Option { - return allowed(levelError | levelWarn | levelInfo) -} - -// AllowWarn allows error and warn level log events to pass. -func AllowWarn() Option { - return allowed(levelError | levelWarn) -} - -// AllowError allows only error level log events to pass. -func AllowError() Option { - return allowed(levelError) -} - -// AllowNone allows no leveled log events to pass. -func AllowNone() Option { - return allowed(0) -} - -func allowed(allowed level) Option { - return func(l *logger) { l.allowed = allowed } -} - -// Parse a string to its corresponding level value. Valid strings are "debug", -// "info", "warn", and "error". Strings are normalized via strings.TrimSpace and -// strings.ToLower. -func Parse(level string) (Value, error) { - switch strings.TrimSpace(strings.ToLower(level)) { - case debugValue.name: - return debugValue, nil - case infoValue.name: - return infoValue, nil - case warnValue.name: - return warnValue, nil - case errorValue.name: - return errorValue, nil - default: - return nil, ErrInvalidLevelString - } -} - -// ParseDefault calls Parse and returns the default Value on error. -func ParseDefault(level string, def Value) Value { - v, err := Parse(level) - if err != nil { - return def - } - return v -} - -// ErrNotAllowed sets the error to return from Log when it squelches a log -// event disallowed by the configured Allow[Level] option. By default, -// ErrNotAllowed is nil; in this case the log event is squelched with no -// error. -func ErrNotAllowed(err error) Option { - return func(l *logger) { l.errNotAllowed = err } -} - -// SquelchNoLevel instructs Log to squelch log events with no level, so that -// they don't proceed through to the wrapped logger. If SquelchNoLevel is set -// to true and a log event is squelched in this way, the error value -// configured with ErrNoLevel is returned to the caller. -func SquelchNoLevel(squelch bool) Option { - return func(l *logger) { l.squelchNoLevel = squelch } -} - -// ErrNoLevel sets the error to return from Log when it squelches a log event -// with no level. By default, ErrNoLevel is nil; in this case the log event is -// squelched with no error. -func ErrNoLevel(err error) Option { - return func(l *logger) { l.errNoLevel = err } -} - -// NewInjector wraps next and returns a logger that adds a Key/level pair to -// the beginning of log events that don't already contain a level. In effect, -// this gives a default level to logs without a level. -func NewInjector(next log.Logger, level Value) log.Logger { - return &injector{ - next: next, - level: level, - } -} - -type injector struct { - next log.Logger - level interface{} -} - -func (l *injector) Log(keyvals ...interface{}) error { - for i := 1; i < len(keyvals); i += 2 { - if _, ok := keyvals[i].(*levelValue); ok { - return l.next.Log(keyvals...) - } - } - kvs := make([]interface{}, len(keyvals)+2) - kvs[0], kvs[1] = key, l.level - copy(kvs[2:], keyvals) - return l.next.Log(kvs...) -} - -// Value is the interface that each of the canonical level values implement. -// It contains unexported methods that prevent types from other packages from -// implementing it and guaranteeing that NewFilter can distinguish the levels -// defined in this package from all other values. -type Value interface { - String() string - levelVal() -} - -// Key returns the unique key added to log events by the loggers in this -// package. -func Key() interface{} { return key } - -// ErrorValue returns the unique value added to log events by Error. -func ErrorValue() Value { return errorValue } - -// WarnValue returns the unique value added to log events by Warn. -func WarnValue() Value { return warnValue } - -// InfoValue returns the unique value added to log events by Info. -func InfoValue() Value { return infoValue } - -// DebugValue returns the unique value added to log events by Debug. -func DebugValue() Value { return debugValue } - -var ( - // key is of type interface{} so that it allocates once during package - // initialization and avoids allocating every time the value is added to a - // []interface{} later. - key interface{} = "level" - - errorValue = &levelValue{level: levelError, name: "error"} - warnValue = &levelValue{level: levelWarn, name: "warn"} - infoValue = &levelValue{level: levelInfo, name: "info"} - debugValue = &levelValue{level: levelDebug, name: "debug"} -) - -type level byte - -const ( - levelDebug level = 1 << iota - levelInfo - levelWarn - levelError -) - -type levelValue struct { - name string - level -} - -func (v *levelValue) String() string { return v.name } -func (v *levelValue) levelVal() {} diff --git a/vendor/github.com/go-kit/log/log.go b/vendor/github.com/go-kit/log/log.go deleted file mode 100644 index 62e11adac..000000000 --- a/vendor/github.com/go-kit/log/log.go +++ /dev/null @@ -1,179 +0,0 @@ -package log - -import "errors" - -// Logger is the fundamental interface for all log operations. Log creates a -// log event from keyvals, a variadic sequence of alternating keys and values. -// Implementations must be safe for concurrent use by multiple goroutines. In -// particular, any implementation of Logger that appends to keyvals or -// modifies or retains any of its elements must make a copy first. -type Logger interface { - Log(keyvals ...interface{}) error -} - -// ErrMissingValue is appended to keyvals slices with odd length to substitute -// the missing value. -var ErrMissingValue = errors.New("(MISSING)") - -// With returns a new contextual logger with keyvals prepended to those passed -// to calls to Log. If logger is also a contextual logger created by With, -// WithPrefix, or WithSuffix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func With(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - return &context{ - logger: l.logger, - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - keyvals: kvs[:len(kvs):len(kvs)], - hasValuer: l.hasValuer || containsValuer(keyvals), - sKeyvals: l.sKeyvals, - sHasValuer: l.sHasValuer, - } -} - -// WithPrefix returns a new contextual logger with keyvals prepended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With, WithPrefix, or WithSuffix, keyvals is prepended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithPrefix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.keyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(kvs, l.keyvals...) - return &context{ - logger: l.logger, - keyvals: kvs, - hasValuer: l.hasValuer || containsValuer(keyvals), - sKeyvals: l.sKeyvals, - sHasValuer: l.sHasValuer, - } -} - -// WithSuffix returns a new contextual logger with keyvals appended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With, WithPrefix, or WithSuffix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithSuffix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.sKeyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(l.sKeyvals, kvs...) - return &context{ - logger: l.logger, - keyvals: l.keyvals, - hasValuer: l.hasValuer, - sKeyvals: kvs, - sHasValuer: l.sHasValuer || containsValuer(keyvals), - } -} - -// context is the Logger implementation returned by With, WithPrefix, and -// WithSuffix. It wraps a Logger and holds keyvals that it includes in all -// log events. Its Log method calls bindValues to generate values for each -// Valuer in the context keyvals. -// -// A context must always have the same number of stack frames between calls to -// its Log method and the eventual binding of Valuers to their value. This -// requirement comes from the functional requirement to allow a context to -// resolve application call site information for a Caller stored in the -// context. To do this we must be able to predict the number of logging -// functions on the stack when bindValues is called. -// -// Two implementation details provide the needed stack depth consistency. -// -// 1. newContext avoids introducing an additional layer when asked to -// wrap another context. -// 2. With, WithPrefix, and WithSuffix avoid introducing an additional -// layer by returning a newly constructed context with a merged keyvals -// rather than simply wrapping the existing context. -type context struct { - logger Logger - keyvals []interface{} - sKeyvals []interface{} // suffixes - hasValuer bool - sHasValuer bool -} - -func newContext(logger Logger) *context { - if c, ok := logger.(*context); ok { - return c - } - return &context{logger: logger} -} - -// Log replaces all value elements (odd indexes) containing a Valuer in the -// stored context with their generated value, appends keyvals, and passes the -// result to the wrapped Logger. -func (l *context) Log(keyvals ...interface{}) error { - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - if l.hasValuer { - // If no keyvals were appended above then we must copy l.keyvals so - // that future log events will reevaluate the stored Valuers. - if len(keyvals) == 0 { - kvs = append([]interface{}{}, l.keyvals...) - } - bindValues(kvs[:(len(l.keyvals))]) - } - kvs = append(kvs, l.sKeyvals...) - if l.sHasValuer { - bindValues(kvs[len(kvs)-len(l.sKeyvals):]) - } - return l.logger.Log(kvs...) -} - -// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If -// f is a function with the appropriate signature, LoggerFunc(f) is a Logger -// object that calls f. -type LoggerFunc func(...interface{}) error - -// Log implements Logger by calling f(keyvals...). -func (f LoggerFunc) Log(keyvals ...interface{}) error { - return f(keyvals...) -} diff --git a/vendor/github.com/go-kit/log/logfmt_logger.go b/vendor/github.com/go-kit/log/logfmt_logger.go deleted file mode 100644 index a00305298..000000000 --- a/vendor/github.com/go-kit/log/logfmt_logger.go +++ /dev/null @@ -1,62 +0,0 @@ -package log - -import ( - "bytes" - "io" - "sync" - - "github.com/go-logfmt/logfmt" -) - -type logfmtEncoder struct { - *logfmt.Encoder - buf bytes.Buffer -} - -func (l *logfmtEncoder) Reset() { - l.Encoder.Reset() - l.buf.Reset() -} - -var logfmtEncoderPool = sync.Pool{ - New: func() interface{} { - var enc logfmtEncoder - enc.Encoder = logfmt.NewEncoder(&enc.buf) - return &enc - }, -} - -type logfmtLogger struct { - w io.Writer -} - -// NewLogfmtLogger returns a logger that encodes keyvals to the Writer in -// logfmt format. Each log event produces no more than one call to w.Write. -// The passed Writer must be safe for concurrent use by multiple goroutines if -// the returned Logger will be used concurrently. -func NewLogfmtLogger(w io.Writer) Logger { - return &logfmtLogger{w} -} - -func (l logfmtLogger) Log(keyvals ...interface{}) error { - enc := logfmtEncoderPool.Get().(*logfmtEncoder) - enc.Reset() - defer logfmtEncoderPool.Put(enc) - - if err := enc.EncodeKeyvals(keyvals...); err != nil { - return err - } - - // Add newline to the end of the buffer - if err := enc.EndRecord(); err != nil { - return err - } - - // The Logger interface requires implementations to be safe for concurrent - // use by multiple goroutines. For this implementation that means making - // only one call to l.w.Write() for each call to Log. - if _, err := l.w.Write(enc.buf.Bytes()); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-kit/log/nop_logger.go b/vendor/github.com/go-kit/log/nop_logger.go deleted file mode 100644 index 1047d626c..000000000 --- a/vendor/github.com/go-kit/log/nop_logger.go +++ /dev/null @@ -1,8 +0,0 @@ -package log - -type nopLogger struct{} - -// NewNopLogger returns a logger that doesn't do anything. -func NewNopLogger() Logger { return nopLogger{} } - -func (nopLogger) Log(...interface{}) error { return nil } diff --git a/vendor/github.com/go-kit/log/staticcheck.conf b/vendor/github.com/go-kit/log/staticcheck.conf deleted file mode 100644 index 528438b97..000000000 --- a/vendor/github.com/go-kit/log/staticcheck.conf +++ /dev/null @@ -1 +0,0 @@ -checks = ["all"] diff --git a/vendor/github.com/go-kit/log/stdlib.go b/vendor/github.com/go-kit/log/stdlib.go deleted file mode 100644 index 0338edbe2..000000000 --- a/vendor/github.com/go-kit/log/stdlib.go +++ /dev/null @@ -1,151 +0,0 @@ -package log - -import ( - "bytes" - "io" - "log" - "regexp" - "strings" -) - -// StdlibWriter implements io.Writer by invoking the stdlib log.Print. It's -// designed to be passed to a Go kit logger as the writer, for cases where -// it's necessary to redirect all Go kit log output to the stdlib logger. -// -// If you have any choice in the matter, you shouldn't use this. Prefer to -// redirect the stdlib log to the Go kit logger via NewStdlibAdapter. -type StdlibWriter struct{} - -// Write implements io.Writer. -func (w StdlibWriter) Write(p []byte) (int, error) { - log.Print(strings.TrimSpace(string(p))) - return len(p), nil -} - -// StdlibAdapter wraps a Logger and allows it to be passed to the stdlib -// logger's SetOutput. It will extract date/timestamps, filenames, and -// messages, and place them under relevant keys. -type StdlibAdapter struct { - Logger - timestampKey string - fileKey string - messageKey string - prefix string - joinPrefixToMsg bool -} - -// StdlibAdapterOption sets a parameter for the StdlibAdapter. -type StdlibAdapterOption func(*StdlibAdapter) - -// TimestampKey sets the key for the timestamp field. By default, it's "ts". -func TimestampKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.timestampKey = key } -} - -// FileKey sets the key for the file and line field. By default, it's "caller". -func FileKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.fileKey = key } -} - -// MessageKey sets the key for the actual log message. By default, it's "msg". -func MessageKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.messageKey = key } -} - -// Prefix configures the adapter to parse a prefix from stdlib log events. If -// you provide a non-empty prefix to the stdlib logger, then your should provide -// that same prefix to the adapter via this option. -// -// By default, the prefix isn't included in the msg key. Set joinPrefixToMsg to -// true if you want to include the parsed prefix in the msg. -func Prefix(prefix string, joinPrefixToMsg bool) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.prefix = prefix; a.joinPrefixToMsg = joinPrefixToMsg } -} - -// NewStdlibAdapter returns a new StdlibAdapter wrapper around the passed -// logger. It's designed to be passed to log.SetOutput. -func NewStdlibAdapter(logger Logger, options ...StdlibAdapterOption) io.Writer { - a := StdlibAdapter{ - Logger: logger, - timestampKey: "ts", - fileKey: "caller", - messageKey: "msg", - } - for _, option := range options { - option(&a) - } - return a -} - -func (a StdlibAdapter) Write(p []byte) (int, error) { - p = a.handlePrefix(p) - - result := subexps(p) - keyvals := []interface{}{} - var timestamp string - if date, ok := result["date"]; ok && date != "" { - timestamp = date - } - if time, ok := result["time"]; ok && time != "" { - if timestamp != "" { - timestamp += " " - } - timestamp += time - } - if timestamp != "" { - keyvals = append(keyvals, a.timestampKey, timestamp) - } - if file, ok := result["file"]; ok && file != "" { - keyvals = append(keyvals, a.fileKey, file) - } - if msg, ok := result["msg"]; ok { - msg = a.handleMessagePrefix(msg) - keyvals = append(keyvals, a.messageKey, msg) - } - if err := a.Logger.Log(keyvals...); err != nil { - return 0, err - } - return len(p), nil -} - -func (a StdlibAdapter) handlePrefix(p []byte) []byte { - if a.prefix != "" { - p = bytes.TrimPrefix(p, []byte(a.prefix)) - } - return p -} - -func (a StdlibAdapter) handleMessagePrefix(msg string) string { - if a.prefix == "" { - return msg - } - - msg = strings.TrimPrefix(msg, a.prefix) - if a.joinPrefixToMsg { - msg = a.prefix + msg - } - return msg -} - -const ( - logRegexpDate = `(?P[0-9]{4}/[0-9]{2}/[0-9]{2})?[ ]?` - logRegexpTime = `(?P