diff --git a/cmd/crio/main.go b/cmd/crio/main.go index 0ed159453da..5ce6f0f8476 100644 --- a/cmd/crio/main.go +++ b/cmd/crio/main.go @@ -63,9 +63,9 @@ func catchShutdown(ctx context.Context, cancel context.CancelFunc, gserver *grpc case unix.SIGPIPE: continue case signals.Interrupt: - logrus.Debugf("Caught SIGINT") + log.Debugf(ctx, "Caught SIGINT") case signals.Term: - logrus.Debugf("Caught SIGTERM") + log.Debugf(ctx, "Caught SIGTERM") default: continue } @@ -73,12 +73,12 @@ func catchShutdown(ctx context.Context, cancel context.CancelFunc, gserver *grpc gserver.GracefulStop() hserver.Shutdown(ctx) // nolint: errcheck if err := sserver.StopStreamServer(); err != nil { - logrus.Warnf("error shutting down streaming server: %v", err) + log.Warnf(ctx, "error shutting down streaming server: %v", err) } sserver.StopMonitors() cancel() if err := sserver.Shutdown(ctx); err != nil { - logrus.Warnf("error shutting down main service %v", err) + log.Warnf(ctx, "error shutting down main service %v", err) } return } @@ -186,9 +186,9 @@ func main() { profilePort := c.Int("profile-port") profileEndpoint := fmt.Sprintf("localhost:%v", profilePort) go func() { - logrus.Debugf("starting profiling server on %v", profileEndpoint) + log.Debugf(ctx, "starting profiling server on %v", profileEndpoint) if err := http.ListenAndServe(profileEndpoint, nil); err != nil { - logrus.Fatalf("unable to run profiling server: %v", err) + log.Fatalf(ctx, "unable to run profiling server: %v", err) } }() } @@ -212,7 +212,7 @@ func main() { lis, err := server.Listen("unix", config.Listen) if err != nil { - logrus.Fatalf("failed to listen: %v", err) + log.Fatalf(ctx, "failed to listen: %v", err) } grpcServer := grpc.NewServer( @@ -255,13 +255,13 @@ func main() { // CleanShutdownFile. f, err := os.Create(config.CleanShutdownSupportedFileName()) if err != nil { - logrus.Errorf("Writing clean shutdown supported file: %v", err) + log.Errorf(ctx, "Writing clean shutdown supported file: %v", err) } f.Close() // and sync the changes to disk if err := utils.SyncParent(config.CleanShutdownFile); err != nil { - logrus.Errorf("failed to sync parent directory of clean shutdown file: %v", err) + log.Errorf(ctx, "failed to sync parent directory of clean shutdown file: %v", err) } } @@ -301,12 +301,12 @@ func main() { go func() { if err := grpcServer.Serve(grpcL); err != nil { - logrus.Errorf("unable to run GRPC server: %v", err) + log.Errorf(ctx, "unable to run GRPC server: %v", err) } }() go func() { if err := httpServer.Serve(httpL); err != nil { - logrus.Debugf("closed http server") + log.Debugf(ctx, "closed http server") } }() @@ -317,7 +317,7 @@ func main() { if graceful && strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") { err = nil } else { - logrus.Errorf("Failed to serve grpc request: %v", err) + log.Errorf(ctx, "Failed to serve grpc request: %v", err) } } }() @@ -331,22 +331,22 @@ func main() { } if err := crioServer.Shutdown(ctx); err != nil { - logrus.Warnf("error shutting down service: %v", err) + log.Warnf(ctx, "error shutting down service: %v", err) } cancel() <-streamServerCloseCh - logrus.Debug("closed stream server") + log.Debugf(ctx, "closed stream server") <-serverMonitorsCh - logrus.Debug("closed monitors") + log.Debugf(ctx, "closed monitors") err = <-hookSync if err == nil || err == context.Canceled { - logrus.Debug("closed hook monitor") + log.Debugf(ctx, "closed hook monitor") } else { - logrus.Errorf("hook monitor failed: %v", err) + log.Errorf(ctx, "hook monitor failed: %v", err) } <-serverCloseCh - logrus.Debug("closed main server") + log.Debugf(ctx, "closed main server") return nil } diff --git a/internal/lib/container_server.go b/internal/lib/container_server.go index 11988d2dcf4..399ce89e6dd 100644 --- a/internal/lib/container_server.go +++ b/internal/lib/container_server.go @@ -15,6 +15,7 @@ import ( "github.com/containers/storage/pkg/truncindex" "github.com/cri-o/cri-o/internal/hostport" "github.com/cri-o/cri-o/internal/lib/sandbox" + "github.com/cri-o/cri-o/internal/log" "github.com/cri-o/cri-o/internal/oci" "github.com/cri-o/cri-o/internal/storage" crioann "github.com/cri-o/cri-o/pkg/annotations" @@ -232,7 +233,7 @@ func (c *ContainerServer) LoadSandbox(ctx context.Context, id string) (retErr er defer func() { if retErr != nil { if err := c.RemoveSandbox(sb.ID()); err != nil { - logrus.Warnf("could not remove sandbox ID %s: %v", sb.ID(), err) + log.Warnf(ctx, "could not remove sandbox ID %s: %v", sb.ID(), err) } } }() @@ -338,7 +339,7 @@ func (c *ContainerServer) LoadSandbox(ctx context.Context, id string) (retErr er defer func() { if retErr != nil { if err1 := c.ctrIDIndex.Delete(scontainer.ID()); err1 != nil { - logrus.Warnf("could not delete container ID %s: %v", scontainer.ID(), err1) + log.Warnf(ctx, "could not delete container ID %s: %v", scontainer.ID(), err1) } } }() @@ -492,7 +493,7 @@ func (c *ContainerServer) ContainerStateFromDisk(ctx context.Context, ctr *oci.C // on disk func (c *ContainerServer) ContainerStateToDisk(ctx context.Context, ctr *oci.Container) error { if err := c.Runtime().UpdateContainerStatus(ctx, ctr); err != nil { - logrus.Warnf("error updating the container status %q: %v", ctr.ID(), err) + log.Warnf(ctx, "error updating the container status %q: %v", ctr.ID(), err) } jsonSource, err := ioutils.NewAtomicFileWriter(ctr.StatePath(), 0o644) diff --git a/internal/lib/stop.go b/internal/lib/stop.go index 87479d42f13..08e115684dc 100644 --- a/internal/lib/stop.go +++ b/internal/lib/stop.go @@ -3,9 +3,10 @@ package lib import ( "context" + "github.com/cri-o/cri-o/internal/log" + "github.com/cri-o/cri-o/internal/oci" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // ContainerStop stops a running container with a grace period (i.e., timeout). @@ -36,7 +37,7 @@ func (c *ContainerServer) ContainerStop(ctx context.Context, container string, t } if err := c.ContainerStateToDisk(ctx, ctr); err != nil { - logrus.Warnf("unable to write containers %s state to disk: %v", ctr.ID(), err) + log.Warnf(ctx, "unable to write containers %s state to disk: %v", ctr.ID(), err) } return ctrID, nil diff --git a/internal/log/log.go b/internal/log/log.go index 2d46efb8587..13235a40d25 100644 --- a/internal/log/log.go +++ b/internal/log/log.go @@ -28,6 +28,10 @@ func Errorf(ctx context.Context, format string, args ...interface{}) { entry(ctx).Errorf(format, args...) } +func Fatalf(ctx context.Context, format string, args ...interface{}) { + entry(ctx).Fatalf(format, args...) +} + func entry(ctx context.Context) *logrus.Entry { logger := logrus.StandardLogger() if ctx == nil { diff --git a/internal/log/log_test.go b/internal/log/log_test.go index 7152cf65011..f903cdd8659 100644 --- a/internal/log/log_test.go +++ b/internal/log/log_test.go @@ -137,4 +137,17 @@ var _ = t.Describe("Log", func() { Expect(buf.String()).To(BeEmpty()) }) }) + + t.Describe("Fatalf", func() { + BeforeEach(func() { beforeEach(logrus.FatalLevel) }) + + It("should not error log", func() { + // Given + // When + log.Errorf(ctx, msg) + + // Then + Expect(buf.String()).To(BeEmpty()) + }) + }) }) diff --git a/internal/oci/runtime_oci.go b/internal/oci/runtime_oci.go index 3ac764b9783..261a8023cf2 100644 --- a/internal/oci/runtime_oci.go +++ b/internal/oci/runtime_oci.go @@ -187,7 +187,7 @@ func (r *runtimeOCI) CreateContainer(ctx context.Context, c *Container, cgroupPa defer func() { if retErr != nil { if err := r.DeleteContainer(ctx, c); err != nil { - logrus.Warnf("unable to delete container %s: %v", c.ID(), err) + log.Warnf(ctx, "unable to delete container %s: %v", c.ID(), err) } } }() @@ -214,18 +214,18 @@ func (r *runtimeOCI) CreateContainer(ctx context.Context, c *Container, cgroupPa if ss.err != nil { return fmt.Errorf("error reading container (probably exited) json message: %v", ss.err) } - logrus.Debugf("Received container pid: %d", ss.si.Pid) + log.Debugf(ctx, "Received container pid: %d", ss.si.Pid) pid = ss.si.Pid if ss.si.Pid == -1 { if ss.si.Message != "" { - logrus.Errorf("Container creation error: %s", ss.si.Message) + log.Errorf(ctx, "Container creation error: %s", ss.si.Message) return fmt.Errorf("container create failed: %s", ss.si.Message) } - logrus.Errorf("Container creation failed") + log.Errorf(ctx, "Container creation failed") return fmt.Errorf("container create failed") } case <-time.After(ContainerCreateTimeout): - logrus.Errorf("Container creation timeout (%v)", ContainerCreateTimeout) + log.Errorf(ctx, "Container creation timeout (%v)", ContainerCreateTimeout) return fmt.Errorf("create container timeout") } @@ -274,7 +274,7 @@ func prepareExec() (pidFileName string, parentPipe, childPipe *os.File, _ error) return pidFileName, parentPipe, childPipe, nil } -func parseLog(l []byte) (stdout, stderr []byte) { +func parseLog(ctx context.Context, l []byte) (stdout, stderr []byte) { // Split the log on newlines, which is what separates entries. lines := bytes.SplitAfter(l, []byte{'\n'}) for _, line := range lines { @@ -288,7 +288,7 @@ func parseLog(l []byte) (stdout, stderr []byte) { if len(parts) < 4 { // Ignore the line if it's formatted incorrectly, but complain // about it so it can be debugged. - logrus.Warnf("hit invalid log format: %q", string(line)) + log.Warnf(ctx, "hit invalid log format: %q", string(line)) continue } @@ -310,7 +310,7 @@ func parseLog(l []byte) (stdout, stderr []byte) { stderr = append(stderr, content...) default: // Complain about unknown pipes. - logrus.Warnf("hit invalid log format [unknown pipe %s]: %q", pipe, string(line)) + log.Warnf(ctx, "hit invalid log format [unknown pipe %s]: %q", pipe, string(line)) continue } } @@ -404,7 +404,7 @@ func (r *runtimeOCI) ExecSyncContainer(ctx context.Context, c *Container, comman defer parentPipe.Close() defer func() { if e := os.Remove(pidFile); e != nil { - logrus.Warnf("could not remove temporary PID file %s", pidFile) + log.Warnf(ctx, "could not remove temporary PID file %s", pidFile) } }() @@ -492,7 +492,7 @@ func (r *runtimeOCI) ExecSyncContainer(ctx context.Context, c *Container, comman var ec *exitCodeInfo decodeErr := json.NewDecoder(parentPipe).Decode(&ec) if decodeErr == nil { - logrus.Debugf("Received container exit code: %v, message: %s", ec.ExitCode, ec.Message) + log.Debugf(ctx, "Received container exit code: %v, message: %s", ec.ExitCode, ec.Message) // When we timeout the command in conmon then we should return // an ExecSyncResponse with a non-zero exit code because @@ -553,7 +553,7 @@ func (r *runtimeOCI) ExecSyncContainer(ctx context.Context, c *Container, comman } // We have to parse the log output into {stdout, stderr} buffers. - stdoutBytes, stderrBytes := parseLog(logBytes) + stdoutBytes, stderrBytes := parseLog(ctx, logBytes) return &ExecSyncResponse{ Stdout: stdoutBytes, Stderr: stderrBytes, @@ -606,7 +606,7 @@ func WaitContainerStop(ctx context.Context, c *Container, timeout time.Duration, if err := c.verifyPid(); err != nil { // The initial container process either doesn't exist, or isn't ours. if !errors.Is(err, ErrNotFound) { - logrus.Warnf("failed to find process for container %s: %v", c.id, err) + log.Warnf(ctx, "failed to find process for container %s: %v", c.id, err) } close(done) return @@ -707,7 +707,7 @@ func (r *runtimeOCI) StopContainer(ctx context.Context, c *Container, timeout in if err == nil { return nil } - logrus.Warnf("Stopping container %v with stop signal timed out: %v", c.id, err) + log.Warnf(ctx, "Stopping container %v with stop signal timed out: %v", c.id, err) } if _, err := utils.ExecCmd( @@ -772,7 +772,7 @@ func (r *runtimeOCI) UpdateContainerStatus(ctx context.Context, c *Container) er } if c.state.ExitCode != nil && !c.state.Finished.IsZero() { - logrus.Debugf("Skipping status update for: %+v", c.state) + log.Debugf(ctx, "Skipping status update for: %+v", c.state) return nil } @@ -790,9 +790,9 @@ func (r *runtimeOCI) UpdateContainerStatus(ctx context.Context, c *Container) er // We always populate the fields below so kube can restart/reschedule // containers failing. if exitErr, isExitError := err.(*exec.ExitError); isExitError { - logrus.Errorf("failed to update container state for %s: stdout: %s, stderr: %s", c.id, string(out), string(exitErr.Stderr)) + log.Errorf(ctx, "failed to update container state for %s: stdout: %s, stderr: %s", c.id, string(out), string(exitErr.Stderr)) } else { - logrus.Errorf("failed to update container state for %s: %v", c.id, err) + log.Errorf(ctx, "failed to update container state for %s: %v", c.id, err) } c.state.Status = ContainerStateStopped if err := updateContainerStatusFromExitFile(c); err != nil { @@ -849,7 +849,7 @@ func (r *runtimeOCI) UpdateContainerStatus(ctx context.Context, c *Container) er } *c.state = *state if err != nil { - logrus.Warnf("failed to find container exit file for %v: %v", c.id, err) + log.Warnf(ctx, "failed to find container exit file for %v: %v", c.id, err) } else { c.state.Finished, err = getFinishedTime(fi) if err != nil { @@ -864,7 +864,7 @@ func (r *runtimeOCI) UpdateContainerStatus(ctx context.Context, c *Container) er return fmt.Errorf("status code conversion failed: %v", err) } c.state.ExitCode = utils.Int32Ptr(int32(statusCode)) - logrus.Debugf("found exit code for %s: %d", c.id, statusCode) + log.Debugf(ctx, "found exit code for %s: %d", c.id, statusCode) } oomFilePath := filepath.Join(c.bundlePath, "oom") @@ -945,10 +945,10 @@ func (r *runtimeOCI) AttachContainer(ctx context.Context, c *Container, inputStr defer controlFile.Close() kubecontainer.HandleResizing(resize, func(size remotecommand.TerminalSize) { - logrus.Debugf("Got a resize event: %+v", size) + log.Debugf(ctx, "Got a resize event: %+v", size) _, err := fmt.Fprintf(controlFile, "%d %d %d\n", 1, size.Height, size.Width) if err != nil { - logrus.Debugf("Failed to write to control file to resize terminal: %v", err) + log.Debugf(ctx, "Failed to write to control file to resize terminal: %v", err) } }) @@ -1126,11 +1126,11 @@ func (r *runtimeOCI) ReopenContainerLog(ctx context.Context, c *Container) error for { select { case event := <-watcher.Events: - logrus.Debugf("event: %v", event) + log.Debugf(ctx, "event: %v", event) if event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Write == fsnotify.Write { - logrus.Debugf("file created %s", event.Name) + log.Debugf(ctx, "file created %s", event.Name) if event.Name == c.LogPath() { - logrus.Debugf("expected log file created") + log.Debugf(ctx, "expected log file created") done <- struct{}{} return } @@ -1144,13 +1144,13 @@ func (r *runtimeOCI) ReopenContainerLog(ctx context.Context, c *Container) error }() cLogDir := filepath.Dir(c.LogPath()) if err := watcher.Add(cLogDir); err != nil { - logrus.Errorf("watcher.Add(%q) failed: %s", cLogDir, err) + log.Errorf(ctx, "watcher.Add(%q) failed: %s", cLogDir, err) close(done) doneClosed = true } if _, err = fmt.Fprintf(controlFile, "%d %d %d\n", 2, 0, 0); err != nil { - logrus.Debugf("Failed to write to control file to reopen log file: %v", err) + log.Debugf(ctx, "Failed to write to control file to reopen log file: %v", err) } select { diff --git a/internal/oci/runtime_vm.go b/internal/oci/runtime_vm.go index 7a62fa8a7a6..16c9e7f8f46 100644 --- a/internal/oci/runtime_vm.go +++ b/internal/oci/runtime_vm.go @@ -17,6 +17,7 @@ import ( "github.com/containerd/containerd/runtime/v2/task" "github.com/containerd/ttrpc" "github.com/containers/podman/v3/pkg/cgroups" + "github.com/cri-o/cri-o/internal/log" "github.com/cri-o/cri-o/utils" "github.com/cri-o/cri-o/utils/errdefs" "github.com/cri-o/cri-o/utils/fifo" @@ -75,8 +76,8 @@ func newRuntimeVM(path, root string) RuntimeImpl { // CreateContainer creates a container. func (r *runtimeVM) CreateContainer(ctx context.Context, c *Container, cgroupParent string) (retErr error) { - logrus.Debug("runtimeVM.CreateContainer() start") - defer logrus.Debug("runtimeVM.CreateContainer() end") + log.Debugf(ctx, "runtimeVM.CreateContainer() start") + defer log.Debugf(ctx, "runtimeVM.CreateContainer() end") // Lock the container c.opLock.Lock() @@ -117,7 +118,7 @@ func (r *runtimeVM) CreateContainer(ctx context.Context, c *Container, cgroupPar if stderrCh != nil { <-stderrCh } - logrus.Debugf("Finish redirecting log file %q, closing it", c.LogPath()) + log.Debugf(ctx, "Finish redirecting log file %q, closing it", c.LogPath()) f.Close() }() @@ -178,8 +179,8 @@ func (r *runtimeVM) CreateContainer(ctx context.Context, c *Container, cgroupPar } func (r *runtimeVM) startRuntimeDaemon(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.startRuntimeDaemon() start") - defer logrus.Debug("runtimeVM.startRuntimeDaemon() end") + log.Debugf(ctx, "runtimeVM.startRuntimeDaemon() start") + defer log.Debugf(ctx, "runtimeVM.startRuntimeDaemon() end") // Prepare the command to run args := []string{"-id", c.ID()} @@ -251,8 +252,8 @@ func (r *runtimeVM) startRuntimeDaemon(ctx context.Context, c *Container) error // StartContainer starts a container. func (r *runtimeVM) StartContainer(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.StartContainer() start") - defer logrus.Debug("runtimeVM.StartContainer() end") + log.Debugf(ctx, "runtimeVM.StartContainer() start") + defer log.Debugf(ctx, "runtimeVM.StartContainer() end") // Lock the container c.opLock.Lock() @@ -269,10 +270,10 @@ func (r *runtimeVM) StartContainer(ctx context.Context, c *Container) error { _, err := r.wait(ctx, c.ID(), "") if err == nil { if err1 := r.updateContainerStatus(ctx, c); err1 != nil { - logrus.Warningf("error updating container status %v", err1) + log.Warnf(ctx, "error updating container status %v", err1) } } else { - logrus.Warningf("wait for %s returned: %v", c.ID(), err) + log.Warnf(ctx, "wait for %s returned: %v", c.ID(), err) } }() @@ -281,8 +282,8 @@ func (r *runtimeVM) StartContainer(ctx context.Context, c *Container) error { // ExecContainer prepares a streaming endpoint to execute a command in the container. func (r *runtimeVM) ExecContainer(ctx context.Context, c *Container, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { - logrus.Debug("runtimeVM.ExecContainer() start") - defer logrus.Debug("runtimeVM.ExecContainer() end") + log.Debugf(ctx, "runtimeVM.ExecContainer() start") + defer log.Debugf(ctx, "runtimeVM.ExecContainer() end") exitCode, err := r.execContainerCommon(ctx, c, cmd, 0, stdin, stdout, stderr, tty, resize) if err != nil { @@ -300,8 +301,8 @@ func (r *runtimeVM) ExecContainer(ctx context.Context, c *Container, cmd []strin // ExecSyncContainer execs a command in a container and returns it's stdout, stderr and return code. func (r *runtimeVM) ExecSyncContainer(ctx context.Context, c *Container, command []string, timeout int64) (*ExecSyncResponse, error) { - logrus.Debug("runtimeVM.ExecSyncContainer() start") - defer logrus.Debug("runtimeVM.ExecSyncContainer() end") + log.Debugf(ctx, "runtimeVM.ExecSyncContainer() start") + defer log.Debugf(ctx, "runtimeVM.ExecSyncContainer() end") var stdoutBuf, stderrBuf bytes.Buffer stdout := cioutil.NewNopWriteCloser(&stdoutBuf) @@ -323,8 +324,8 @@ func (r *runtimeVM) ExecSyncContainer(ctx context.Context, c *Container, command } func (r *runtimeVM) execContainerCommon(ctx context.Context, c *Container, cmd []string, timeout int64, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) (exitCode int32, retErr error) { - logrus.Debug("runtimeVM.execContainerCommon() start") - defer logrus.Debug("runtimeVM.execContainerCommon() end") + log.Debugf(ctx, "runtimeVM.execContainerCommon() start") + defer log.Debugf(ctx, "runtimeVM.execContainerCommon() end") // Cancel the context before returning to ensure goroutines are stopped. ctx, cancel := context.WithCancel(ctx) @@ -391,7 +392,7 @@ func (r *runtimeVM) execContainerCommon(ctx context.Context, c *Container, cmd [ defer func() { if retErr != nil { if err := r.remove(ctx, c.ID(), execID); err != nil { - logrus.Debugf("unable to remove container %s: %v", c.ID(), err) + log.Debugf(ctx, "unable to remove container %s: %v", c.ID(), err) } } }() @@ -408,10 +409,10 @@ func (r *runtimeVM) execContainerCommon(ctx context.Context, c *Container, cmd [ // Initialize terminal resizing if necessary if resize != nil { kubecontainer.HandleResizing(resize, func(size remotecommand.TerminalSize) { - logrus.Debugf("Got a resize event: %+v", size) + log.Debugf(ctx, "Got a resize event: %+v", size) if err := r.resizePty(ctx, c.ID(), execID, size); err != nil { - logrus.Warnf("Failed to resize terminal: %v", err) + log.Warnf(ctx, "Failed to resize terminal: %v", err) } }) } @@ -456,7 +457,7 @@ func (r *runtimeVM) execContainerCommon(ctx context.Context, c *Container, cmd [ if err == nil { // Delete the process if err := r.remove(ctx, c.ID(), execID); err != nil { - logrus.Debugf("unable to remove container %s: %v", c.ID(), err) + log.Debugf(ctx, "unable to remove container %s: %v", c.ID(), err) } } @@ -465,8 +466,8 @@ func (r *runtimeVM) execContainerCommon(ctx context.Context, c *Container, cmd [ // UpdateContainer updates container resources func (r *runtimeVM) UpdateContainer(ctx context.Context, c *Container, res *rspec.LinuxResources) error { - logrus.Debug("runtimeVM.UpdateContainer() start") - defer logrus.Debug("runtimeVM.UpdateContainer() end") + log.Debugf(ctx, "runtimeVM.UpdateContainer() start") + defer log.Debugf(ctx, "runtimeVM.UpdateContainer() end") // Lock the container c.opLock.Lock() @@ -490,8 +491,8 @@ func (r *runtimeVM) UpdateContainer(ctx context.Context, c *Container, res *rspe // StopContainer stops a container. Timeout is given in seconds. func (r *runtimeVM) StopContainer(ctx context.Context, c *Container, timeout int64) error { - logrus.Debug("runtimeVM.StopContainer() start") - defer logrus.Debug("runtimeVM.StopContainer() end") + log.Debugf(ctx, "runtimeVM.StopContainer() start") + defer log.Debugf(ctx, "runtimeVM.StopContainer() end") // Lock the container c.opLock.Lock() @@ -533,7 +534,7 @@ func (r *runtimeVM) StopContainer(ctx context.Context, c *Container, timeout int c.state.Finished = time.Now() return nil } - logrus.Warnf("%v", err) + log.Warnf(ctx, "%v", err) } sig = syscall.SIGKILL @@ -543,7 +544,7 @@ func (r *runtimeVM) StopContainer(ctx context.Context, c *Container, timeout int } if err := r.waitCtrTerminate(sig, stopCh, killContainerTimeout); err != nil { - logrus.Errorf("%v", err) + log.Errorf(ctx, "%v", err) return err } @@ -562,8 +563,8 @@ func (r *runtimeVM) waitCtrTerminate(sig syscall.Signal, stopCh chan error, time // DeleteContainer deletes a container. func (r *runtimeVM) DeleteContainer(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.DeleteContainer() start") - defer logrus.Debug("runtimeVM.DeleteContainer() end") + log.Debugf(ctx, "runtimeVM.DeleteContainer() start") + defer log.Debugf(ctx, "runtimeVM.DeleteContainer() end") // Lock the container c.opLock.Lock() @@ -605,8 +606,8 @@ func (r *runtimeVM) deleteContainer(ctx context.Context, c *Container, force boo // UpdateContainerStatus refreshes the status of the container. func (r *runtimeVM) UpdateContainerStatus(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.UpdateContainerStatus() start") - defer logrus.Debug("runtimeVM.UpdateContainerStatus() end") + log.Debugf(ctx, "runtimeVM.UpdateContainerStatus() start") + defer log.Debugf(ctx, "runtimeVM.UpdateContainerStatus() end") // Lock the container c.opLock.Lock() @@ -619,8 +620,8 @@ func (r *runtimeVM) UpdateContainerStatus(ctx context.Context, c *Container) err // status refresh. // It does **not** Lock the container, thus it's the caller responsibility to do so, when needed. func (r *runtimeVM) updateContainerStatus(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.updateContainerStatus() start") - defer logrus.Debug("runtimeVM.updateContainerStatus() end") + log.Debugf(ctx, "runtimeVM.updateContainerStatus() start") + defer log.Debugf(ctx, "runtimeVM.updateContainerStatus() end") // This can happen on restore, for example if we switch the runtime type // for a container from "oci" to "vm" for the same runtime. @@ -667,8 +668,8 @@ func (r *runtimeVM) updateContainerStatus(ctx context.Context, c *Container) err // PauseContainer pauses a container. func (r *runtimeVM) PauseContainer(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.PauseContainer() start") - defer logrus.Debug("runtimeVM.PauseContainer() end") + log.Debugf(ctx, "runtimeVM.PauseContainer() start") + defer log.Debugf(ctx, "runtimeVM.PauseContainer() end") // Lock the container c.opLock.Lock() @@ -685,8 +686,8 @@ func (r *runtimeVM) PauseContainer(ctx context.Context, c *Container) error { // UnpauseContainer unpauses a container. func (r *runtimeVM) UnpauseContainer(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.UnpauseContainer() start") - defer logrus.Debug("runtimeVM.UnpauseContainer() end") + log.Debugf(ctx, "runtimeVM.UnpauseContainer() start") + defer log.Debugf(ctx, "runtimeVM.UnpauseContainer() end") // Lock the container c.opLock.Lock() @@ -703,8 +704,8 @@ func (r *runtimeVM) UnpauseContainer(ctx context.Context, c *Container) error { // ContainerStats provides statistics of a container. func (r *runtimeVM) ContainerStats(ctx context.Context, c *Container, _ string) (*ContainerStats, error) { - logrus.Debug("runtimeVM.ContainerStats() start") - defer logrus.Debug("runtimeVM.ContainerStats() end") + log.Debugf(ctx, "runtimeVM.ContainerStats() start") + defer log.Debugf(ctx, "runtimeVM.ContainerStats() end") // Lock the container with a shared lock c.opLock.RLock() @@ -735,8 +736,8 @@ func (r *runtimeVM) ContainerStats(ctx context.Context, c *Container, _ string) // SignalContainer sends a signal to a container process. func (r *runtimeVM) SignalContainer(ctx context.Context, c *Container, sig syscall.Signal) error { - logrus.Debug("runtimeVM.SignalContainer() start") - defer logrus.Debug("runtimeVM.SignalContainer() end") + log.Debugf(ctx, "runtimeVM.SignalContainer() start") + defer log.Debugf(ctx, "runtimeVM.SignalContainer() end") // Lock the container c.opLock.Lock() @@ -747,15 +748,15 @@ func (r *runtimeVM) SignalContainer(ctx context.Context, c *Container, sig sysca // AttachContainer attaches IO to a running container. func (r *runtimeVM) AttachContainer(ctx context.Context, c *Container, inputStream io.Reader, outputStream, errorStream io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { - logrus.Debug("runtimeVM.AttachContainer() start") - defer logrus.Debug("runtimeVM.AttachContainer() end") + log.Debugf(ctx, "runtimeVM.AttachContainer() start") + defer log.Debugf(ctx, "runtimeVM.AttachContainer() end") // Initialize terminal resizing kubecontainer.HandleResizing(resize, func(size remotecommand.TerminalSize) { - logrus.Debugf("Got a resize event: %+v", size) + log.Debugf(ctx, "Got a resize event: %+v", size) if err := r.resizePty(ctx, c.ID(), "", size); err != nil { - logrus.Warnf("Failed to resize terminal: %v", err) + log.Warnf(ctx, "Failed to resize terminal: %v", err) } }) @@ -781,17 +782,17 @@ func (r *runtimeVM) AttachContainer(ctx context.Context, c *Container, inputStre } // PortForwardContainer forwards the specified port provides statistics of a container. -func (r *runtimeVM) PortForwardContainer(context.Context, *Container, string, int32, io.ReadWriteCloser) error { - logrus.Debug("runtimeVM.PortForwardContainer() start") - defer logrus.Debug("runtimeVM.PortForwardContainer() end") +func (r *runtimeVM) PortForwardContainer(ctx context.Context, c *Container, netNsPath string, port int32, stream io.ReadWriteCloser) error { + log.Debugf(ctx, "runtimeVM.PortForwardContainer() start") + defer logrus.Debug(ctx, "runtimeVM.PortForwardContainer() end") return nil } // ReopenContainerLog reopens the log file of a container. func (r *runtimeVM) ReopenContainerLog(ctx context.Context, c *Container) error { - logrus.Debug("runtimeVM.ReopenContainerLog() start") - defer logrus.Debug("runtimeVM.ReopenContainerLog() end") + log.Debugf(ctx, "runtimeVM.ReopenContainerLog() start") + defer log.Debugf(ctx, "runtimeVM.ReopenContainerLog() end") return nil } diff --git a/server/server.go b/server/server.go index 23daea33019..75a94e3f9c8 100644 --- a/server/server.go +++ b/server/server.go @@ -21,6 +21,7 @@ import ( "github.com/cri-o/cri-o/internal/hostport" "github.com/cri-o/cri-o/internal/lib" "github.com/cri-o/cri-o/internal/lib/sandbox" + "github.com/cri-o/cri-o/internal/log" "github.com/cri-o/cri-o/internal/oci" "github.com/cri-o/cri-o/internal/resourcestore" "github.com/cri-o/cri-o/internal/runtimehandlerhooks" @@ -161,7 +162,7 @@ func (s *Server) getPortForward(req *types.PortForwardRequest) (*types.PortForwa func (s *Server) restore(ctx context.Context) { containers, err := s.Store().Containers() if err != nil && !errors.Is(err, os.ErrNotExist) { - logrus.Warnf("could not read containers and sandboxes: %v", err) + log.Warnf(ctx, "could not read containers and sandboxes: %v", err) } pods := map[string]*storage.RuntimeContainerMetadata{} podContainers := map[string]*storage.RuntimeContainerMetadata{} @@ -170,11 +171,11 @@ func (s *Server) restore(ctx context.Context) { for i := range containers { metadata, err2 := s.StorageRuntimeServer().GetContainerMetadata(containers[i].ID) if err2 != nil { - logrus.Warnf("error parsing metadata for %s: %v, ignoring", containers[i].ID, err2) + log.Warnf(ctx, "error parsing metadata for %s: %v, ignoring", containers[i].ID, err2) continue } if !storage.IsCrioContainer(&metadata) { - logrus.Debugf("container %s determined to not be a CRI-O container or sandbox", containers[i].ID) + log.Debugf(ctx, "container %s determined to not be a CRI-O container or sandbox", containers[i].ID) continue } names[containers[i].ID] = containers[i].Names @@ -191,10 +192,10 @@ func (s *Server) restore(ctx context.Context) { if err = s.LoadSandbox(ctx, sbID); err == nil { continue } - logrus.Warnf("could not restore sandbox %s container %s: %v", metadata.PodID, sbID, err) + log.Warnf(ctx, "could not restore sandbox %s container %s: %v", metadata.PodID, sbID, err) for _, n := range names[sbID] { if err := s.Store().DeleteContainer(n); err != nil { - logrus.Warnf("unable to delete container %s: %v", n, err) + log.Warnf(ctx, "unable to delete container %s: %v", n, err) } // Release the infra container name and the pod name for future use if strings.Contains(n, infraName) { @@ -204,12 +205,12 @@ func (s *Server) restore(ctx context.Context) { } } // Go through the containers and delete any container that was under the deleted pod - logrus.Warnf("deleting all containers under sandbox %s since it could not be restored", sbID) + log.Warnf(ctx, "deleting all containers under sandbox %s since it could not be restored", sbID) for k, v := range podContainers { if v.PodID == sbID { for _, n := range names[k] { if err := s.Store().DeleteContainer(n); err != nil { - logrus.Warnf("unable to delete container %s: %v", n, err) + log.Warnf(ctx, "unable to delete container %s: %v", n, err) } // Release the container name for future use s.ReleaseContainerName(n) @@ -226,12 +227,12 @@ func (s *Server) restore(ctx context.Context) { if err := s.LoadContainer(ctx, containerID); err != nil { // containers of other runtimes should not be deleted if err == lib.ErrIsNonCrioContainer { - logrus.Infof("ignoring non CRI-O container %s", containerID) + log.Infof(ctx, "ignoring non CRI-O container %s", containerID) } else { - logrus.Warnf("could not restore container %s: %v", containerID, err) + log.Warnf(ctx, "could not restore container %s: %v", containerID, err) for _, n := range names[containerID] { if err := s.Store().DeleteContainer(n); err != nil { - logrus.Warnf("unable to delete container %s: %v", n, err) + log.Warnf(ctx, "unable to delete container %s: %v", n, err) } // Release the container name s.ReleaseContainerName(n) @@ -245,13 +246,13 @@ func (s *Server) restore(ctx context.Context) { // Clean up networking if pod couldn't be restored and was deleted if ok := deletedPods[sb.ID()]; ok { if err := s.networkStop(ctx, sb); err != nil { - logrus.Warnf("error stopping network on restore cleanup %v:", err) + log.Warnf(ctx, "error stopping network on restore cleanup %v:", err) } continue } ips, err := s.getSandboxIPs(sb) if err != nil { - logrus.Warnf("could not restore sandbox IP for %v: %v", sb.ID(), err) + log.Warnf(ctx, "could not restore sandbox IP for %v: %v", sb.ID(), err) continue } sb.AddIPs(ips) @@ -262,11 +263,11 @@ func (s *Server) restore(ctx context.Context) { func (s *Server) cleanupSandboxesOnShutdown(ctx context.Context) { _, err := os.Stat(shutdownFile) if err == nil || !os.IsNotExist(err) { - logrus.Debugf("shutting down all sandboxes, on shutdown") + log.Debugf(ctx, "shutting down all sandboxes, on shutdown") s.stopAllPodSandboxes(ctx) err = os.Remove(shutdownFile) if err != nil { - logrus.Warnf("Failed to remove %q", shutdownFile) + log.Warnf(ctx, "Failed to remove %q", shutdownFile) } } } @@ -471,11 +472,11 @@ func New( go func() { defer close(s.stream.streamServerCloseCh) if err := s.stream.streamServer.Start(true); err != nil && err != http.ErrServerClosed { - logrus.Fatalf("Failed to start streaming server: %v", err) + log.Fatalf(ctx, "Failed to start streaming server: %v", err) } }() - logrus.Debugf("sandboxes: %v", s.ContainerServer.ListSandboxes()) + log.Debugf(ctx, "sandboxes: %v", s.ContainerServer.ListSandboxes()) // Start a configuration watcher for the default config s.config.StartWatcher() @@ -611,7 +612,7 @@ func (s *Server) MonitorsCloseChan() chan struct{} { func (s *Server) StartExitMonitor(ctx context.Context) { watcher, err := fsnotify.NewWatcher() if err != nil { - logrus.Fatalf("Failed to create new watch: %v", err) + log.Fatalf(ctx, "Failed to create new watch: %v", err) } defer watcher.Close() @@ -620,50 +621,50 @@ func (s *Server) StartExitMonitor(ctx context.Context) { for { select { case event := <-watcher.Events: - logrus.Debugf("event: %v", event) + log.Debugf(ctx, "event: %v", event) if event.Op&fsnotify.Create == fsnotify.Create { containerID := filepath.Base(event.Name) - logrus.Debugf("container or sandbox exited: %v", containerID) + log.Debugf(ctx, "container or sandbox exited: %v", containerID) c := s.GetContainer(containerID) if c != nil { - logrus.Debugf("container exited and found: %v", containerID) + log.Debugf(ctx, "container exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(ctx, c) if err != nil { - logrus.Warnf("Failed to update container status %s: %v", containerID, err) + log.Warnf(ctx, "Failed to update container status %s: %v", containerID, err) } else if err := s.ContainerStateToDisk(ctx, c); err != nil { - logrus.Warnf("unable to write containers %s state to disk: %v", c.ID(), err) + log.Warnf(ctx, "unable to write containers %s state to disk: %v", c.ID(), err) } } else { sb := s.GetSandbox(containerID) if sb != nil { c := sb.InfraContainer() if c == nil { - logrus.Warnf("no infra container set for sandbox: %v", containerID) + log.Warnf(ctx, "no infra container set for sandbox: %v", containerID) continue } - logrus.Debugf("sandbox exited and found: %v", containerID) + log.Debugf(ctx, "sandbox exited and found: %v", containerID) err := s.Runtime().UpdateContainerStatus(ctx, c) if err != nil { - logrus.Warnf("Failed to update sandbox infra container status %s: %v", c.ID(), err) + log.Warnf(ctx, "Failed to update sandbox infra container status %s: %v", c.ID(), err) } else if err := s.ContainerStateToDisk(ctx, c); err != nil { - logrus.Warnf("unable to write containers %s state to disk: %v", c.ID(), err) + log.Warnf(ctx, "unable to write containers %s state to disk: %v", c.ID(), err) } } } } case err := <-watcher.Errors: - logrus.Debugf("watch error: %v", err) + log.Debugf(ctx, "watch error: %v", err) close(done) return case <-s.monitorsChan: - logrus.Debug("closing exit monitor...") + log.Debugf(ctx, "closing exit monitor...") close(done) return } } }() if err := watcher.Add(s.config.ContainerExitsDir); err != nil { - logrus.Errorf("watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err) + log.Errorf(ctx, "watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err) close(done) } <-done diff --git a/test/copyimg/copyimg.go b/test/copyimg/copyimg.go index 01c36a06ed4..cf967bfa3f5 100644 --- a/test/copyimg/copyimg.go +++ b/test/copyimg/copyimg.go @@ -12,6 +12,7 @@ import ( "github.com/containers/podman/v3/pkg/rootless" sstorage "github.com/containers/storage" "github.com/containers/storage/pkg/reexec" + "github.com/cri-o/cri-o/internal/log" "github.com/sirupsen/logrus" "github.com/urfave/cli/v2" ) @@ -97,11 +98,11 @@ func main() { if imageName != "" { if rootDir == "" && runrootDir != "" { - logrus.Errorf("must set --root and --runroot, or neither") + log.Errorf(ctx, "must set --root and --runroot, or neither") os.Exit(1) } if rootDir != "" && runrootDir == "" { - logrus.Errorf("must set --root and --runroot, or neither") + log.Errorf(ctx, "must set --root and --runroot, or neither") os.Exit(1) } storeOptions, err := sstorage.DefaultStoreOptions(rootless.IsRootless(), rootless.GetRootlessUID()) @@ -116,20 +117,20 @@ func main() { } store, err = sstorage.GetStore(storeOptions) if err != nil { - logrus.Errorf("error opening storage: %v", err) + log.Errorf(ctx, "error opening storage: %v", err) os.Exit(1) } defer func() { _, err = store.Shutdown(false) if err != nil { - logrus.Warnf("unable to shutdown store: %v", err) + log.Warnf(ctx, "unable to shutdown store: %v", err) } }() storage.Transport.SetStore(store) ref, err = storage.Transport.ParseStoreReference(store, imageName) if err != nil { - logrus.Errorf("error parsing image name: %v", err) + log.Errorf(ctx, "error parsing image name: %v", err) os.Exit(1) } } @@ -139,18 +140,18 @@ func main() { } policy, err := signature.DefaultPolicy(&systemContext) if err != nil { - logrus.Errorf("error loading signature policy: %v", err) + log.Errorf(ctx, "error loading signature policy: %v", err) os.Exit(1) } policyContext, err := signature.NewPolicyContext(policy) if err != nil { - logrus.Errorf("error loading signature policy: %v", err) + log.Errorf(ctx, "error loading signature policy: %v", err) os.Exit(1) } defer func() { err = policyContext.Destroy() if err != nil { - logrus.Fatalf("unable to destroy policy context: %v", err) + log.Fatalf(ctx, "unable to destroy policy context: %v", err) } }() options := ©.Options{} @@ -158,7 +159,7 @@ func main() { if importFrom != "" { importRef, err = alltransports.ParseImageName(importFrom) if err != nil { - logrus.Errorf("error parsing image name %v: %v", importFrom, err) + log.Errorf(ctx, "error parsing image name %v: %v", importFrom, err) os.Exit(1) } } @@ -166,7 +167,7 @@ func main() { if exportTo != "" { exportRef, err = alltransports.ParseImageName(exportTo) if err != nil { - logrus.Errorf("error parsing image name %v: %v", exportTo, err) + log.Errorf(ctx, "error parsing image name %v: %v", exportTo, err) os.Exit(1) } } @@ -175,34 +176,34 @@ func main() { if importFrom != "" { _, err = copy.Image(ctx, policyContext, ref, importRef, options) if err != nil { - logrus.Errorf("error importing %s: %v", importFrom, err) + log.Errorf(ctx, "error importing %s: %v", importFrom, err) os.Exit(1) } } if addName != "" { destImage, err1 := storage.Transport.GetStoreImage(store, ref) if err1 != nil { - logrus.Errorf("error finding image: %v", err1) + log.Errorf(ctx, "error finding image: %v", err1) os.Exit(1) } names := append(destImage.Names, imageName, addName) err = store.SetNames(destImage.ID, names) if err != nil { - logrus.Errorf("error adding name to %s: %v", imageName, err) + log.Errorf(ctx, "error adding name to %s: %v", imageName, err) os.Exit(1) } } if exportTo != "" { _, err = copy.Image(ctx, policyContext, exportRef, ref, options) if err != nil { - logrus.Errorf("error exporting %s: %v", exportTo, err) + log.Errorf(ctx, "error exporting %s: %v", exportTo, err) os.Exit(1) } } } else if importFrom != "" && exportTo != "" { _, err = copy.Image(ctx, policyContext, exportRef, importRef, options) if err != nil { - logrus.Errorf("error copying %s to %s: %v", importFrom, exportTo, err) + log.Errorf(ctx, "error copying %s to %s: %v", importFrom, exportTo, err) os.Exit(1) } }