swap logrus types for their containerd/logs aliases

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2023-07-30 17:18:56 +02:00
parent 39a13456c1
commit 5e2a1195d7
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C
51 changed files with 391 additions and 373 deletions

View file

@ -9,7 +9,6 @@ import (
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/errcode"
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
) )
@ -21,7 +20,7 @@ type causer interface {
// FromError retrieves status code from error message. // FromError retrieves status code from error message.
func FromError(err error) int { func FromError(err error) int {
if err == nil { if err == nil {
log.G(context.TODO()).WithFields(logrus.Fields{"error": err}).Error("unexpected HTTP error handling") log.G(context.TODO()).WithError(err).Error("unexpected HTTP error handling")
return http.StatusInternalServerError return http.StatusInternalServerError
} }
@ -67,10 +66,11 @@ func FromError(err error) int {
return FromError(e.Cause()) return FromError(e.Cause())
} }
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"module": "api", "module": "api",
"error": err,
"error_type": fmt.Sprintf("%T", err), "error_type": fmt.Sprintf("%T", err),
}).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err) }).Debug("FIXME: Got an API for which error does not match any expected type!!!")
} }
if statusCode == 0 { if statusCode == 0 {

View file

@ -1,9 +1,9 @@
package server // import "github.com/docker/docker/api/server" package server // import "github.com/docker/docker/api/server"
import ( import (
"github.com/containerd/containerd/log"
"github.com/docker/docker/api/server/httputils" "github.com/docker/docker/api/server/httputils"
"github.com/docker/docker/api/server/middleware" "github.com/docker/docker/api/server/middleware"
"github.com/sirupsen/logrus"
) )
// handlerWithGlobalMiddlewares wraps the handler function for a request with // handlerWithGlobalMiddlewares wraps the handler function for a request with
@ -16,7 +16,7 @@ func (s *Server) handlerWithGlobalMiddlewares(handler httputils.APIFunc) httputi
next = m.WrapHandler(next) next = m.WrapHandler(next)
} }
if logrus.GetLevel() == logrus.DebugLevel { if log.GetLevel() == log.DebugLevel {
next = middleware.DebugRequestMiddleware(next) next = middleware.DebugRequestMiddleware(next)
} }

View file

@ -16,7 +16,6 @@ import (
"github.com/docker/docker/api/types/versions" "github.com/docker/docker/api/types/versions"
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
func (sr *swarmRouter) initCluster(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { func (sr *swarmRouter) initCluster(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
@ -195,7 +194,7 @@ func (sr *swarmRouter) getService(ctx context.Context, w http.ResponseWriter, r
service, err := sr.backend.GetService(vars["id"], insertDefaults) service, err := sr.backend.GetService(vars["id"], insertDefaults)
if err != nil { if err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"service-id": vars["id"], "service-id": vars["id"],
}).Debug("Error getting service") }).Debug("Error getting service")
@ -231,7 +230,7 @@ func (sr *swarmRouter) createService(ctx context.Context, w http.ResponseWriter,
resp, err := sr.backend.CreateService(service, encodedAuth, queryRegistry) resp, err := sr.backend.CreateService(service, encodedAuth, queryRegistry)
if err != nil { if err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"error": err, "error": err,
"service-name": service.Name, "service-name": service.Name,
}).Debug("Error creating service") }).Debug("Error creating service")
@ -270,7 +269,7 @@ func (sr *swarmRouter) updateService(ctx context.Context, w http.ResponseWriter,
resp, err := sr.backend.UpdateService(vars["id"], version, service, flags, queryRegistry) resp, err := sr.backend.UpdateService(vars["id"], version, service, flags, queryRegistry)
if err != nil { if err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"service-id": vars["id"], "service-id": vars["id"],
}).Debug("Error updating service") }).Debug("Error updating service")
@ -281,7 +280,7 @@ func (sr *swarmRouter) updateService(ctx context.Context, w http.ResponseWriter,
func (sr *swarmRouter) removeService(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { func (sr *swarmRouter) removeService(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := sr.backend.RemoveService(vars["id"]); err != nil { if err := sr.backend.RemoveService(vars["id"]); err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"service-id": vars["id"], "service-id": vars["id"],
}).Debug("Error removing service") }).Debug("Error removing service")
@ -335,7 +334,7 @@ func (sr *swarmRouter) getNodes(ctx context.Context, w http.ResponseWriter, r *h
func (sr *swarmRouter) getNode(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { func (sr *swarmRouter) getNode(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
node, err := sr.backend.GetNode(vars["id"]) node, err := sr.backend.GetNode(vars["id"])
if err != nil { if err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"node-id": vars["id"], "node-id": vars["id"],
}).Debug("Error getting node") }).Debug("Error getting node")
@ -359,7 +358,7 @@ func (sr *swarmRouter) updateNode(ctx context.Context, w http.ResponseWriter, r
} }
if err := sr.backend.UpdateNode(vars["id"], version, node); err != nil { if err := sr.backend.UpdateNode(vars["id"], version, node); err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"node-id": vars["id"], "node-id": vars["id"],
}).Debug("Error updating node") }).Debug("Error updating node")
@ -376,7 +375,7 @@ func (sr *swarmRouter) removeNode(ctx context.Context, w http.ResponseWriter, r
force := httputils.BoolValue(r, "force") force := httputils.BoolValue(r, "force")
if err := sr.backend.RemoveNode(vars["id"], force); err != nil { if err := sr.backend.RemoveNode(vars["id"], force); err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"node-id": vars["id"], "node-id": vars["id"],
}).Debug("Error removing node") }).Debug("Error removing node")
@ -406,7 +405,7 @@ func (sr *swarmRouter) getTasks(ctx context.Context, w http.ResponseWriter, r *h
func (sr *swarmRouter) getTask(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { func (sr *swarmRouter) getTask(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
task, err := sr.backend.GetTask(vars["id"]) task, err := sr.backend.GetTask(vars["id"])
if err != nil { if err != nil {
log.G(ctx).WithContext(ctx).WithFields(logrus.Fields{ log.G(ctx).WithContext(ctx).WithFields(log.Fields{
"error": err, "error": err,
"task-id": vars["id"], "task-id": vars["id"],
}).Debug("Error getting task") }).Debug("Error getting task")

View file

@ -3,21 +3,21 @@ package debug // import "github.com/docker/docker/cli/debug"
import ( import (
"os" "os"
"github.com/sirupsen/logrus" "github.com/containerd/containerd/log"
) )
// Enable sets the DEBUG env var to true // Enable sets the DEBUG env var to true
// and makes the logger to log at debug level. // and makes the logger to log at debug level.
func Enable() { func Enable() {
os.Setenv("DEBUG", "1") os.Setenv("DEBUG", "1")
logrus.SetLevel(logrus.DebugLevel) _ = log.SetLevel("debug")
} }
// Disable sets the DEBUG env var to false // Disable sets the DEBUG env var to false
// and makes the logger to log at info level. // and makes the logger to log at info level.
func Disable() { func Disable() {
os.Setenv("DEBUG", "") os.Setenv("DEBUG", "")
logrus.SetLevel(logrus.InfoLevel) _ = log.SetLevel("info")
} }
// IsEnabled checks whether the debug flag is set or not. // IsEnabled checks whether the debug flag is set or not.

View file

@ -4,30 +4,30 @@ import (
"os" "os"
"testing" "testing"
"github.com/sirupsen/logrus" "github.com/containerd/containerd/log"
) )
func TestEnable(t *testing.T) { func TestEnable(t *testing.T) {
defer func() { t.Cleanup(func() {
os.Setenv("DEBUG", "") _ = os.Setenv("DEBUG", "")
logrus.SetLevel(logrus.InfoLevel) _ = log.SetLevel("info")
}() })
Enable() Enable()
if os.Getenv("DEBUG") != "1" { if debug := os.Getenv("DEBUG"); debug != "1" {
t.Fatalf("expected DEBUG=1, got %s", os.Getenv("DEBUG")) t.Fatalf("expected DEBUG=1, got %s", debug)
} }
if logrus.GetLevel() != logrus.DebugLevel { if lvl := log.GetLevel(); lvl != log.DebugLevel {
t.Fatalf("expected log level %v, got %v", logrus.DebugLevel, logrus.GetLevel()) t.Fatalf("expected log level %v, got %v", log.DebugLevel, lvl)
} }
} }
func TestDisable(t *testing.T) { func TestDisable(t *testing.T) {
Disable() Disable()
if os.Getenv("DEBUG") != "" { if debug := os.Getenv("DEBUG"); debug != "" {
t.Fatalf(`expected DEBUG="", got %s`, os.Getenv("DEBUG")) t.Fatalf(`expected DEBUG="", got %s`, debug)
} }
if logrus.GetLevel() != logrus.InfoLevel { if lvl := log.GetLevel(); lvl != log.InfoLevel {
t.Fatalf("expected log level %v, got %v", logrus.InfoLevel, logrus.GetLevel()) t.Fatalf("expected log level %v, got %v", log.InfoLevel, lvl)
} }
} }

View file

@ -47,7 +47,6 @@ import (
dopts "github.com/docker/docker/opts" dopts "github.com/docker/docker/opts"
"github.com/docker/docker/pkg/authorization" "github.com/docker/docker/pkg/authorization"
"github.com/docker/docker/pkg/homedir" "github.com/docker/docker/pkg/homedir"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/pidfile" "github.com/docker/docker/pkg/pidfile"
"github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugingetter"
"github.com/docker/docker/pkg/rootless" "github.com/docker/docker/pkg/rootless"
@ -305,8 +304,8 @@ func (cli *DaemonCli) start(opts *daemonOptions) (err error) {
defer apiWG.Done() defer apiWG.Done()
log.G(ctx).Infof("API listen on %s", ls.Addr()) log.G(ctx).Infof("API listen on %s", ls.Addr())
if err := httpServer.Serve(ls); err != http.ErrServerClosed { if err := httpServer.Serve(ls); err != http.ErrServerClosed {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"listener": ls.Addr(), "listener": ls.Addr(),
}).Error("ServeAPI error") }).Error("ServeAPI error")
@ -861,37 +860,31 @@ func systemContainerdRunning(honorXDG bool) (string, bool, error) {
return addr, err == nil, nil return addr, err == nil, nil
} }
// configureDaemonLogs sets the logrus logging level and formatting. It expects // configureDaemonLogs sets the logging level and formatting. It expects
// the passed configuration to already be validated, and ignores invalid options. // the passed configuration to already be validated, and ignores invalid options.
func configureDaemonLogs(conf *config.Config) { func configureDaemonLogs(conf *config.Config) {
if conf.LogLevel != "" { switch conf.LogFormat {
lvl, err := logrus.ParseLevel(conf.LogLevel)
if err == nil {
logrus.SetLevel(lvl)
}
} else {
logrus.SetLevel(logrus.InfoLevel)
}
logFormat := conf.LogFormat
if logFormat == "" {
logFormat = log.TextFormat
}
var formatter logrus.Formatter
switch logFormat {
case log.JSONFormat: case log.JSONFormat:
formatter = &logrus.JSONFormatter{ logrus.SetFormatter(&logrus.JSONFormatter{
TimestampFormat: jsonmessage.RFC3339NanoFixed, TimestampFormat: log.RFC3339NanoFixed,
} })
case log.TextFormat: case log.TextFormat, "":
formatter = &logrus.TextFormatter{ logrus.SetFormatter(&logrus.TextFormatter{
TimestampFormat: jsonmessage.RFC3339NanoFixed, TimestampFormat: log.RFC3339NanoFixed,
DisableColors: conf.RawLogs, DisableColors: conf.RawLogs,
FullTimestamp: true, FullTimestamp: true,
} })
default: default:
panic("unsupported log format " + logFormat) panic("unsupported log format " + conf.LogFormat)
}
logLevel := conf.LogLevel
if logLevel == "" {
logLevel = "info"
}
if err := log.SetLevel(logLevel); err != nil {
log.G(context.TODO()).WithError(err).Warn("configure log level")
} }
logrus.SetFormatter(formatter)
} }
func configureProxyEnv(conf *config.Config) { func configureProxyEnv(conf *config.Config) {
@ -911,7 +904,7 @@ func configureProxyEnv(conf *config.Config) {
func overrideProxyEnv(name, val string) { func overrideProxyEnv(name, val string) {
if oldVal := os.Getenv(name); oldVal != "" && oldVal != val { if oldVal := os.Getenv(name); oldVal != "" && oldVal != val {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"name": name, "name": name,
"old-value": config.MaskCredentials(oldVal), "old-value": config.MaskCredentials(oldVal),
"new-value": config.MaskCredentials(val), "new-value": config.MaskCredentials(val),

View file

@ -211,14 +211,15 @@ func TestLoadDaemonConfigWithRegistryOptions(t *testing.T) {
func TestConfigureDaemonLogs(t *testing.T) { func TestConfigureDaemonLogs(t *testing.T) {
conf := &config.Config{} conf := &config.Config{}
configureDaemonLogs(conf) configureDaemonLogs(conf)
assert.Check(t, is.Equal(logrus.InfoLevel, logrus.GetLevel())) assert.Check(t, is.Equal(log.InfoLevel, log.GetLevel()))
conf.LogLevel = "warn"
configureDaemonLogs(conf)
assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel()))
// log level should not be changed when passing an invalid value // log level should not be changed when passing an invalid value
conf.LogLevel = "foobar" conf.LogLevel = "foobar"
configureDaemonLogs(conf) configureDaemonLogs(conf)
assert.Check(t, is.Equal(logrus.WarnLevel, logrus.GetLevel())) assert.Check(t, is.Equal(log.InfoLevel, log.GetLevel()))
conf.LogLevel = "warn"
configureDaemonLogs(conf)
// TODO (thaJeztah): add more aliases in log package
assert.Check(t, is.Equal(logrus.WarnLevel, log.GetLevel()))
} }

View file

@ -6,9 +6,9 @@ import (
"os/signal" "os/signal"
"syscall" "syscall"
"github.com/containerd/containerd/log"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/reexec"
"github.com/docker/docker/pkg/rootless" "github.com/docker/docker/pkg/rootless"
"github.com/moby/buildkit/util/apicaps" "github.com/moby/buildkit/util/apicaps"
@ -84,7 +84,7 @@ func main() {
// initial log formatting; this setting is updated after the daemon configuration is loaded. // initial log formatting; this setting is updated after the daemon configuration is loaded.
logrus.SetFormatter(&logrus.TextFormatter{ logrus.SetFormatter(&logrus.TextFormatter{
TimestampFormat: jsonmessage.RFC3339NanoFixed, TimestampFormat: log.RFC3339NanoFixed,
FullTimestamp: true, FullTimestamp: true,
}) })

View file

@ -62,7 +62,7 @@ func NewController(backend Backend, t *api.Task) (*Controller, error) {
backend: backend, backend: backend,
spec: spec, spec: spec,
serviceID: t.ServiceID, serviceID: t.ServiceID,
logger: log.G(context.TODO()).WithFields(logrus.Fields{ logger: log.G(context.TODO()).WithFields(log.Fields{
"controller": "plugin", "controller": "plugin",
"task": t.ID, "task": t.ID,
"plugin": spec.Name, "plugin": spec.Name,

View file

@ -11,6 +11,7 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/containerd/containerd/log"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/backend" "github.com/docker/docker/api/types/backend"
@ -27,10 +28,9 @@ import (
gogotypes "github.com/gogo/protobuf/types" gogotypes "github.com/gogo/protobuf/types"
"github.com/moby/swarmkit/v2/agent/exec" "github.com/moby/swarmkit/v2/agent/exec"
"github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/log" swarmlog "github.com/moby/swarmkit/v2/log"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )
@ -95,7 +95,7 @@ func (c *containerAdapter) pullImage(ctx context.Context) error {
authConfig := &registry.AuthConfig{} authConfig := &registry.AuthConfig{}
if encodedAuthConfig != "" { if encodedAuthConfig != "" {
if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuthConfig))).Decode(authConfig); err != nil { if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuthConfig))).Decode(authConfig); err != nil {
log.G(ctx).Warnf("invalid authconfig: %v", err) swarmlog.G(ctx).Warnf("invalid authconfig: %v", err)
} }
} }
@ -121,19 +121,19 @@ func (c *containerAdapter) pullImage(ctx context.Context) error {
} }
return err return err
} }
l := log.G(ctx) l := swarmlog.G(ctx)
// limit pull progress logs unless the status changes // limit pull progress logs unless the status changes
if spamLimiter.Allow() || lastStatus != m["status"] { if spamLimiter.Allow() || lastStatus != m["status"] {
// if we have progress details, we have everything we need // if we have progress details, we have everything we need
if progress, ok := m["progressDetail"].(map[string]interface{}); ok { if progress, ok := m["progressDetail"].(map[string]interface{}); ok {
// first, log the image and status // first, log the image and status
l = l.WithFields(logrus.Fields{ l = l.WithFields(log.Fields{
"image": c.container.image(), "image": c.container.image(),
"status": m["status"], "status": m["status"],
}) })
// then, if we have progress, log the progress // then, if we have progress, log the progress
if progress["current"] != nil && progress["total"] != nil { if progress["current"] != nil && progress["total"] != nil {
l = l.WithFields(logrus.Fields{ l = l.WithFields(log.Fields{
"current": progress["current"], "current": progress["current"],
"total": progress["total"], "total": progress["total"],
}) })
@ -240,7 +240,7 @@ func (c *containerAdapter) removeNetworks(ctx context.Context) error {
case errors.As(err, &errNoSuchNetwork): case errors.As(err, &errNoSuchNetwork):
continue continue
default: default:
log.G(ctx).Errorf("network %s remove failed: %v", name, err) swarmlog.G(ctx).Errorf("network %s remove failed: %v", name, err)
return err return err
} }
} }
@ -374,7 +374,7 @@ func (c *containerAdapter) inspect(ctx context.Context) (types.ContainerJSON, er
// events issues a call to the events API and returns a channel with all // events issues a call to the events API and returns a channel with all
// events. The stream of events can be shutdown by cancelling the context. // events. The stream of events can be shutdown by cancelling the context.
func (c *containerAdapter) events(ctx context.Context) <-chan events.Message { func (c *containerAdapter) events(ctx context.Context) <-chan events.Message {
log.G(ctx).Debugf("waiting on events") swarmlog.G(ctx).Debugf("waiting on events")
buffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter()) buffer, l := c.backend.SubscribeToEvents(time.Time{}, time.Time{}, c.container.eventFilter())
eventsq := make(chan events.Message, len(buffer)) eventsq := make(chan events.Message, len(buffer))
@ -390,7 +390,7 @@ func (c *containerAdapter) events(ctx context.Context) <-chan events.Message {
case ev := <-l: case ev := <-l:
jev, ok := ev.(events.Message) jev, ok := ev.(events.Message)
if !ok { if !ok {
log.G(ctx).Warnf("unexpected event message: %q", ev) swarmlog.G(ctx).Warnf("unexpected event message: %q", ev)
continue continue
} }
select { select {
@ -485,7 +485,7 @@ func (c *containerAdapter) waitClusterVolumes(ctx context.Context) error {
} }
} }
} }
log.G(ctx).Debug("volumes ready") swarmlog.G(ctx).Debug("volumes ready")
return nil return nil
} }

View file

@ -7,6 +7,7 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/containerd/containerd/log"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
@ -21,10 +22,9 @@ import (
"github.com/moby/swarmkit/v2/agent/exec" "github.com/moby/swarmkit/v2/agent/exec"
"github.com/moby/swarmkit/v2/api" "github.com/moby/swarmkit/v2/api"
"github.com/moby/swarmkit/v2/api/naming" "github.com/moby/swarmkit/v2/api/naming"
"github.com/moby/swarmkit/v2/log" swarmlog "github.com/moby/swarmkit/v2/log"
"github.com/moby/swarmkit/v2/template" "github.com/moby/swarmkit/v2/template"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
type executor struct { type executor struct {
@ -160,8 +160,7 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error {
if na == nil || na.Network == nil || len(na.Addresses) == 0 { if na == nil || na.Network == nil || len(na.Addresses) == 0 {
// this should not happen, but we got a panic here and don't have a // this should not happen, but we got a panic here and don't have a
// good idea about what the underlying data structure looks like. // good idea about what the underlying data structure looks like.
log.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)). swarmlog.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).Warn("skipping nil or malformed node network attachment entry")
Warnf("skipping nil or malformed node network attachment entry")
continue continue
} }
@ -192,8 +191,7 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error {
// same thing as above, check sanity of the attachments so we don't // same thing as above, check sanity of the attachments so we don't
// get a panic. // get a panic.
if na == nil || na.Network == nil || len(na.Addresses) == 0 { if na == nil || na.Network == nil || len(na.Addresses) == 0 {
log.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)). swarmlog.G(ctx).WithField("NetworkAttachment", fmt.Sprintf("%#v", na)).Warn("skipping nil or malformed node network attachment entry")
Warnf("skipping nil or malformed node network attachment entry")
continue continue
} }
@ -262,19 +260,16 @@ func (e *executor) Configure(ctx context.Context, node *api.Node) error {
// just to log an appropriate, informative error. i'm unsure if // just to log an appropriate, informative error. i'm unsure if
// this can ever actually occur, but we need to know if it does. // this can ever actually occur, but we need to know if it does.
if gone { if gone {
log.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw) swarmlog.G(ctx).Warnf("network %s should be removed, but still has active attachments", nw)
} else { } else {
log.G(ctx).Warnf( swarmlog.G(ctx).Warnf("network %s should have its node LB IP changed, but cannot be removed because of active attachments", nw)
"network %s should have its node LB IP changed, but cannot be removed because of active attachments",
nw,
)
} }
continue continue
case errors.As(err, &errNoSuchNetwork): case errors.As(err, &errNoSuchNetwork):
// NoSuchNetworkError indicates the network is already gone. // NoSuchNetworkError indicates the network is already gone.
continue continue
default: default:
log.G(ctx).Errorf("network %s remove failed: %v", nw, err) swarmlog.G(ctx).Errorf("network %s remove failed: %v", nw, err)
} }
} }
@ -301,7 +296,7 @@ func (e *executor) Controller(t *api.Task) (exec.Controller, error) {
var ctlr exec.Controller var ctlr exec.Controller
switch r := t.Spec.GetRuntime().(type) { switch r := t.Spec.GetRuntime().(type) {
case *api.TaskSpec_Generic: case *api.TaskSpec_Generic:
log.G(context.TODO()).WithFields(logrus.Fields{ swarmlog.G(context.TODO()).WithFields(log.Fields{
"kind": r.Generic.Kind, "kind": r.Generic.Kind,
"type_url": r.Generic.Payload.TypeUrl, "type_url": r.Generic.Payload.TypeUrl,
}).Debug("custom runtime requested") }).Debug("custom runtime requested")

View file

@ -23,7 +23,6 @@ import (
"github.com/moby/sys/mount" "github.com/moby/sys/mount"
"github.com/opencontainers/selinux/go-selinux/label" "github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@ -200,7 +199,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
return errors.Wrap(err, "error creating secret mount path") return errors.Wrap(err, "error creating secret mount path")
} }
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"name": s.File.Name, "name": s.File.Name,
"path": fPath, "path": fPath,
}).Debug("injecting secret") }).Debug("injecting secret")
@ -251,7 +250,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
return errors.Wrap(err, "error creating config mount path") return errors.Wrap(err, "error creating config mount path")
} }
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"name": configRef.File.Name, "name": configRef.File.Name,
"path": fPath, "path": fPath,
}).Debug("injecting config") }).Debug("injecting config")

View file

@ -11,7 +11,6 @@ import (
"github.com/docker/docker/libnetwork" "github.com/docker/docker/libnetwork"
"github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/system"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) { func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]string, error) {
@ -61,7 +60,7 @@ func (daemon *Daemon) setupConfigDir(c *container.Container) (setupErr error) {
if err != nil { if err != nil {
return errors.Wrap(err, "error getting config file path for container") return errors.Wrap(err, "error getting config file path for container")
} }
log := log.G(context.TODO()).WithFields(logrus.Fields{"name": configRef.File.Name, "path": fPath}) log := log.G(context.TODO()).WithFields(log.Fields{"name": configRef.File.Name, "path": fPath})
log.Debug("injecting config") log.Debug("injecting config")
config, err := c.DependencyStore.Configs().Get(configRef.ConfigID) config, err := c.DependencyStore.Configs().Get(configRef.ConfigID)
@ -131,7 +130,7 @@ func (daemon *Daemon) setupSecretDir(c *container.Container) (setupErr error) {
if err != nil { if err != nil {
return err return err
} }
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"name": s.File.Name, "name": s.File.Name,
"path": fPath, "path": fPath,
}).Debug("injecting secret") }).Debug("injecting secret")

View file

@ -12,7 +12,6 @@ import (
"github.com/docker/docker/image" "github.com/docker/docker/image"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// Children returns a slice of image ID which rootfs is a superset of the // Children returns a slice of image ID which rootfs is a superset of the
@ -36,8 +35,8 @@ func (i *ImageService) Children(ctx context.Context, id image.ID) ([]image.ID, e
rootfs, err := platformRootfs(ctx, cs, target, platform) rootfs, err := platformRootfs(ctx, cs, target, platform)
if err != nil { if err != nil {
if !cerrdefs.IsNotFound(err) { if !cerrdefs.IsNotFound(err) {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"image": target.Digest, "image": target.Digest,
"platform": platform, "platform": platform,
}).Warning("failed to get platform-specific rootfs") }).Warning("failed to get platform-specific rootfs")
@ -60,8 +59,8 @@ func (i *ImageService) Children(ctx context.Context, id image.ID) ([]image.ID, e
rootfs, err := platformRootfs(ctx, cs, img.Target, platform) rootfs, err := platformRootfs(ctx, cs, img.Target, platform)
if err != nil { if err != nil {
if !cerrdefs.IsNotFound(err) { if !cerrdefs.IsNotFound(err) {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"image": img.Target.Digest, "image": img.Target.Digest,
"platform": platform, "platform": platform,
}).Warning("failed to get platform-specific rootfs") }).Warning("failed to get platform-specific rootfs")

View file

@ -22,7 +22,6 @@ import (
"github.com/opencontainers/image-spec/specs-go" "github.com/opencontainers/image-spec/specs-go"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
func (i *ImageService) PerformWithBaseFS(ctx context.Context, c *container.Container, fn func(root string) error) error { func (i *ImageService) PerformWithBaseFS(ctx context.Context, c *container.Container, fn func(root string) error) error {
@ -97,14 +96,14 @@ func (i *ImageService) ExportImage(ctx context.Context, names []string, outStrea
ref = reference.TagNameOnly(ref) ref = reference.TagNameOnly(ref)
opts = append(opts, archive.WithManifest(target, ref.String())) opts = append(opts, archive.WithManifest(target, ref.String()))
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"target": target, "target": target,
"name": ref.String(), "name": ref.String(),
}).Debug("export image") }).Debug("export image")
} else { } else {
opts = append(opts, archive.WithManifest(target)) opts = append(opts, archive.WithManifest(target))
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"target": target, "target": target,
}).Debug("export image without name") }).Debug("export image without name")
} }
@ -177,7 +176,7 @@ func (i *ImageService) LoadImage(ctx context.Context, inTar io.ReadCloser, outSt
} }
err = i.walkImageManifests(ctx, img, func(platformImg *ImageManifest) error { err = i.walkImageManifests(ctx, img, func(platformImg *ImageManifest) error {
logger := log.G(ctx).WithFields(logrus.Fields{ logger := log.G(ctx).WithFields(log.Fields{
"image": name, "image": name,
"manifest": platformImg.Target().Digest, "manifest": platformImg.Target().Digest,
}) })
@ -259,7 +258,7 @@ func (i *ImageService) getBestDescriptorForExport(ctx context.Context, indexDesc
log.G(ctx).WithField("manifest", mfst.Digest).Debug("manifest content present, will export") log.G(ctx).WithField("manifest", mfst.Digest).Debug("manifest content present, will export")
} else { } else {
hasMissingManifests = true hasMissingManifests = true
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"manifest": mfst.Digest, "manifest": mfst.Digest,
"missing": missing, "missing": missing,
}).Debug("manifest is missing, won't export") }).Debug("manifest is missing, won't export")

View file

@ -26,7 +26,6 @@ import (
"github.com/opencontainers/image-spec/specs-go" "github.com/opencontainers/image-spec/specs-go"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// ImportImage imports an image, getting the archived layer data from layerReader. // ImportImage imports an image, getting the archived layer data from layerReader.
@ -67,7 +66,7 @@ func (i *ImageService) ImportImage(ctx context.Context, ref reference.Named, pla
logger.WithError(err).Debug("failed to write layer blob") logger.WithError(err).Debug("failed to write layer blob")
return "", err return "", err
} }
logger = logger.WithFields(logrus.Fields{ logger = logger.WithFields(log.Fields{
"compressedDigest": compressedDigest, "compressedDigest": compressedDigest,
"uncompressedDigest": uncompressedDigest, "uncompressedDigest": uncompressedDigest,
}) })

View file

@ -23,7 +23,6 @@ import (
"github.com/opencontainers/image-spec/identity" "github.com/opencontainers/image-spec/identity"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// Subset of ocispec.Image that only contains Labels // Subset of ocispec.Image that only contains Labels
@ -127,8 +126,8 @@ func (i *ImageService) Images(ctx context.Context, opts types.ImageListOptions)
available, err := img.CheckContentAvailable(ctx) available, err := img.CheckContentAvailable(ctx)
if err != nil { if err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"manifest": img.Target(), "manifest": img.Target(),
"image": img.Name(), "image": img.Name(),
}).Warn("checking availability of platform specific manifest failed") }).Warn("checking availability of platform specific manifest failed")
@ -189,7 +188,7 @@ func (i *ImageService) singlePlatformImage(ctx context.Context, contentStore con
unpackedUsage, err := calculateSnapshotTotalUsage(ctx, snapshotter, imageSnapshotID) unpackedUsage, err := calculateSnapshotTotalUsage(ctx, snapshotter, imageSnapshotID)
if err != nil { if err != nil {
if !cerrdefs.IsNotFound(err) { if !cerrdefs.IsNotFound(err) {
log.G(ctx).WithError(err).WithFields(logrus.Fields{ log.G(ctx).WithError(err).WithFields(log.Fields{
"image": image.Name(), "image": image.Name(),
"snapshotID": imageSnapshotID, "snapshotID": imageSnapshotID,
}).Warn("failed to calculate unpacked size of image") }).Warn("failed to calculate unpacked size of image")
@ -210,7 +209,7 @@ func (i *ImageService) singlePlatformImage(ctx context.Context, contentStore con
rawImg := image.Metadata() rawImg := image.Metadata()
target := rawImg.Target.Digest target := rawImg.Target.Digest
logger := log.G(ctx).WithFields(logrus.Fields{ logger := log.G(ctx).WithFields(log.Fields{
"name": rawImg.Name, "name": rawImg.Name,
"digest": target, "digest": target,
}) })
@ -469,8 +468,8 @@ func setupLabelFilter(store content.Store, fltrs filters.Args) (func(image image
return true return true
} }
if err != nil { if err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"image": image.Name, "image": image.Name,
"checks": checks, "checks": checks,
}).Error("failed to check image labels") }).Error("failed to check image labels")

View file

@ -15,7 +15,6 @@ import (
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
var imagesAcceptedFilters = map[string]bool{ var imagesAcceptedFilters = map[string]bool{
@ -80,7 +79,7 @@ func (i *ImageService) pruneUnused(ctx context.Context, filterFunc imageFilterFu
if !danglingOnly || isDanglingImage(img) { if !danglingOnly || isDanglingImage(img) {
canBePruned := filterFunc(img) canBePruned := filterFunc(img)
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"image": img.Name, "image": img.Name,
"canBePruned": canBePruned, "canBePruned": canBePruned,
}).Debug("considering image for pruning") }).Debug("considering image for pruning")
@ -116,7 +115,7 @@ func (i *ImageService) pruneUnused(ctx context.Context, filterFunc imageFilterFu
} }
ref, err := reference.ParseNormalizedNamed(ctr.Config.Image) ref, err := reference.ParseNormalizedNamed(ctr.Config.Image)
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"ctr": ctr.ID, "ctr": ctr.ID,
"image": ref, "image": ref,
"nameParseErr": err, "nameParseErr": err,

View file

@ -16,7 +16,6 @@ import (
"github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/streamformatter"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/sirupsen/logrus"
) )
// PullImage initiates a pull operation. image is the repository name to pull, and // PullImage initiates a pull operation. image is the repository name to pull, and
@ -76,7 +75,7 @@ func (i *ImageService) PullImage(ctx context.Context, image, tagOrDigest string,
return err return err
} }
logger := log.G(ctx).WithFields(logrus.Fields{ logger := log.G(ctx).WithFields(log.Fields{
"digest": img.Target().Digest, "digest": img.Target().Digest,
"remote": ref.String(), "remote": ref.String(),
}) })

View file

@ -10,7 +10,6 @@ import (
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
"github.com/docker/docker/image" "github.com/docker/docker/image"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// TagImage creates an image named as newTag and targeting the given descriptor id. // TagImage creates an image named as newTag and targeting the given descriptor id.
@ -55,7 +54,7 @@ func (i *ImageService) TagImage(ctx context.Context, imageID image.ID, newTag re
} }
} }
logger := log.G(ctx).WithFields(logrus.Fields{ logger := log.G(ctx).WithFields(log.Fields{
"imageID": imageID.String(), "imageID": imageID.String(),
"tag": newTag.String(), "tag": newTag.String(),
}) })

View file

@ -14,7 +14,6 @@ import (
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/docker/docker/pkg/useragent" "github.com/docker/docker/pkg/useragent"
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
"github.com/sirupsen/logrus"
) )
func (i *ImageService) newResolverFromAuthConfig(ctx context.Context, authConfig *registrytypes.AuthConfig) (remotes.Resolver, docker.StatusTracker) { func (i *ImageService) newResolverFromAuthConfig(ctx context.Context, authConfig *registrytypes.AuthConfig) (remotes.Resolver, docker.StatusTracker) {
@ -64,7 +63,7 @@ func authorizationCredsFromAuthConfig(authConfig registrytypes.AuthConfig) docke
return docker.WithAuthCreds(func(host string) (string, string, error) { return docker.WithAuthCreds(func(host string) (string, string, error) {
if cfgHost != host { if cfgHost != host {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"host": host, "host": host,
"cfgHost": cfgHost, "cfgHost": cfgHost,
}).Warn("Host doesn't match") }).Warn("Host doesn't match")

View file

@ -22,7 +22,6 @@ import (
"github.com/docker/docker/registry" "github.com/docker/docker/registry"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// ImageService implements daemon.ImageService // ImageService implements daemon.ImageService
@ -175,7 +174,7 @@ func (i *ImageService) GetContainerLayerSize(ctx context.Context, containerID st
log.G(ctx).WithError(err).WithField("ctr", containerID).Warn("unexpected error when calculating usage of the parent snapshots") log.G(ctx).WithError(err).WithField("ctr", containerID).Warn("unexpected error when calculating usage of the parent snapshots")
} }
} }
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"rwLayerUsage": rwLayerUsage.Size, "rwLayerUsage": rwLayerUsage.Size,
"unpacked": unpackedUsage.Size, "unpacked": unpackedUsage.Size,
}).Debug("GetContainerLayerSize") }).Debug("GetContainerLayerSize")

View file

@ -192,7 +192,7 @@ func (daemon *Daemon) UsesSnapshotter() bool {
// RegistryHosts returns the registry hosts configuration for the host component // RegistryHosts returns the registry hosts configuration for the host component
// of a distribution image reference. // of a distribution image reference.
func (daemon *Daemon) RegistryHosts(host string) ([]docker.RegistryHost, error) { func (daemon *Daemon) RegistryHosts(host string) ([]docker.RegistryHost, error) {
var m = map[string]resolverconfig.RegistryConfig{} m := map[string]resolverconfig.RegistryConfig{}
mirrors := daemon.registryService.ServiceConfig().Mirrors mirrors := daemon.registryService.ServiceConfig().Mirrors
m["docker.io"] = resolverconfig.RegistryConfig{Mirrors: mirrors} m["docker.io"] = resolverconfig.RegistryConfig{Mirrors: mirrors}
@ -268,27 +268,27 @@ func (daemon *Daemon) restore(cfg *configStore) error {
_ = sem.Acquire(context.Background(), 1) _ = sem.Acquire(context.Background(), 1)
defer sem.Release(1) defer sem.Release(1)
log := log.G(context.TODO()).WithField("container", id) logger := log.G(context.TODO()).WithField("container", id)
c, err := daemon.load(id) c, err := daemon.load(id)
if err != nil { if err != nil {
log.WithError(err).Error("failed to load container") logger.WithError(err).Error("failed to load container")
return return
} }
if c.Driver != daemon.imageService.StorageDriver() { if c.Driver != daemon.imageService.StorageDriver() {
// Ignore the container if it wasn't created with the current storage-driver // Ignore the container if it wasn't created with the current storage-driver
log.Debugf("not restoring container because it was created with another storage driver (%s)", c.Driver) logger.Debugf("not restoring container because it was created with another storage driver (%s)", c.Driver)
return return
} }
if accessor, ok := daemon.imageService.(layerAccessor); ok { if accessor, ok := daemon.imageService.(layerAccessor); ok {
rwlayer, err := accessor.GetLayerByID(c.ID) rwlayer, err := accessor.GetLayerByID(c.ID)
if err != nil { if err != nil {
log.WithError(err).Error("failed to load container mount") logger.WithError(err).Error("failed to load container mount")
return return
} }
c.RWLayer = rwlayer c.RWLayer = rwlayer
} }
log.WithFields(logrus.Fields{ logger.WithFields(log.Fields{
"running": c.IsRunning(), "running": c.IsRunning(),
"paused": c.IsPaused(), "paused": c.IsPaused(),
}).Debug("loaded container") }).Debug("loaded container")
@ -311,17 +311,17 @@ func (daemon *Daemon) restore(cfg *configStore) error {
_ = sem.Acquire(context.Background(), 1) _ = sem.Acquire(context.Background(), 1)
defer sem.Release(1) defer sem.Release(1)
log := log.G(context.TODO()).WithField("container", c.ID) logger := log.G(context.TODO()).WithField("container", c.ID)
if err := daemon.registerName(c); err != nil { if err := daemon.registerName(c); err != nil {
log.WithError(err).Errorf("failed to register container name: %s", c.Name) logger.WithError(err).Errorf("failed to register container name: %s", c.Name)
mapLock.Lock() mapLock.Lock()
delete(containers, c.ID) delete(containers, c.ID)
mapLock.Unlock() mapLock.Unlock()
return return
} }
if err := daemon.Register(c); err != nil { if err := daemon.Register(c); err != nil {
log.WithError(err).Error("failed to register container") logger.WithError(err).Error("failed to register container")
mapLock.Lock() mapLock.Lock()
delete(containers, c.ID) delete(containers, c.ID)
mapLock.Unlock() mapLock.Unlock()
@ -338,16 +338,16 @@ func (daemon *Daemon) restore(cfg *configStore) error {
_ = sem.Acquire(context.Background(), 1) _ = sem.Acquire(context.Background(), 1)
defer sem.Release(1) defer sem.Release(1)
log := log.G(context.TODO()).WithField("container", c.ID) baseLogger := log.G(context.TODO()).WithField("container", c.ID)
if err := daemon.checkpointAndSave(c); err != nil { if err := daemon.checkpointAndSave(c); err != nil {
log.WithError(err).Error("error saving backported mountspec to disk") baseLogger.WithError(err).Error("error saving backported mountspec to disk")
} }
daemon.setStateCounter(c) daemon.setStateCounter(c)
logger := func(c *container.Container) *logrus.Entry { logger := func(c *container.Container) *logrus.Entry {
return log.WithFields(logrus.Fields{ return baseLogger.WithFields(log.Fields{
"running": c.IsRunning(), "running": c.IsRunning(),
"paused": c.IsPaused(), "paused": c.IsPaused(),
"restarting": c.IsRestarting(), "restarting": c.IsRestarting(),
@ -382,7 +382,7 @@ func (daemon *Daemon) restore(cfg *configStore) error {
} else if !cfg.LiveRestoreEnabled { } else if !cfg.LiveRestoreEnabled {
logger(c).Debug("shutting down container considered alive by containerd") logger(c).Debug("shutting down container considered alive by containerd")
if err := daemon.shutdownContainer(c); err != nil && !errdefs.IsNotFound(err) { if err := daemon.shutdownContainer(c); err != nil && !errdefs.IsNotFound(err) {
log.WithError(err).Error("error shutting down container") baseLogger.WithError(err).Error("error shutting down container")
return return
} }
status = containerd.Stopped status = containerd.Stopped
@ -406,7 +406,7 @@ func (daemon *Daemon) restore(cfg *configStore) error {
case containerd.Paused, containerd.Pausing: case containerd.Paused, containerd.Pausing:
// nothing to do // nothing to do
case containerd.Unknown, containerd.Stopped, "": case containerd.Unknown, containerd.Stopped, "":
log.WithField("status", status).Error("unexpected status for paused container during restore") baseLogger.WithField("status", status).Error("unexpected status for paused container during restore")
default: default:
// running // running
c.Lock() c.Lock()
@ -414,7 +414,7 @@ func (daemon *Daemon) restore(cfg *configStore) error {
daemon.setStateCounter(c) daemon.setStateCounter(c)
daemon.updateHealthMonitor(c) daemon.updateHealthMonitor(c)
if err := c.CheckpointTo(daemon.containersReplica); err != nil { if err := c.CheckpointTo(daemon.containersReplica); err != nil {
log.WithError(err).Error("failed to update paused container state") baseLogger.WithError(err).Error("failed to update paused container state")
} }
c.Unlock() c.Unlock()
} }
@ -438,7 +438,7 @@ func (daemon *Daemon) restore(cfg *configStore) error {
c.SetStopped(&ces) c.SetStopped(&ces)
daemon.Cleanup(c) daemon.Cleanup(c)
if err := c.CheckpointTo(daemon.containersReplica); err != nil { if err := c.CheckpointTo(daemon.containersReplica); err != nil {
log.WithError(err).Error("failed to update stopped container state") baseLogger.WithError(err).Error("failed to update stopped container state")
} }
c.Unlock() c.Unlock()
logger(c).Debug("set stopped state") logger(c).Debug("set stopped state")
@ -502,9 +502,9 @@ func (daemon *Daemon) restore(cfg *configStore) error {
c.RemovalInProgress = false c.RemovalInProgress = false
c.Dead = true c.Dead = true
if err := c.CheckpointTo(daemon.containersReplica); err != nil { if err := c.CheckpointTo(daemon.containersReplica); err != nil {
log.WithError(err).Error("failed to update RemovalInProgress container state") baseLogger.WithError(err).Error("failed to update RemovalInProgress container state")
} else { } else {
log.Debugf("reset RemovalInProgress state for container") baseLogger.Debugf("reset RemovalInProgress state for container")
} }
} }
c.Unlock() c.Unlock()
@ -1170,7 +1170,7 @@ func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
engineCpus.Set(float64(info.NCPU)) engineCpus.Set(float64(info.NCPU))
engineMemory.Set(float64(info.MemTotal)) engineMemory.Set(float64(info.MemTotal))
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"version": dockerversion.Version, "version": dockerversion.Version,
"commit": dockerversion.GitCommit, "commit": dockerversion.GitCommit,
"graphdriver": d.ImageService().StorageDriver(), "graphdriver": d.ImageService().StorageDriver(),
@ -1256,16 +1256,16 @@ func (daemon *Daemon) Shutdown(ctx context.Context) error {
if !c.IsRunning() { if !c.IsRunning() {
return return
} }
log := log.G(ctx).WithField("container", c.ID) logger := log.G(ctx).WithField("container", c.ID)
log.Debug("shutting down container") logger.Debug("shutting down container")
if err := daemon.shutdownContainer(c); err != nil { if err := daemon.shutdownContainer(c); err != nil {
log.WithError(err).Error("failed to shut down container") logger.WithError(err).Error("failed to shut down container")
return return
} }
if mountid, err := daemon.imageService.GetLayerMountID(c.ID); err == nil { if mountid, err := daemon.imageService.GetLayerMountID(c.ID); err == nil {
daemon.cleanupMountsByID(mountid) daemon.cleanupMountsByID(mountid)
} }
log.Debugf("shut down container") logger.Debugf("shut down container")
}) })
} }

View file

@ -14,7 +14,6 @@ import (
"github.com/docker/docker/layer" "github.com/docker/docker/layer"
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
const imageKeyPrefix = "moby-image-" const imageKeyPrefix = "moby-image-"
@ -83,7 +82,7 @@ func (s *imageStoreForPull) updateLease(ctx context.Context, dgst digest.Digest)
Type: "content", Type: "content",
} }
for _, dgst := range digested { for _, dgst := range digested {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"digest": dgst, "digest": dgst,
"lease": lease.ID, "lease": lease.ID,
}).Debug("Adding content digest to lease") }).Debug("Adding content digest to lease")

View file

@ -16,7 +16,6 @@ import (
"github.com/docker/docker/image" "github.com/docker/docker/image"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
var acceptedPsFilterTags = map[string]bool{ var acceptedPsFilterTags = map[string]bool{
@ -619,14 +618,13 @@ func (daemon *Daemon) refreshImage(ctx context.Context, s *container.Snapshot) (
// Check if the image reference still resolves to the same digest. // Check if the image reference still resolves to the same digest.
img, err := daemon.imageService.GetImage(ctx, s.Image, imagetypes.GetImageOpts{}) img, err := daemon.imageService.GetImage(ctx, s.Image, imagetypes.GetImageOpts{})
// If the image is no longer found or can't be resolved for some other // If the image is no longer found or can't be resolved for some other
// reason. Update the Image to the specific ID of the original image it // reason. Update the Image to the specific ID of the original image it
// resolved to when the container was created. // resolved to when the container was created.
if err != nil { if err != nil {
if !errdefs.IsNotFound(err) { if !errdefs.IsNotFound(err) {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"containerID": c.ID, "containerID": c.ID,
"image": s.Image, "image": s.Image,
"imageID": s.ImageID, "imageID": s.ImageID,

View file

@ -27,7 +27,6 @@ import (
"github.com/docker/docker/daemon/logger/loggerutils" "github.com/docker/docker/daemon/logger/loggerutils"
"github.com/docker/docker/dockerversion" "github.com/docker/docker/dockerversion"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
const ( const (
@ -378,7 +377,7 @@ func newAWSLogsClient(info logger.Info, configOpts ...func(*config.LoadOptions)
return nil, errors.Wrap(err, "could not initialize AWS SDK config") return nil, errors.Wrap(err, "could not initialize AWS SDK config")
} }
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"region": *region, "region": *region,
}).Debug("Created awslogs client") }).Debug("Created awslogs client")
@ -477,7 +476,7 @@ func (l *logStream) createLogGroup() error {
}); err != nil { }); err != nil {
var apiErr smithy.APIError var apiErr smithy.APIError
if errors.As(err, &apiErr) { if errors.As(err, &apiErr) {
fields := logrus.Fields{ fields := log.Fields{
"errorCode": apiErr.ErrorCode(), "errorCode": apiErr.ErrorCode(),
"message": apiErr.ErrorMessage(), "message": apiErr.ErrorMessage(),
"logGroupName": l.logGroupName, "logGroupName": l.logGroupName,
@ -499,7 +498,7 @@ func (l *logStream) createLogGroup() error {
func (l *logStream) createLogStream() error { func (l *logStream) createLogStream() error {
// Directly return if we do not want to create log stream. // Directly return if we do not want to create log stream.
if !l.logCreateStream { if !l.logCreateStream {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"logGroupName": l.logGroupName, "logGroupName": l.logGroupName,
"logStreamName": l.logStreamName, "logStreamName": l.logStreamName,
"logCreateStream": l.logCreateStream, "logCreateStream": l.logCreateStream,
@ -516,7 +515,7 @@ func (l *logStream) createLogStream() error {
if err != nil { if err != nil {
var apiErr smithy.APIError var apiErr smithy.APIError
if errors.As(err, &apiErr) { if errors.As(err, &apiErr) {
fields := logrus.Fields{ fields := log.Fields{
"errorCode": apiErr.ErrorCode(), "errorCode": apiErr.ErrorCode(),
"message": apiErr.ErrorMessage(), "message": apiErr.ErrorMessage(),
"logGroupName": l.logGroupName, "logGroupName": l.logGroupName,
@ -695,7 +694,7 @@ func (l *logStream) publishBatch(batch *eventBatch) {
if apiErr := (*types.DataAlreadyAcceptedException)(nil); errors.As(err, &apiErr) { if apiErr := (*types.DataAlreadyAcceptedException)(nil); errors.As(err, &apiErr) {
// already submitted, just grab the correct sequence token // already submitted, just grab the correct sequence token
nextSequenceToken = apiErr.ExpectedSequenceToken nextSequenceToken = apiErr.ExpectedSequenceToken
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"errorCode": apiErr.ErrorCode(), "errorCode": apiErr.ErrorCode(),
"message": apiErr.ErrorMessage(), "message": apiErr.ErrorMessage(),
"logGroupName": l.logGroupName, "logGroupName": l.logGroupName,
@ -725,7 +724,7 @@ func (l *logStream) putLogEvents(events []types.InputLogEvent, sequenceToken *st
if err != nil { if err != nil {
var apiErr smithy.APIError var apiErr smithy.APIError
if errors.As(err, &apiErr) { if errors.As(err, &apiErr) {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"errorCode": apiErr.ErrorCode(), "errorCode": apiErr.ErrorCode(),
"message": apiErr.ErrorMessage(), "message": apiErr.ErrorMessage(),
"logGroupName": l.logGroupName, "logGroupName": l.logGroupName,

View file

@ -24,7 +24,7 @@ type follow struct {
// Do follows the log file as it is written, starting from f at read. // Do follows the log file as it is written, starting from f at read.
func (fl *follow) Do(f *os.File, read logPos) { func (fl *follow) Do(f *os.File, read logPos) {
fl.log = log.G(context.TODO()).WithFields(logrus.Fields{ fl.log = log.G(context.TODO()).WithFields(log.Fields{
"module": "logger", "module": "logger",
"file": f.Name(), "file": f.Name(),
}) })

View file

@ -16,7 +16,6 @@ import (
logcache "github.com/docker/docker/daemon/logger/loggerutils/cache" logcache "github.com/docker/docker/daemon/logger/loggerutils/cache"
"github.com/docker/docker/errdefs" "github.com/docker/docker/errdefs"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// ContainerLogs copies the container's log channel to the channel provided in // ContainerLogs copies the container's log channel to the channel provided in
@ -26,7 +25,7 @@ import (
// if it returns nil, the config channel will be active and return log // if it returns nil, the config channel will be active and return log
// messages until it runs out or the context is canceled. // messages until it runs out or the context is canceled.
func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *types.ContainerLogsOptions) (messages <-chan *backend.LogMessage, isTTY bool, retErr error) { func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *types.ContainerLogsOptions) (messages <-chan *backend.LogMessage, isTTY bool, retErr error) {
lg := log.G(ctx).WithFields(logrus.Fields{ lg := log.G(ctx).WithFields(log.Fields{
"module": "daemon", "module": "daemon",
"method": "(*Daemon).ContainerLogs", "method": "(*Daemon).ContainerLogs",
"container": containerName, "container": containerName,

View file

@ -13,7 +13,6 @@ import (
libcontainerdtypes "github.com/docker/docker/libcontainerd/types" libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
"github.com/docker/docker/restartmanager" "github.com/docker/docker/restartmanager"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
func (daemon *Daemon) setStateCounter(c *container.Container) { func (daemon *Daemon) setStateCounter(c *container.Container) {
@ -43,8 +42,8 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine
es, err := tsk.Delete(ctx) es, err := tsk.Delete(ctx)
cancel() cancel()
if err != nil { if err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"container": c.ID, "container": c.ID,
}).Warn("failed to delete container from containerd") }).Warn("failed to delete container from containerd")
} else { } else {
@ -73,8 +72,8 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine
execDuration := time.Since(c.StartedAt) execDuration := time.Since(c.StartedAt)
restart, wait, err := c.RestartManager().ShouldRestart(uint32(exitStatus.ExitCode), daemonShutdown || c.HasBeenManuallyStopped, execDuration) restart, wait, err := c.RestartManager().ShouldRestart(uint32(exitStatus.ExitCode), daemonShutdown || c.HasBeenManuallyStopped, execDuration)
if err != nil { if err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"container": c.ID, "container": c.ID,
"restartCount": c.RestartCount, "restartCount": c.RestartCount,
"exitStatus": exitStatus, "exitStatus": exitStatus,
@ -93,7 +92,7 @@ func (daemon *Daemon) handleContainerExit(c *container.Container, e *libcontaine
if restart { if restart {
c.RestartCount++ c.RestartCount++
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"container": c.ID, "container": c.ID,
"restartCount": c.RestartCount, "restartCount": c.RestartCount,
"exitStatus": exitStatus, "exitStatus": exitStatus,
@ -207,8 +206,8 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei
if execConfig.Process != nil { if execConfig.Process != nil {
go func() { go func() {
if _, err := execConfig.Process.Delete(context.Background()); err != nil { if _, err := execConfig.Process.Delete(context.Background()); err != nil {
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"container": ei.ContainerID, "container": ei.ContainerID,
"process": ei.ProcessID, "process": ei.ProcessID,
}).Warn("failed to delete process") }).Warn("failed to delete process")
@ -232,8 +231,8 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei
if errdefs.IsNotFound(err) { if errdefs.IsNotFound(err) {
// The container was started by not-docker and so could have been deleted by // The container was started by not-docker and so could have been deleted by
// not-docker before we got around to loading it from containerd. // not-docker before we got around to loading it from containerd.
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"container": c.ID, "container": c.ID,
}).Debug("could not load containerd container for start event") }).Debug("could not load containerd container for start event")
return nil return nil
@ -243,8 +242,8 @@ func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei
tsk, err := ctr.Task(context.Background()) tsk, err := ctr.Task(context.Background())
if err != nil { if err != nil {
if errdefs.IsNotFound(err) { if errdefs.IsNotFound(err) {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"container": c.ID, "container": c.ID,
}).Debug("failed to load task for externally-started container") }).Debug("failed to load task for externally-started container")
return nil return nil
@ -311,5 +310,5 @@ func (daemon *Daemon) autoRemove(cfg *config.Config, c *container.Container) {
return return
} }
log.G(context.TODO()).WithFields(logrus.Fields{logrus.ErrorKey: err, "container": c.ID}).Error("error removing container") log.G(context.TODO()).WithFields(log.Fields{"error": err, "container": c.ID}).Error("error removing container")
} }

View file

@ -9,7 +9,6 @@ import (
mounttypes "github.com/docker/docker/api/types/mount" mounttypes "github.com/docker/docker/api/types/mount"
"github.com/docker/docker/container" "github.com/docker/docker/container"
volumesservice "github.com/docker/docker/volume/service" volumesservice "github.com/docker/docker/volume/service"
"github.com/sirupsen/logrus"
) )
func (daemon *Daemon) prepareMountPoints(container *container.Container) error { func (daemon *Daemon) prepareMountPoints(container *container.Container) error {
@ -23,7 +22,7 @@ func (daemon *Daemon) prepareMountPoints(container *container.Container) error {
continue continue
} }
if alive { if alive {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"container": container.ID, "container": container.ID,
"volume": config.Volume.Name(), "volume": config.Volume.Name(),
}).Debug("Live-restoring volume for alive container") }).Debug("Live-restoring volume for alive container")

View file

@ -32,7 +32,6 @@ import (
"github.com/docker/docker/runconfig" "github.com/docker/docker/runconfig"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// PredefinedNetworkError is returned when user tries to create predefined network that already exists. // PredefinedNetworkError is returned when user tries to create predefined network that already exists.
@ -328,7 +327,7 @@ func (daemon *Daemon) createNetwork(cfg *config.Config, create types.NetworkCrea
if defaultOpts, ok := cfg.DefaultNetworkOpts[driver]; create.ConfigFrom == nil && ok { if defaultOpts, ok := cfg.DefaultNetworkOpts[driver]; create.ConfigFrom == nil && ok {
for k, v := range defaultOpts { for k, v := range defaultOpts {
if _, ok := networkOptions[k]; !ok { if _, ok := networkOptions[k]; !ok {
log.G(context.TODO()).WithFields(logrus.Fields{"driver": driver, "network": id, k: v}).Debug("Applying network default option") log.G(context.TODO()).WithFields(log.Fields{"driver": driver, "network": id, k: v}).Debug("Applying network default option")
networkOptions[k] = v networkOptions[k] = v
} }
} }
@ -412,7 +411,7 @@ func (daemon *Daemon) pluginRefCount(driver, capability string, mode int) {
if daemon.PluginStore != nil { if daemon.PluginStore != nil {
_, err := daemon.PluginStore.Get(driver, capability, mode) _, err := daemon.PluginStore.Get(driver, capability, mode)
if err != nil { if err != nil {
log.G(context.TODO()).WithError(err).WithFields(logrus.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation") log.G(context.TODO()).WithError(err).WithFields(log.Fields{"mode": mode, "driver": driver}).Error("Error handling plugin refcount operation")
} }
} }
} }

View file

@ -9,7 +9,6 @@ import (
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/mitchellh/copystructure" "github.com/mitchellh/copystructure"
"github.com/sirupsen/logrus"
"github.com/docker/docker/daemon/config" "github.com/docker/docker/daemon/config"
) )
@ -280,7 +279,7 @@ func (daemon *Daemon) reloadNetworkDiagnosticPort(txn *reloadTxn, newCfg *config
return nil return nil
} }
// Enable the network diagnostic if the flag is set with a valid port within the range // Enable the network diagnostic if the flag is set with a valid port within the range
log.G(context.TODO()).WithFields(logrus.Fields{"port": conf.NetworkDiagnosticPort, "ip": "127.0.0.1"}).Warn("Starting network diagnostic server") log.G(context.TODO()).WithFields(log.Fields{"port": conf.NetworkDiagnosticPort, "ip": "127.0.0.1"}).Warn("Starting network diagnostic server")
daemon.netController.StartDiagnostic(conf.NetworkDiagnosticPort) daemon.netController.StartDiagnostic(conf.NetworkDiagnosticPort)
return nil return nil
}) })

View file

@ -33,7 +33,6 @@ import (
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1" ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
archvariant "github.com/tonistiigi/go-archvariant" archvariant "github.com/tonistiigi/go-archvariant"
) )
@ -375,8 +374,7 @@ func (p *puller) pullTag(ctx context.Context, ref reference.Named, platform *oci
return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", reference.FamiliarString(ref)) return false, fmt.Errorf("internal error: reference has neither a tag nor a digest: %s", reference.FamiliarString(ref))
} }
ctx = log.WithLogger(ctx, log.G(ctx).WithFields( ctx = log.WithLogger(ctx, log.G(ctx).WithFields(log.Fields{
logrus.Fields{
"digest": dgst, "digest": dgst,
"remote": ref, "remote": ref,
})) }))

View file

@ -13,7 +13,6 @@ import (
"github.com/opencontainers/go-digest" "github.com/opencontainers/go-digest"
"github.com/opencontainers/go-digest/digestset" "github.com/opencontainers/go-digest/digestset"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// Store is an interface for creating and accessing images // Store is an interface for creating and accessing images
@ -75,7 +74,7 @@ func (is *store) restore() error {
// if we don't need it. The "f" type alias is here is just for convenience, // if we don't need it. The "f" type alias is here is just for convenience,
// and to make the code _slightly_ more DRY. See the discussion on GitHub; // and to make the code _slightly_ more DRY. See the discussion on GitHub;
// https://github.com/moby/moby/pull/44426#discussion_r1059519071 // https://github.com/moby/moby/pull/44426#discussion_r1059519071
type f = logrus.Fields type f = log.Fields
err := is.fs.Walk(func(dgst digest.Digest) error { err := is.fs.Walk(func(dgst digest.Digest) error {
img, err := is.Get(ID(dgst)) img, err := is.Get(ID(dgst))
if err != nil { if err != nil {

View file

@ -9,8 +9,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/containerd/containerd/log"
"github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/pkg/jsonmessage"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
"gotest.tools/v3/icmd" "gotest.tools/v3/icmd"
) )
@ -67,7 +67,7 @@ func (s *DockerCLILogsSuite) TestLogsTimestamps(c *testing.T) {
for _, l := range lines { for _, l := range lines {
if l != "" { if l != "" {
_, err := time.Parse(jsonmessage.RFC3339NanoFixed+" ", ts.FindString(l)) _, err := time.Parse(log.RFC3339NanoFixed+" ", ts.FindString(l))
assert.NilError(c, err, "Failed to parse timestamp from %v", l) assert.NilError(c, err, "Failed to parse timestamp from %v", l)
// ensure we have padded 0's // ensure we have padded 0's
assert.Equal(c, l[29], uint8('Z')) assert.Equal(c, l[29], uint8('Z'))

View file

@ -163,13 +163,13 @@ func (c *client) NewContainer(_ context.Context, id string, spec *specs.Spec, sh
ei := libcontainerdtypes.EventInfo{ ei := libcontainerdtypes.EventInfo{
ContainerID: id, ContainerID: id,
} }
c.logger.WithFields(logrus.Fields{ c.logger.WithFields(log.Fields{
"container": id, "container": id,
"event": libcontainerdtypes.EventCreate, "event": libcontainerdtypes.EventCreate,
}).Info("sending event") }).Info("sending event")
err := c.backend.ProcessEvent(id, libcontainerdtypes.EventCreate, ei) err := c.backend.ProcessEvent(id, libcontainerdtypes.EventCreate, ei)
if err != nil { if err != nil {
c.logger.WithError(err).WithFields(logrus.Fields{ c.logger.WithError(err).WithFields(log.Fields{
"container": id, "container": id,
"event": libcontainerdtypes.EventCreate, "event": libcontainerdtypes.EventCreate,
}).Error("failed to process event") }).Error("failed to process event")
@ -498,14 +498,14 @@ func (ctr *container) Start(_ context.Context, _ string, withStdin bool, attachS
ProcessID: t.id, ProcessID: t.id,
Pid: pid, Pid: pid,
} }
ctr.client.logger.WithFields(logrus.Fields{ ctr.client.logger.WithFields(log.Fields{
"container": ctr.id, "container": ctr.id,
"event": libcontainerdtypes.EventStart, "event": libcontainerdtypes.EventStart,
"event-info": ei, "event-info": ei,
}).Info("sending event") }).Info("sending event")
err := ctr.client.backend.ProcessEvent(ei.ContainerID, libcontainerdtypes.EventStart, ei) err := ctr.client.backend.ProcessEvent(ei.ContainerID, libcontainerdtypes.EventStart, ei)
if err != nil { if err != nil {
ctr.client.logger.WithError(err).WithFields(logrus.Fields{ ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": ei.ContainerID, "container": ei.ContainerID,
"event": libcontainerdtypes.EventStart, "event": libcontainerdtypes.EventStart,
"event-info": ei, "event-info": ei,
@ -562,7 +562,7 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process,
if err != nil { if err != nil {
return nil, err return nil, err
} }
logger := t.ctr.client.logger.WithFields(logrus.Fields{ logger := t.ctr.client.logger.WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"exec": processID, "exec": processID,
}) })
@ -654,14 +654,14 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process,
ProcessID: p.id, ProcessID: p.id,
Pid: uint32(pid), Pid: uint32(pid),
} }
t.ctr.client.logger.WithFields(logrus.Fields{ t.ctr.client.logger.WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventExecAdded, "event": libcontainerdtypes.EventExecAdded,
"event-info": ei, "event-info": ei,
}).Info("sending event") }).Info("sending event")
err := t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecAdded, ei) err := t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecAdded, ei)
if err != nil { if err != nil {
t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ t.ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventExecAdded, "event": libcontainerdtypes.EventExecAdded,
"event-info": ei, "event-info": ei,
@ -669,7 +669,7 @@ func (t *task) Exec(ctx context.Context, processID string, spec *specs.Process,
} }
err = t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecStarted, ei) err = t.ctr.client.backend.ProcessEvent(t.ctr.id, libcontainerdtypes.EventExecStarted, ei)
if err != nil { if err != nil {
t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ t.ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventExecStarted, "event": libcontainerdtypes.EventExecStarted,
"event-info": ei, "event-info": ei,
@ -709,7 +709,7 @@ func (t *task) Kill(_ context.Context, signal syscall.Signal) error {
return err return err
} }
logger := t.ctr.client.logger.WithFields(logrus.Fields{ logger := t.ctr.client.logger.WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"process": t.id, "process": t.id,
"pid": t.Pid(), "pid": t.Pid(),
@ -748,7 +748,7 @@ func (p *process) Resize(_ context.Context, width, height uint32) error {
return errors.WithStack(errdefs.NotFound(errors.New("process not found"))) return errors.WithStack(errdefs.NotFound(errors.New("process not found")))
} }
p.ctr.client.logger.WithFields(logrus.Fields{ p.ctr.client.logger.WithFields(log.Fields{
"container": p.ctr.id, "container": p.ctr.id,
"process": p.id, "process": p.id,
"height": height, "height": height,
@ -795,12 +795,12 @@ func (t *task) Pause(_ context.Context) error {
ContainerID: t.ctr.id, ContainerID: t.ctr.id,
ProcessID: t.id, ProcessID: t.id,
}) })
t.ctr.client.logger.WithFields(logrus.Fields{ t.ctr.client.logger.WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventPaused, "event": libcontainerdtypes.EventPaused,
}).Info("sending event") }).Info("sending event")
if err != nil { if err != nil {
t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ t.ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventPaused, "event": libcontainerdtypes.EventPaused,
}).Error("failed to process event") }).Error("failed to process event")
@ -836,12 +836,12 @@ func (t *task) Resume(ctx context.Context) error {
ContainerID: t.ctr.id, ContainerID: t.ctr.id,
ProcessID: t.id, ProcessID: t.id,
}) })
t.ctr.client.logger.WithFields(logrus.Fields{ t.ctr.client.logger.WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventResumed, "event": libcontainerdtypes.EventResumed,
}).Info("sending event") }).Info("sending event")
if err != nil { if err != nil {
t.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ t.ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": t.ctr.id, "container": t.ctr.id,
"event": libcontainerdtypes.EventResumed, "event": libcontainerdtypes.EventResumed,
}).Error("failed to process event") }).Error("failed to process event")
@ -1109,7 +1109,7 @@ func (ctr *container) terminateContainer() error {
} }
func (p *process) reap() { func (p *process) reap() {
logger := p.ctr.client.logger.WithFields(logrus.Fields{ logger := p.ctr.client.logger.WithFields(log.Fields{
"container": p.ctr.id, "container": p.ctr.id,
"process": p.id, "process": p.id,
}) })
@ -1166,14 +1166,14 @@ func (p *process) reap() {
ExitedAt: exitedAt, ExitedAt: exitedAt,
Error: eventErr, Error: eventErr,
} }
p.ctr.client.logger.WithFields(logrus.Fields{ p.ctr.client.logger.WithFields(log.Fields{
"container": p.ctr.id, "container": p.ctr.id,
"event": libcontainerdtypes.EventExit, "event": libcontainerdtypes.EventExit,
"event-info": ei, "event-info": ei,
}).Info("sending event") }).Info("sending event")
err := p.ctr.client.backend.ProcessEvent(p.ctr.id, libcontainerdtypes.EventExit, ei) err := p.ctr.client.backend.ProcessEvent(p.ctr.id, libcontainerdtypes.EventExit, ei)
if err != nil { if err != nil {
p.ctr.client.logger.WithError(err).WithFields(logrus.Fields{ p.ctr.client.logger.WithError(err).WithFields(log.Fields{
"container": p.ctr.id, "container": p.ctr.id,
"event": libcontainerdtypes.EventExit, "event": libcontainerdtypes.EventExit,
"event-info": ei, "event-info": ei,
@ -1200,7 +1200,7 @@ func (ctr *container) Delete(context.Context) error {
} }
var ( var (
logger = ctr.client.logger.WithFields(logrus.Fields{ logger = ctr.client.logger.WithFields(log.Fields{
"container": ctr.id, "container": ctr.id,
}) })
thisErr error thisErr error

View file

@ -167,7 +167,7 @@ func (c *container) Start(ctx context.Context, checkpointDir string, withStdin b
if checkpoint != nil { if checkpoint != nil {
err := c.client.client.ContentStore().Delete(ctx, checkpoint.Digest) err := c.client.client.ContentStore().Delete(ctx, checkpoint.Digest)
if err != nil { if err != nil {
c.client.logger.WithError(err).WithFields(logrus.Fields{ c.client.logger.WithError(err).WithFields(log.Fields{
"ref": checkpointDir, "ref": checkpointDir,
"digest": checkpoint.Digest, "digest": checkpoint.Digest,
}).Warnf("failed to delete temporary checkpoint entry") }).Warnf("failed to delete temporary checkpoint entry")
@ -392,7 +392,7 @@ func (c *container) Delete(ctx context.Context) error {
} }
if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" { if os.Getenv("LIBCONTAINERD_NOCLEAN") != "1" {
if err := os.RemoveAll(bundle); err != nil { if err := os.RemoveAll(bundle); err != nil {
c.client.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{ c.client.logger.WithContext(ctx).WithError(err).WithFields(log.Fields{
"container": c.c8dCtr.ID(), "container": c.c8dCtr.ID(),
"bundle": bundle, "bundle": bundle,
}).Error("failed to remove state dir") }).Error("failed to remove state dir")
@ -573,7 +573,7 @@ func (c *client) processEvent(ctx context.Context, et libcontainerdtypes.EventTy
c.eventQ.Append(ei.ContainerID, func() { c.eventQ.Append(ei.ContainerID, func() {
err := c.backend.ProcessEvent(ei.ContainerID, et, ei) err := c.backend.ProcessEvent(ei.ContainerID, et, ei)
if err != nil { if err != nil {
c.logger.WithContext(ctx).WithError(err).WithFields(logrus.Fields{ c.logger.WithContext(ctx).WithError(err).WithFields(log.Fields{
"container": ei.ContainerID, "container": ei.ContainerID,
"event": et, "event": et,
"event-info": ei, "event-info": ei,
@ -718,7 +718,7 @@ func (c *client) processEventStream(ctx context.Context, ns string) {
ContainerID: t.ContainerID, ContainerID: t.ContainerID,
} }
case *apievents.TaskDelete: case *apievents.TaskDelete:
c.logger.WithFields(logrus.Fields{ c.logger.WithFields(log.Fields{
"topic": ev.Topic, "topic": ev.Topic,
"type": reflect.TypeOf(t), "type": reflect.TypeOf(t),
"container": t.ContainerID, "container": t.ContainerID,
@ -726,7 +726,7 @@ func (c *client) processEventStream(ctx context.Context, ns string) {
).Info("ignoring event") ).Info("ignoring event")
continue continue
default: default:
c.logger.WithFields(logrus.Fields{ c.logger.WithFields(log.Fields{
"topic": ev.Topic, "topic": ev.Topic,
"type": reflect.TypeOf(t), "type": reflect.TypeOf(t),
}, },

View file

@ -7,8 +7,8 @@ import (
winio "github.com/Microsoft/go-winio" winio "github.com/Microsoft/go-winio"
"github.com/containerd/containerd/cio" "github.com/containerd/containerd/cio"
"github.com/containerd/containerd/log"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
type delayedConnection struct { type delayedConnection struct {
@ -59,7 +59,7 @@ type stdioPipes struct {
func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) { func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
p := &stdioPipes{} p := &stdioPipes{}
if fifos.Stdin != "" { if fifos.Stdin != "" {
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("listen") c.logger.WithField("stdin", fifos.Stdin).Debug("listen")
l, err := winio.ListenPipe(fifos.Stdin, nil) l, err := winio.ListenPipe(fifos.Stdin, nil)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to create stdin pipe %s", fifos.Stdin) return nil, errors.Wrapf(err, "failed to create stdin pipe %s", fifos.Stdin)
@ -76,7 +76,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
p.stdin = dc p.stdin = dc
go func() { go func() {
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("accept") c.logger.WithField("stdin", fifos.Stdin).Debug("accept")
conn, err := l.Accept() conn, err := l.Accept()
if err != nil { if err != nil {
dc.Close() dc.Close()
@ -85,14 +85,14 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
} }
return return
} }
c.logger.WithFields(logrus.Fields{"stdin": fifos.Stdin}).Debug("connected") c.logger.WithField("stdin", fifos.Stdin).Debug("connected")
dc.con = conn dc.con = conn
dc.unblockConnectionWaiters() dc.unblockConnectionWaiters()
}() }()
} }
if fifos.Stdout != "" { if fifos.Stdout != "" {
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("listen") c.logger.WithField("stdout", fifos.Stdout).Debug("listen")
l, err := winio.ListenPipe(fifos.Stdout, nil) l, err := winio.ListenPipe(fifos.Stdout, nil)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to create stdout pipe %s", fifos.Stdout) return nil, errors.Wrapf(err, "failed to create stdout pipe %s", fifos.Stdout)
@ -109,23 +109,23 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
p.stdout = dc p.stdout = dc
go func() { go func() {
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("accept") c.logger.WithField("stdout", fifos.Stdout).Debug("accept")
conn, err := l.Accept() conn, err := l.Accept()
if err != nil { if err != nil {
dc.Close() dc.Close()
if err != winio.ErrPipeListenerClosed { if err != winio.ErrPipeListenerClosed {
c.logger.WithError(err).Errorf("failed to accept stdout connection on %s", fifos.Stdout) c.logger.WithFields(log.Fields{"error": err, "stdout": fifos.Stdout}).Error("failed to accept stdout connection")
} }
return return
} }
c.logger.WithFields(logrus.Fields{"stdout": fifos.Stdout}).Debug("connected") c.logger.WithField("stdout", fifos.Stdout).Debug("connected")
dc.con = conn dc.con = conn
dc.unblockConnectionWaiters() dc.unblockConnectionWaiters()
}() }()
} }
if fifos.Stderr != "" { if fifos.Stderr != "" {
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("listen") c.logger.WithField("stderr", fifos.Stderr).Debug("listen")
l, err := winio.ListenPipe(fifos.Stderr, nil) l, err := winio.ListenPipe(fifos.Stderr, nil)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to create stderr pipe %s", fifos.Stderr) return nil, errors.Wrapf(err, "failed to create stderr pipe %s", fifos.Stderr)
@ -142,7 +142,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
p.stderr = dc p.stderr = dc
go func() { go func() {
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("accept") c.logger.WithField("stderr", fifos.Stderr).Debug("accept")
conn, err := l.Accept() conn, err := l.Accept()
if err != nil { if err != nil {
dc.Close() dc.Close()
@ -151,7 +151,7 @@ func (c *client) newStdioPipes(fifos *cio.FIFOSet) (_ *stdioPipes, err error) {
} }
return return
} }
c.logger.WithFields(logrus.Fields{"stderr": fifos.Stderr}).Debug("connected") c.logger.WithField("stderr", fifos.Stderr).Debug("connected")
dc.con = conn dc.con = conn
dc.unblockConnectionWaiters() dc.unblockConnectionWaiters()
}() }()

View file

@ -12,8 +12,6 @@ import (
"os" "os"
"strings" "strings"
"github.com/sirupsen/logrus"
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/docker/docker/libnetwork" "github.com/docker/docker/libnetwork"
"github.com/docker/docker/libnetwork/diagnostic" "github.com/docker/docker/libnetwork/diagnostic"
@ -53,7 +51,7 @@ func main() {
flag.Parse() flag.Parse()
if *verbosePtr { if *verbosePtr {
logrus.SetLevel(logrus.DebugLevel) _ = log.SetLevel("debug")
} }
if _, ok := os.LookupEnv("DIND_CLIENT"); !ok && *joinPtr { if _, ok := os.LookupEnv("DIND_CLIENT"); !ok && *joinPtr {

View file

@ -4,18 +4,13 @@ import (
"context" "context"
"os" "os"
"github.com/sirupsen/logrus"
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/docker/docker/libnetwork/cmd/networkdb-test/dbclient" "github.com/docker/docker/libnetwork/cmd/networkdb-test/dbclient"
"github.com/docker/docker/libnetwork/cmd/networkdb-test/dbserver" "github.com/docker/docker/libnetwork/cmd/networkdb-test/dbserver"
) )
func main() { func main() {
formatter := &logrus.TextFormatter{ _ = log.SetFormat(log.TextFormat)
FullTimestamp: true,
}
logrus.SetFormatter(formatter)
log.G(context.TODO()).Infof("Starting the image with these args: %v", os.Args) log.G(context.TODO()).Infof("Starting the image with these args: %v", os.Args)
if len(os.Args) < 1 { if len(os.Args) < 1 {
log.G(context.TODO()).Fatal("You need at least 1 argument [client/server]") log.G(context.TODO()).Fatal("You need at least 1 argument [client/server]")

View file

@ -14,7 +14,6 @@ import (
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/docker/docker/libnetwork/internal/caller" "github.com/docker/docker/libnetwork/internal/caller"
"github.com/docker/docker/pkg/stack" "github.com/docker/docker/pkg/stack"
"github.com/sirupsen/logrus"
) )
// HTTPHandlerFunc TODO // HTTPHandlerFunc TODO
@ -130,24 +129,32 @@ func (s *Server) IsDiagnosticEnabled() bool {
} }
func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) { func notImplemented(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() //nolint:errcheck _ = r.ParseForm()
_, json := ParseHTTPFormOptions(r) _, jsonOutput := ParseHTTPFormOptions(r)
rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path)) rsp := WrongCommand("not implemented", fmt.Sprintf("URL path: %s no method implemented check /help\n", r.URL.Path))
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.G(context.TODO()).WithFields(log.Fields{
log.Info("command not implemented done") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
}).Info("command not implemented done")
HTTPReply(w, rsp, json) //nolint:errcheck _, _ = HTTPReply(w, rsp, jsonOutput)
} }
func help(ctx interface{}, w http.ResponseWriter, r *http.Request) { func help(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() //nolint:errcheck _ = r.ParseForm()
_, json := ParseHTTPFormOptions(r) _, jsonOutput := ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.G(context.TODO()).WithFields(log.Fields{
log.Info("help done") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
}).Info("help done")
n, ok := ctx.(*Server) n, ok := ctx.(*Server)
var result string var result string
@ -155,35 +162,39 @@ func help(ctx interface{}, w http.ResponseWriter, r *http.Request) {
for path := range n.registeredHanders { for path := range n.registeredHanders {
result += fmt.Sprintf("%s\n", path) result += fmt.Sprintf("%s\n", path)
} }
HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), json) //nolint:errcheck _, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: result}), jsonOutput)
} }
} }
func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) { func ready(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() //nolint:errcheck _ = r.ParseForm()
_, json := ParseHTTPFormOptions(r) _, jsonOutput := ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) log.G(context.TODO()).WithFields(log.Fields{
log.Info("ready done") "component": "diagnostic",
HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), json) //nolint:errcheck "remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
}).Info("ready done")
_, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: "OK"}), jsonOutput)
} }
func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) { func stackTrace(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() //nolint:errcheck _ = r.ParseForm()
_, json := ParseHTTPFormOptions(r) _, jsonOutput := ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()})
log.Info("stack trace") logger.Info("stack trace")
path, err := stack.DumpToFile("/tmp/") path, err := stack.DumpToFile("/tmp/")
if err != nil { if err != nil {
log.WithError(err).Error("failed to write goroutines dump") logger.WithError(err).Error("failed to write goroutines dump")
HTTPReply(w, FailCommand(err), json) //nolint:errcheck _, _ = HTTPReply(w, FailCommand(err), jsonOutput)
} else { } else {
log.Info("stack trace done") logger.Info("stack trace done")
HTTPReply(w, CommandSucceed(&StringCmd{Info: fmt.Sprintf("goroutine stacks written to %s", path)}), json) //nolint:errcheck _, _ = HTTPReply(w, CommandSucceed(&StringCmd{Info: "goroutine stacks written to " + path}), jsonOutput)
} }
} }
@ -203,12 +214,12 @@ type JSONOutput struct {
// ParseHTTPFormOptions easily parse the JSON printing options // ParseHTTPFormOptions easily parse the JSON printing options
func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) { func ParseHTTPFormOptions(r *http.Request) (bool, *JSONOutput) {
_, unsafe := r.Form["unsafe"] _, unsafe := r.Form["unsafe"]
v, json := r.Form["json"] v, enableJSON := r.Form["json"]
var pretty bool var pretty bool
if len(v) > 0 { if len(v) > 0 {
pretty = v[0] == "pretty" pretty = v[0] == "pretty"
} }
return unsafe, &JSONOutput{enable: json, prettyPrint: pretty} return unsafe, &JSONOutput{enable: enableJSON, prettyPrint: pretty}
} }
// HTTPReply helper function that takes care of sending the message out // HTTPReply helper function that takes care of sending the message out

View file

@ -22,7 +22,6 @@ import (
"github.com/docker/docker/libnetwork/osl" "github.com/docker/docker/libnetwork/osl"
"github.com/docker/docker/libnetwork/types" "github.com/docker/docker/libnetwork/types"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink" "github.com/vishvananda/netlink"
"github.com/vishvananda/netns" "github.com/vishvananda/netns"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
@ -217,15 +216,15 @@ func (d *driver) DeleteNetwork(nid string) error {
if n.secure { if n.secure {
for _, s := range n.subnets { for _, s := range n.subnets {
if err := programMangle(s.vni, false); err != nil { if err := programMangle(s.vni, false); err != nil {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"network_id": n.id, "network_id": n.id,
"subnet": s.subnetIP, "subnet": s.subnetIP,
}).Warn("Failed to clean up iptables rules during overlay network deletion") }).Warn("Failed to clean up iptables rules during overlay network deletion")
} }
if err := programInput(s.vni, false); err != nil { if err := programInput(s.vni, false); err != nil {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
logrus.ErrorKey: err, "error": err,
"network_id": n.id, "network_id": n.id,
"subnet": s.subnetIP, "subnet": s.subnetIP,
}).Warn("Failed to clean up iptables rules during overlay network deletion") }).Warn("Failed to clean up iptables rules during overlay network deletion")

View file

@ -14,7 +14,6 @@ import (
"github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringid"
"github.com/docker/go-events" "github.com/docker/go-events"
"github.com/hashicorp/memberlist" "github.com/hashicorp/memberlist"
"github.com/sirupsen/logrus"
"gotest.tools/v3/assert" "gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp" is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/poll" "gotest.tools/v3/poll"
@ -24,7 +23,7 @@ var dbPort int32 = 10000
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
os.WriteFile("/proc/sys/net/ipv6/conf/lo/disable_ipv6", []byte{'0', '\n'}, 0o644) os.WriteFile("/proc/sys/net/ipv6/conf/lo/disable_ipv6", []byte{'0', '\n'}, 0o644)
logrus.SetLevel(logrus.ErrorLevel) log.SetLevel("error")
os.Exit(m.Run()) os.Exit(m.Run())
} }
@ -840,7 +839,7 @@ func TestNetworkDBIslands(t *testing.T) {
return defaultTimeout return defaultTimeout
} }
logrus.SetLevel(logrus.DebugLevel) _ = log.SetLevel("debug")
conf := DefaultConfig() conf := DefaultConfig()
// Shorten durations to speed up test execution. // Shorten durations to speed up test execution.
conf.rejoinClusterDuration = conf.rejoinClusterDuration / 10 conf.rejoinClusterDuration = conf.rejoinClusterDuration / 10

View file

@ -10,7 +10,6 @@ import (
"github.com/containerd/containerd/log" "github.com/containerd/containerd/log"
"github.com/docker/docker/libnetwork/diagnostic" "github.com/docker/docker/libnetwork/diagnostic"
"github.com/docker/docker/libnetwork/internal/caller" "github.com/docker/docker/libnetwork/internal/caller"
"github.com/sirupsen/logrus"
) )
const ( const (
@ -34,17 +33,22 @@ var NetDbPaths2Func = map[string]diagnostic.HTTPHandlerFunc{
} }
func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("join cluster") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("join cluster")
if len(r.Form["members"]) < 1 { if len(r.Form["members"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?members=ip1,ip2,...", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?members=ip1,ip2,...", r.URL.Path))
log.Error("join cluster failed, wrong input") logger.Error("join cluster failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -54,12 +58,12 @@ func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) {
err := nDB.Join(strings.Split(r.Form["members"][0], ",")) err := nDB.Join(strings.Split(r.Form["members"][0], ","))
if err != nil { if err != nil {
rsp := diagnostic.FailCommand(fmt.Errorf("%s error in the DB join %s", r.URL.Path, err)) rsp := diagnostic.FailCommand(fmt.Errorf("%s error in the DB join %s", r.URL.Path, err))
log.WithError(err).Error("join cluster failed") logger.WithError(err).Error("join cluster failed")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
log.Info("join cluster done") logger.Info("join cluster done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -67,17 +71,22 @@ func dbJoin(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("network peers") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("network peers")
if len(r.Form["nid"]) < 1 { if len(r.Form["nid"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path))
log.Error("network peers failed, wrong input") logger.Error("network peers failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -93,7 +102,7 @@ func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP})
} }
} }
log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network peers done") logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network peers done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json)
return return
} }
@ -101,13 +110,18 @@ func dbPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("cluster peers") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("cluster peers")
nDB, ok := ctx.(*NetworkDB) nDB, ok := ctx.(*NetworkDB)
if ok { if ok {
@ -116,7 +130,7 @@ func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
for i, peerInfo := range peers { for i, peerInfo := range peers {
rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP}) rsp.Elements = append(rsp.Elements, &diagnostic.PeerEntryObj{Index: i, Name: peerInfo.Name, IP: peerInfo.IP})
} }
log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("cluster peers done") logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("cluster peers done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json)
return return
} }
@ -124,20 +138,25 @@ func dbClusterPeers(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
unsafe, json := diagnostic.ParseHTTPFormOptions(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("create entry") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("create entry")
if len(r.Form["tname"]) < 1 || if len(r.Form["tname"]) < 1 ||
len(r.Form["nid"]) < 1 || len(r.Form["nid"]) < 1 ||
len(r.Form["key"]) < 1 || len(r.Form["key"]) < 1 ||
len(r.Form["value"]) < 1 { len(r.Form["value"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path))
log.Error("create entry failed, wrong input") logger.Error("create entry failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -151,7 +170,7 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
var err error var err error
decodedValue, err = base64.StdEncoding.DecodeString(value) decodedValue, err = base64.StdEncoding.DecodeString(value)
if err != nil { if err != nil {
log.WithError(err).Error("create entry failed") logger.WithError(err).Error("create entry failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
@ -162,10 +181,10 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
if err := nDB.CreateEntry(tname, nid, key, decodedValue); err != nil { if err := nDB.CreateEntry(tname, nid, key, decodedValue); err != nil {
rsp := diagnostic.FailCommand(err) rsp := diagnostic.FailCommand(err)
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
log.WithError(err).Error("create entry failed") logger.WithError(err).Error("create entry failed")
return return
} }
log.Info("create entry done") logger.Info("create entry done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -173,20 +192,25 @@ func dbCreateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
unsafe, json := diagnostic.ParseHTTPFormOptions(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("update entry") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("update entry")
if len(r.Form["tname"]) < 1 || if len(r.Form["tname"]) < 1 ||
len(r.Form["nid"]) < 1 || len(r.Form["nid"]) < 1 ||
len(r.Form["key"]) < 1 || len(r.Form["key"]) < 1 ||
len(r.Form["value"]) < 1 { len(r.Form["value"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k&value=v", r.URL.Path))
log.Error("update entry failed, wrong input") logger.Error("update entry failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -200,7 +224,7 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
var err error var err error
decodedValue, err = base64.StdEncoding.DecodeString(value) decodedValue, err = base64.StdEncoding.DecodeString(value)
if err != nil { if err != nil {
log.WithError(err).Error("update entry failed") logger.WithError(err).Error("update entry failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
@ -209,11 +233,11 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
nDB, ok := ctx.(*NetworkDB) nDB, ok := ctx.(*NetworkDB)
if ok { if ok {
if err := nDB.UpdateEntry(tname, nid, key, decodedValue); err != nil { if err := nDB.UpdateEntry(tname, nid, key, decodedValue); err != nil {
log.WithError(err).Error("update entry failed") logger.WithError(err).Error("update entry failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
log.Info("update entry done") logger.Info("update entry done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -221,19 +245,24 @@ func dbUpdateEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("delete entry") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("delete entry")
if len(r.Form["tname"]) < 1 || if len(r.Form["tname"]) < 1 ||
len(r.Form["nid"]) < 1 || len(r.Form["nid"]) < 1 ||
len(r.Form["key"]) < 1 { len(r.Form["key"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path))
log.Error("delete entry failed, wrong input") logger.Error("delete entry failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -246,11 +275,11 @@ func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
if ok { if ok {
err := nDB.DeleteEntry(tname, nid, key) err := nDB.DeleteEntry(tname, nid, key)
if err != nil { if err != nil {
log.WithError(err).Error("delete entry failed") logger.WithError(err).Error("delete entry failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
log.Info("delete entry done") logger.Info("delete entry done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -258,19 +287,24 @@ func dbDeleteEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
unsafe, json := diagnostic.ParseHTTPFormOptions(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("get entry") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("get entry")
if len(r.Form["tname"]) < 1 || if len(r.Form["tname"]) < 1 ||
len(r.Form["nid"]) < 1 || len(r.Form["nid"]) < 1 ||
len(r.Form["key"]) < 1 { len(r.Form["key"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id&key=k", r.URL.Path))
log.Error("get entry failed, wrong input") logger.Error("get entry failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -283,7 +317,7 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
if ok { if ok {
value, err := nDB.GetEntry(tname, nid, key) value, err := nDB.GetEntry(tname, nid, key)
if err != nil { if err != nil {
log.WithError(err).Error("get entry failed") logger.WithError(err).Error("get entry failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
@ -296,7 +330,7 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
rsp := &diagnostic.TableEntryObj{Key: key, Value: encodedValue} rsp := &diagnostic.TableEntryObj{Key: key, Value: encodedValue}
log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get entry done") logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get entry done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json)
return return
} }
@ -304,17 +338,22 @@ func dbGetEntry(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("join network") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("join network")
if len(r.Form["nid"]) < 1 { if len(r.Form["nid"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path))
log.Error("join network failed, wrong input") logger.Error("join network failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -324,11 +363,11 @@ func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
nDB, ok := ctx.(*NetworkDB) nDB, ok := ctx.(*NetworkDB)
if ok { if ok {
if err := nDB.JoinNetwork(nid); err != nil { if err := nDB.JoinNetwork(nid); err != nil {
log.WithError(err).Error("join network failed") logger.WithError(err).Error("join network failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
log.Info("join network done") logger.Info("join network done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -336,17 +375,22 @@ func dbJoinNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("leave network") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("leave network")
if len(r.Form["nid"]) < 1 { if len(r.Form["nid"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=network_id", r.URL.Path))
log.Error("leave network failed, wrong input") logger.Error("leave network failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -356,11 +400,11 @@ func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
nDB, ok := ctx.(*NetworkDB) nDB, ok := ctx.(*NetworkDB)
if ok { if ok {
if err := nDB.LeaveNetwork(nid); err != nil { if err := nDB.LeaveNetwork(nid); err != nil {
log.WithError(err).Error("leave network failed") logger.WithError(err).Error("leave network failed")
diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json) diagnostic.HTTPReply(w, diagnostic.FailCommand(err), json)
return return
} }
log.Info("leave network done") logger.Info("leave network done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(nil), json)
return return
} }
@ -368,18 +412,23 @@ func dbLeaveNetwork(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
unsafe, json := diagnostic.ParseHTTPFormOptions(r) unsafe, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("get table") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("get table")
if len(r.Form["tname"]) < 1 || if len(r.Form["tname"]) < 1 ||
len(r.Form["nid"]) < 1 { len(r.Form["nid"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?tname=table_name&nid=network_id", r.URL.Path))
log.Error("get table failed, wrong input") logger.Error("get table failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -408,7 +457,7 @@ func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) {
}) })
i++ i++
} }
log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get table done") logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("get table done")
diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json) diagnostic.HTTPReply(w, diagnostic.CommandSucceed(rsp), json)
return return
} }
@ -416,17 +465,22 @@ func dbGetTable(ctx interface{}, w http.ResponseWriter, r *http.Request) {
} }
func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) { func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) {
r.ParseForm() _ = r.ParseForm()
diagnostic.DebugHTTPForm(r) diagnostic.DebugHTTPForm(r)
_, json := diagnostic.ParseHTTPFormOptions(r) _, json := diagnostic.ParseHTTPFormOptions(r)
// audit logs // audit logs
log := log.G(context.TODO()).WithFields(logrus.Fields{"component": "diagnostic", "remoteIP": r.RemoteAddr, "method": caller.Name(0), "url": r.URL.String()}) logger := log.G(context.TODO()).WithFields(log.Fields{
log.Info("network stats") "component": "diagnostic",
"remoteIP": r.RemoteAddr,
"method": caller.Name(0),
"url": r.URL.String(),
})
logger.Info("network stats")
if len(r.Form["nid"]) < 1 { if len(r.Form["nid"]) < 1 {
rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path)) rsp := diagnostic.WrongCommand(missingParameter, fmt.Sprintf("%s?nid=test", r.URL.Path))
log.Error("network stats failed, wrong input") logger.Error("network stats failed, wrong input")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }
@ -446,7 +500,7 @@ func dbNetworkStats(ctx interface{}, w http.ResponseWriter, r *http.Request) {
nDB.RUnlock() nDB.RUnlock()
rsp := diagnostic.CommandSucceed(&diagnostic.NetworkStatsResult{Entries: entries, QueueLen: qLen}) rsp := diagnostic.CommandSucceed(&diagnostic.NetworkStatsResult{Entries: entries, QueueLen: qLen})
log.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done") logger.WithField("response", fmt.Sprintf("%+v", rsp)).Info("network stats done")
diagnostic.HTTPReply(w, rsp, json) diagnostic.HTTPReply(w, rsp, json)
return return
} }

View file

@ -522,12 +522,12 @@ func (r *Resolver) exchange(proto string, extDNS extDNSEntry, query *dns.Msg) *d
} }
defer extConn.Close() defer extConn.Close()
log := r.log().WithFields(logrus.Fields{ logger := r.log().WithFields(log.Fields{
"dns-server": extConn.RemoteAddr().Network() + ":" + extConn.RemoteAddr().String(), "dns-server": extConn.RemoteAddr().Network() + ":" + extConn.RemoteAddr().String(),
"client-addr": extConn.LocalAddr().Network() + ":" + extConn.LocalAddr().String(), "client-addr": extConn.LocalAddr().Network() + ":" + extConn.LocalAddr().String(),
"question": query.Question[0].String(), "question": query.Question[0].String(),
}) })
log.Debug("[resolver] forwarding query") logger.Debug("[resolver] forwarding query")
resp, _, err := (&dns.Client{ resp, _, err := (&dns.Client{
Timeout: extIOTimeout, Timeout: extIOTimeout,
@ -549,7 +549,7 @@ func (r *Resolver) exchange(proto string, extDNS extDNSEntry, query *dns.Msg) *d
if resp == nil { if resp == nil {
// Should be impossible, so make noise if it happens anyway. // Should be impossible, so make noise if it happens anyway.
log.Error("[resolver] external DNS returned empty response") logger.Error("[resolver] external DNS returned empty response")
} }
return resp return resp
} }

View file

@ -30,7 +30,6 @@ import (
"github.com/moby/patternmatcher" "github.com/moby/patternmatcher"
"github.com/moby/sys/sequential" "github.com/moby/sys/sequential"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// ImpliedDirectoryMode represents the mode (Unix permissions) applied to directories that are implied by files in a // ImpliedDirectoryMode represents the mode (Unix permissions) applied to directories that are implied by files in a
@ -790,7 +789,7 @@ func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, o
} }
if len(xattrErrs) > 0 { if len(xattrErrs) > 0 {
log.G(context.TODO()).WithFields(logrus.Fields{ log.G(context.TODO()).WithFields(log.Fields{
"errors": xattrErrs, "errors": xattrErrs,
}).Warn("ignored xattrs in archive: underlying filesystem doesn't support them") }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them")
} }

View file

@ -76,13 +76,12 @@ func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) {
// Create creates a new container // Create creates a new container
func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error { func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
ctx := context.Background() ctx := context.Background()
log := log.G(ctx).WithField("plugin", id)
ctr, err := libcontainerd.ReplaceContainer(ctx, e.client, id, &spec, e.shim, e.shimOpts) ctr, err := libcontainerd.ReplaceContainer(ctx, e.client, id, &spec, e.shim, e.shimOpts)
if err != nil { if err != nil {
return errors.Wrap(err, "error creating containerd container for plugin") return errors.Wrap(err, "error creating containerd container for plugin")
} }
p := c8dPlugin{log: log, ctr: ctr} p := c8dPlugin{log: log.G(ctx).WithField("plugin", id), ctr: ctr}
p.tsk, err = ctr.Start(ctx, "", false, attachStreamsFunc(stdout, stderr)) p.tsk, err = ctr.Start(ctx, "", false, attachStreamsFunc(stdout, stderr))
if err != nil { if err != nil {
p.deleteTaskAndContainer(ctx) p.deleteTaskAndContainer(ctx)

View file

@ -311,7 +311,7 @@ func (logHook) Levels() []logrus.Level {
} }
func (l logHook) Fire(entry *logrus.Entry) error { func (l logHook) Fire(entry *logrus.Entry) error {
entry.Data = logrus.Fields{"plugin": l.id} entry.Data = log.Fields{"plugin": l.id}
return nil return nil
} }

View file

@ -1,15 +1,16 @@
package registry // import "github.com/docker/docker/registry" package registry // import "github.com/docker/docker/registry"
import ( import (
"context"
"net" "net"
"net/url" "net/url"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/containerd/containerd/log"
"github.com/docker/distribution/reference" "github.com/docker/distribution/reference"
"github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/registry"
"github.com/sirupsen/logrus"
) )
// ServiceOptions holds command line options. // ServiceOptions holds command line options.
@ -197,10 +198,10 @@ skip:
return err return err
} }
if strings.HasPrefix(strings.ToLower(r), "http://") { if strings.HasPrefix(strings.ToLower(r), "http://") {
logrus.Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r) log.G(context.TODO()).Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r)
r = r[7:] r = r[7:]
} else if strings.HasPrefix(strings.ToLower(r), "https://") { } else if strings.HasPrefix(strings.ToLower(r), "https://") {
logrus.Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r) log.G(context.TODO()).Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r)
r = r[8:] r = r[8:]
} else if hasScheme(r) { } else if hasScheme(r) {
return invalidParamf("insecure registry %s should not contain '://'", r) return invalidParamf("insecure registry %s should not contain '://'", r)

View file

@ -19,7 +19,6 @@ import (
"github.com/docker/docker/quota" "github.com/docker/docker/quota"
"github.com/docker/docker/volume" "github.com/docker/docker/volume"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
const ( const (
@ -390,7 +389,7 @@ func (v *localVolume) LiveRestoreVolume(ctx context.Context, _ string) error {
} }
v.active.count++ v.active.count++
v.active.mounted = true v.active.mounted = true
log.G(ctx).WithFields(logrus.Fields{ log.G(ctx).WithFields(log.Fields{
"volume": v.name, "volume": v.name,
"active mounts": v.active, "active mounts": v.active,
}).Debugf("Live restored volume") }).Debugf("Live restored volume")

View file

@ -14,7 +14,6 @@ import (
"github.com/docker/docker/volume" "github.com/docker/docker/volume"
"github.com/opencontainers/selinux/go-selinux/label" "github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
// MountPoint is the intersection point between a volume and a container. It // MountPoint is the intersection point between a volume and a container. It
@ -169,7 +168,7 @@ func (m *MountPoint) Setup(mountLabel string, rootIDs idtools.Identity, checkFun
func (m *MountPoint) LiveRestore(ctx context.Context) error { func (m *MountPoint) LiveRestore(ctx context.Context) error {
if m.Volume == nil { if m.Volume == nil {
logrus.Debug("No volume to restore") log.G(ctx).Debug("No volume to restore")
return nil return nil
} }