diff --git a/cli/create.go b/cli/create.go index b7183a686..c202e7827 100644 --- a/cli/create.go +++ b/cli/create.go @@ -18,7 +18,6 @@ import ( vc "github.com/kata-containers/runtime/virtcontainers" vf "github.com/kata-containers/runtime/virtcontainers/factory" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -96,15 +95,15 @@ func create(ctx context.Context, containerID, bundlePath, console, pidFilePath s runtimeConfig oci.RuntimeConfig) error { var err error - span, ctx := opentracing.StartSpanFromContext(ctx, "create") + span, ctx := trace(ctx, "create") defer span.Finish() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - if bundlePath, err = validCreateParams(containerID, bundlePath); err != nil { + if bundlePath, err = validCreateParams(ctx, containerID, bundlePath); err != nil { return err } @@ -129,16 +128,16 @@ func create(ctx context.Context, containerID, bundlePath, console, pidFilePath s }, } kataLog.WithField("factory", factoryConfig).Info("load vm factory") - f, err := vf.NewFactory(factoryConfig, true) + f, err := vf.NewFactory(ctx, factoryConfig, true) if err != nil { kataLog.WithError(err).Warn("load vm factory failed, about to create new one") - f, err = vf.NewFactory(factoryConfig, false) + f, err = vf.NewFactory(ctx, factoryConfig, false) if err != nil { kataLog.WithError(err).Warn("create vm factory failed") } } if err == nil { - vci.SetFactory(f) + vci.SetFactory(ctx, f) } } @@ -254,7 +253,7 @@ func setKernelParams(containerID string, runtimeConfig *oci.RuntimeConfig) error func createSandbox(ctx context.Context, ociSpec oci.CompatOCISpec, runtimeConfig oci.RuntimeConfig, containerID, bundlePath, console string, disableOutput bool) (vc.Process, error) { - span, ctx := opentracing.StartSpanFromContext(ctx, "createSandbox") + span, ctx := trace(ctx, "createSandbox") defer span.Finish() err := setKernelParams(containerID, &runtimeConfig) @@ -267,14 +266,14 @@ func createSandbox(ctx context.Context, ociSpec oci.CompatOCISpec, runtimeConfig return vc.Process{}, err } - sandbox, err := vci.CreateSandbox(sandboxConfig) + sandbox, err := vci.CreateSandbox(ctx, sandboxConfig) if err != nil { return vc.Process{}, err } sid := sandbox.ID() kataLog = kataLog.WithField("sandbox", sid) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("sandbox", sid) containers := sandbox.GetAllContainers() @@ -306,7 +305,7 @@ func setEphemeralStorageType(ociSpec oci.CompatOCISpec) oci.CompatOCISpec { func createContainer(ctx context.Context, ociSpec oci.CompatOCISpec, containerID, bundlePath, console string, disableOutput bool) (vc.Process, error) { - span, ctx := opentracing.StartSpanFromContext(ctx, "createContainer") + span, ctx := trace(ctx, "createContainer") defer span.Finish() ociSpec = setEphemeralStorageType(ociSpec) @@ -322,10 +321,10 @@ func createContainer(ctx context.Context, ociSpec oci.CompatOCISpec, containerID } kataLog = kataLog.WithField("sandbox", sandboxID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("sandbox", sandboxID) - _, c, err := vci.CreateContainer(sandboxID, contConfig) + _, c, err := vci.CreateContainer(ctx, sandboxID, contConfig) if err != nil { return vc.Process{}, err } @@ -338,7 +337,7 @@ func createContainer(ctx context.Context, ociSpec oci.CompatOCISpec, containerID } func createCgroupsFiles(ctx context.Context, containerID string, cgroupsDirPath string, cgroupsPathList []string, pid int) error { - span, _ := opentracing.StartSpanFromContext(ctx, "createCgroupsFiles") + span, _ := trace(ctx, "createCgroupsFiles") defer span.Finish() if len(cgroupsPathList) == 0 { @@ -384,7 +383,7 @@ func createCgroupsFiles(ctx context.Context, containerID string, cgroupsDirPath } func createPIDFile(ctx context.Context, pidFilePath string, pid int) error { - span, _ := opentracing.StartSpanFromContext(ctx, "createPIDFile") + span, _ := trace(ctx, "createPIDFile") defer span.Finish() if pidFilePath == "" { diff --git a/cli/create_test.go b/cli/create_test.go index 609d2e30b..87046873c 100644 --- a/cli/create_test.go +++ b/cli/create_test.go @@ -293,7 +293,7 @@ func TestCreateInvalidArgs(t *testing.T) { }, } - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } @@ -488,7 +488,7 @@ func TestCreateProcessCgroupsPathSuccessful(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } @@ -583,7 +583,7 @@ func TestCreateCreateCgroupsFilesFail(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } @@ -668,7 +668,7 @@ func TestCreateCreateCreatePidFileFail(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } @@ -739,7 +739,7 @@ func TestCreate(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } @@ -1028,7 +1028,7 @@ func TestCreateCreateContainer(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.CreateContainerFunc = func(sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { + testingImpl.CreateContainerFunc = func(ctx context.Context, sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { return &vcmock.Sandbox{}, &vcmock.Container{}, nil } diff --git a/cli/delete.go b/cli/delete.go index 6dad8ffb5..4b359a899 100644 --- a/cli/delete.go +++ b/cli/delete.go @@ -13,7 +13,6 @@ import ( vc "github.com/kata-containers/runtime/virtcontainers" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -60,15 +59,15 @@ EXAMPLE: } func delete(ctx context.Context, containerID string, force bool) error { - span, ctx := opentracing.StartSpanFromContext(ctx, "delete") + span, ctx := trace(ctx, "delete") defer span.Finish() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -80,7 +79,7 @@ func delete(ctx context.Context, containerID string, force bool) error { "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) @@ -134,21 +133,21 @@ func delete(ctx context.Context, containerID string, force bool) error { } func deleteSandbox(ctx context.Context, sandboxID string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "deleteSandbox") + span, _ := trace(ctx, "deleteSandbox") defer span.Finish() - status, err := vci.StatusSandbox(sandboxID) + status, err := vci.StatusSandbox(ctx, sandboxID) if err != nil { return err } if oci.StateToOCIState(status.State) != oci.StateStopped { - if _, err := vci.StopSandbox(sandboxID); err != nil { + if _, err := vci.StopSandbox(ctx, sandboxID); err != nil { return err } } - if _, err := vci.DeleteSandbox(sandboxID); err != nil { + if _, err := vci.DeleteSandbox(ctx, sandboxID); err != nil { return err } @@ -156,16 +155,16 @@ func deleteSandbox(ctx context.Context, sandboxID string) error { } func deleteContainer(ctx context.Context, sandboxID, containerID string, forceStop bool) error { - span, _ := opentracing.StartSpanFromContext(ctx, "deleteContainer") + span, _ := trace(ctx, "deleteContainer") defer span.Finish() if forceStop { - if _, err := vci.StopContainer(sandboxID, containerID); err != nil { + if _, err := vci.StopContainer(ctx, sandboxID, containerID); err != nil { return err } } - if _, err := vci.DeleteContainer(sandboxID, containerID); err != nil { + if _, err := vci.DeleteContainer(ctx, sandboxID, containerID); err != nil { return err } @@ -173,7 +172,7 @@ func deleteContainer(ctx context.Context, sandboxID, containerID string, forceSt } func removeCgroupsPath(ctx context.Context, containerID string, cgroupsPathList []string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "removeCgroupsPath") + span, _ := trace(ctx, "removeCgroupsPath") defer span.Finish() if len(cgroupsPathList) == 0 { diff --git a/cli/delete_test.go b/cli/delete_test.go index eba9e3224..041ea3aee 100644 --- a/cli/delete_test.go +++ b/cli/delete_test.go @@ -77,7 +77,7 @@ func TestDeleteMissingContainerTypeAnnotation(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{}, @@ -104,7 +104,7 @@ func TestDeleteInvalidConfig(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -156,7 +156,7 @@ func TestDeleteSandbox(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -177,7 +177,7 @@ func TestDeleteSandbox(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.StatusSandboxFunc = func(sandboxID string) (vc.SandboxStatus, error) { + testingImpl.StatusSandboxFunc = func(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) { return vc.SandboxStatus{ ID: sandbox.ID(), State: vc.State{ @@ -194,7 +194,7 @@ func TestDeleteSandbox(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.StopSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StopSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -206,7 +206,7 @@ func TestDeleteSandbox(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -234,7 +234,7 @@ func TestDeleteInvalidContainerType(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -273,7 +273,7 @@ func TestDeleteSandboxRunning(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -295,7 +295,7 @@ func TestDeleteSandboxRunning(t *testing.T) { assert.Error(err) assert.False(vcmock.IsMockError(err)) - testingImpl.StatusSandboxFunc = func(sandboxID string) (vc.SandboxStatus, error) { + testingImpl.StatusSandboxFunc = func(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) { return vc.SandboxStatus{ ID: sandbox.ID(), State: vc.State{ @@ -304,7 +304,7 @@ func TestDeleteSandboxRunning(t *testing.T) { }, nil } - testingImpl.StopSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StopSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -318,7 +318,7 @@ func TestDeleteSandboxRunning(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -353,7 +353,7 @@ func TestDeleteRunningContainer(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.MockContainers[0].ID(), Annotations: map[string]string{ @@ -397,7 +397,7 @@ func TestDeleteRunningContainer(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &vcmock.Container{}, nil } @@ -436,7 +436,7 @@ func TestDeleteContainer(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.MockContainers[0].ID(), Annotations: map[string]string{ @@ -470,7 +470,7 @@ func TestDeleteContainer(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &vcmock.Container{}, nil } @@ -536,7 +536,7 @@ func TestDeleteCLIFunctionSuccess(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -549,7 +549,7 @@ func TestDeleteCLIFunctionSuccess(t *testing.T) { }, nil } - testingImpl.StatusSandboxFunc = func(sandboxID string) (vc.SandboxStatus, error) { + testingImpl.StatusSandboxFunc = func(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) { return vc.SandboxStatus{ ID: sandbox.ID(), State: vc.State{ @@ -558,11 +558,11 @@ func TestDeleteCLIFunctionSuccess(t *testing.T) { }, nil } - testingImpl.StopSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StopSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } diff --git a/cli/events.go b/cli/events.go index d9d8d6948..e50ae1296 100644 --- a/cli/events.go +++ b/cli/events.go @@ -14,7 +14,6 @@ import ( "time" vc "github.com/kata-containers/runtime/virtcontainers" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" @@ -142,7 +141,7 @@ information is displayed once every 5 seconds.`, return err } - span, _ := opentracing.StartSpanFromContext(ctx, "events") + span, _ := trace(ctx, "events") defer span.Finish() containerID := context.Args().First() @@ -151,7 +150,7 @@ information is displayed once every 5 seconds.`, } kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) duration := context.Duration("interval") @@ -159,7 +158,7 @@ information is displayed once every 5 seconds.`, return fmt.Errorf("duration interval must be greater than 0") } - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -171,7 +170,7 @@ information is displayed once every 5 seconds.`, "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) @@ -196,7 +195,7 @@ information is displayed once every 5 seconds.`, }() if context.Bool("stats") { - s, err := vci.StatsContainer(sandboxID, containerID) + s, err := vci.StatsContainer(ctx, sandboxID, containerID) if err != nil { return err } @@ -208,7 +207,7 @@ information is displayed once every 5 seconds.`, go func() { for range time.Tick(context.Duration("interval")) { - s, err := vci.StatsContainer(sandboxID, containerID) + s, err := vci.StatsContainer(ctx, sandboxID, containerID) if err != nil { logrus.Error(err) continue diff --git a/cli/events_test.go b/cli/events_test.go index 7138d9d81..e544202b5 100644 --- a/cli/events_test.go +++ b/cli/events_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "flag" "os" "testing" @@ -74,7 +75,7 @@ func TestEventsCLIFailure(t *testing.T) { }, } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -104,7 +105,7 @@ func TestEventsCLISuccessful(t *testing.T) { }, } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -116,7 +117,7 @@ func TestEventsCLISuccessful(t *testing.T) { }, nil } - testingImpl.StatsContainerFunc = func(sandboxID, containerID string) (vc.ContainerStats, error) { + testingImpl.StatsContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStats, error) { return vc.ContainerStats{}, nil } diff --git a/cli/exec.go b/cli/exec.go index 47130b353..de559b026 100644 --- a/cli/exec.go +++ b/cli/exec.go @@ -17,7 +17,6 @@ import ( vc "github.com/kata-containers/runtime/virtcontainers" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" specs "github.com/opencontainers/runtime-spec/specs-go" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -189,22 +188,22 @@ func generateExecParams(context *cli.Context, specProcess *oci.CompatOCIProcess) } func execute(ctx context.Context, context *cli.Context) error { - span, ctx := opentracing.StartSpanFromContext(ctx, "execute") + span, ctx := trace(ctx, "execute") defer span.Finish() containerID := context.Args().First() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } kataLog = kataLog.WithField("sandbox", sandboxID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("sandbox", sandboxID) // Retrieve OCI spec configuration. @@ -222,7 +221,7 @@ func execute(ctx context.Context, context *cli.Context) error { containerID = params.cID kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // container MUST be ready or running. @@ -258,7 +257,7 @@ func execute(ctx context.Context, context *cli.Context) error { Detach: noNeedForOutput(params.detach, params.ociProcess.Terminal), } - _, _, process, err := vci.EnterContainer(sandboxID, params.cID, cmd) + _, _, process, err := vci.EnterContainer(ctx, sandboxID, params.cID, cmd) if err != nil { return err } diff --git a/cli/exec_test.go b/cli/exec_test.go index c9a6832e4..8319b5da0 100644 --- a/cli/exec_test.go +++ b/cli/exec_test.go @@ -76,7 +76,7 @@ func TestExecuteErrors(t *testing.T) { vcAnnotations.ContainerTypeKey: string(vc.PodSandbox), } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, vc.State{}, annotations), nil } @@ -100,7 +100,7 @@ func TestExecuteErrors(t *testing.T) { } containerState := vc.State{} - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, containerState, annotations), nil } @@ -112,7 +112,7 @@ func TestExecuteErrors(t *testing.T) { containerState = vc.State{ State: vc.StatePaused, } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, containerState, annotations), nil } @@ -124,7 +124,7 @@ func TestExecuteErrors(t *testing.T) { containerState = vc.State{ State: vc.StateStopped, } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, containerState, annotations), nil } @@ -166,7 +166,7 @@ func TestExecuteErrorReadingProcessJson(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -215,7 +215,7 @@ func TestExecuteErrorOpeningConsole(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -282,7 +282,7 @@ func TestExecuteWithFlags(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -299,7 +299,7 @@ func TestExecuteWithFlags(t *testing.T) { assert.True(vcmock.IsMockError(err)) - testingImpl.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + testingImpl.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { return &vcmock.Sandbox{}, &vcmock.Container{}, &vc.Process{}, nil } @@ -316,7 +316,7 @@ func TestExecuteWithFlags(t *testing.T) { os.Remove(pidFilePath) // Process ran and exited successfully - testingImpl.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + testingImpl.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { // create a fake container process workload := []string{"cat", "/dev/null"} command := exec.Command(workload[0], workload[1:]...) @@ -372,7 +372,7 @@ func TestExecuteWithFlagsDetached(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -380,7 +380,7 @@ func TestExecuteWithFlagsDetached(t *testing.T) { testingImpl.StatusContainerFunc = nil }() - testingImpl.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + testingImpl.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { // create a fake container process workload := []string{"cat", "/dev/null"} command := exec.Command(workload[0], workload[1:]...) @@ -451,7 +451,7 @@ func TestExecuteWithInvalidProcessJson(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -503,7 +503,7 @@ func TestExecuteWithValidProcessJson(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -542,7 +542,7 @@ func TestExecuteWithValidProcessJson(t *testing.T) { workload := []string{"cat", "/dev/null"} - testingImpl.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + testingImpl.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { // create a fake container process command := exec.Command(workload[0], workload[1:]...) err := command.Start() @@ -604,7 +604,7 @@ func TestExecuteWithEmptyEnvironmentValue(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -644,7 +644,7 @@ func TestExecuteWithEmptyEnvironmentValue(t *testing.T) { workload := []string{"cat", "/dev/null"} - testingImpl.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + testingImpl.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { // create a fake container process command := exec.Command(workload[0], workload[1:]...) err := command.Start() diff --git a/cli/factory.go b/cli/factory.go index 7b462e64c..3ed658aac 100644 --- a/cli/factory.go +++ b/cli/factory.go @@ -33,8 +33,13 @@ var factoryCLICommand = cli.Command{ var initFactoryCommand = cli.Command{ Name: "init", Usage: "initialize a VM factory based on kata-runtime configuration", - Action: func(context *cli.Context) error { - runtimeConfig, ok := context.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) + Action: func(c *cli.Context) error { + ctx, err := cliContextToContext(c) + if err != nil { + return err + } + + runtimeConfig, ok := c.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) if !ok { return errors.New("invalid runtime config") } @@ -50,7 +55,7 @@ var initFactoryCommand = cli.Command{ }, } kataLog.WithField("factory", factoryConfig).Info("create vm factory") - _, err := vf.NewFactory(factoryConfig, false) + _, err := vf.NewFactory(ctx, factoryConfig, false) if err != nil { kataLog.WithError(err).Error("create vm factory failed") return err @@ -68,8 +73,13 @@ var initFactoryCommand = cli.Command{ var destroyFactoryCommand = cli.Command{ Name: "destroy", Usage: "destroy the VM factory", - Action: func(context *cli.Context) error { - runtimeConfig, ok := context.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) + Action: func(c *cli.Context) error { + ctx, err := cliContextToContext(c) + if err != nil { + return err + } + + runtimeConfig, ok := c.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) if !ok { return errors.New("invalid runtime config") } @@ -85,12 +95,12 @@ var destroyFactoryCommand = cli.Command{ }, } kataLog.WithField("factory", factoryConfig).Info("load vm factory") - f, err := vf.NewFactory(factoryConfig, true) + f, err := vf.NewFactory(ctx, factoryConfig, true) if err != nil { kataLog.WithError(err).Error("load vm factory failed") // ignore error } else { - f.CloseFactory() + f.CloseFactory(ctx) } } fmt.Fprintln(defaultOutputFile, "vm factory destroyed") @@ -101,8 +111,13 @@ var destroyFactoryCommand = cli.Command{ var statusFactoryCommand = cli.Command{ Name: "status", Usage: "query the status of VM factory", - Action: func(context *cli.Context) error { - runtimeConfig, ok := context.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) + Action: func(c *cli.Context) error { + ctx, err := cliContextToContext(c) + if err != nil { + return err + } + + runtimeConfig, ok := c.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) if !ok { return errors.New("invalid runtime config") } @@ -118,11 +133,11 @@ var statusFactoryCommand = cli.Command{ }, } kataLog.WithField("factory", factoryConfig).Info("load vm factory") - f, err := vf.NewFactory(factoryConfig, true) + f, err := vf.NewFactory(ctx, factoryConfig, true) if err != nil { fmt.Fprintln(defaultOutputFile, "vm factory is off") } else { - f.CloseFactory() + f.CloseFactory(ctx) fmt.Fprintln(defaultOutputFile, "vm factory is on") } } else { diff --git a/cli/kata-check.go b/cli/kata-check.go index 84ce48008..8f6b1057c 100644 --- a/cli/kata-check.go +++ b/cli/kata-check.go @@ -24,7 +24,6 @@ import ( "syscall" vc "github.com/kata-containers/runtime/virtcontainers" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -288,7 +287,7 @@ var kataCheckCLICommand = cli.Command{ return err } - span, _ := opentracing.StartSpanFromContext(ctx, "kata-check") + span, _ := trace(ctx, "kata-check") defer span.Finish() setCPUtype() diff --git a/cli/kata-env.go b/cli/kata-env.go index 36708c414..133be1616 100644 --- a/cli/kata-env.go +++ b/cli/kata-env.go @@ -18,7 +18,6 @@ import ( "github.com/kata-containers/runtime/virtcontainers/pkg/oci" vcUtils "github.com/kata-containers/runtime/virtcontainers/utils" specs "github.com/opencontainers/runtime-spec/specs-go" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -411,7 +410,7 @@ var kataEnvCLICommand = cli.Command{ return err } - span, _ := opentracing.StartSpanFromContext(ctx, "kata-env") + span, _ := trace(ctx, "kata-env") defer span.Finish() return handleSettings(defaultOutputFile, context) diff --git a/cli/kill.go b/cli/kill.go index 4ffde4e7a..0e79d441d 100644 --- a/cli/kill.go +++ b/cli/kill.go @@ -14,7 +14,6 @@ import ( vc "github.com/kata-containers/runtime/virtcontainers" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -98,15 +97,15 @@ var signals = map[string]syscall.Signal{ } func kill(ctx context.Context, containerID, signal string, all bool) error { - span, _ := opentracing.StartSpanFromContext(ctx, "kill") + span, _ := trace(ctx, "kill") defer span.Finish() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err @@ -122,7 +121,7 @@ func kill(ctx context.Context, containerID, signal string, all bool) error { span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) signum, err := processSignal(signal) if err != nil { @@ -134,7 +133,7 @@ func kill(ctx context.Context, containerID, signal string, all bool) error { return fmt.Errorf("Container %s not ready, running or paused, cannot send a signal", containerID) } - if err := vci.KillContainer(sandboxID, containerID, signum, all); err != nil { + if err := vci.KillContainer(ctx, sandboxID, containerID, signum, all); err != nil { return err } @@ -149,9 +148,9 @@ func kill(ctx context.Context, containerID, signal string, all bool) error { switch containerType { case vc.PodSandbox: - _, err = vci.StopSandbox(sandboxID) + _, err = vci.StopSandbox(ctx, sandboxID) case vc.PodContainer: - _, err = vci.StopContainer(sandboxID, containerID) + _, err = vci.StopContainer(ctx, sandboxID, containerID) default: return fmt.Errorf("Invalid container type found") } diff --git a/cli/kill_test.go b/cli/kill_test.go index a8456e545..470020fa1 100644 --- a/cli/kill_test.go +++ b/cli/kill_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "flag" "fmt" "os" @@ -19,15 +20,15 @@ import ( ) var ( - testKillContainerFuncReturnNil = func(sandboxID, containerID string, signal syscall.Signal, all bool) error { + testKillContainerFuncReturnNil = func(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { return nil } - testStopContainerFuncReturnNil = func(sandboxID, containerID string) (vc.VCContainer, error) { + testStopContainerFuncReturnNil = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &vcmock.Container{}, nil } - testStopSandboxFuncReturnNil = func(sandboxID string) (vc.VCSandbox, error) { + testStopSandboxFuncReturnNil = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &vcmock.Sandbox{}, nil } ) @@ -78,7 +79,7 @@ func testKillCLIFunctionTerminationSignalSuccessful(t *testing.T, sig string) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -97,7 +98,7 @@ func testKillCLIFunctionTerminationSignalSuccessful(t *testing.T, sig string) { vcAnnotations.ContainerTypeKey: string(vc.PodSandbox), } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -131,7 +132,7 @@ func TestKillCLIFunctionNotTerminationSignalSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -164,7 +165,7 @@ func TestKillCLIFunctionNoSignalSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -183,7 +184,7 @@ func TestKillCLIFunctionNoSignalSuccessful(t *testing.T) { vcAnnotations.ContainerTypeKey: string(vc.PodSandbox), } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -207,7 +208,7 @@ func TestKillCLIFunctionEnableAllSuccessful(t *testing.T) { vcAnnotations.ContainerTypeKey: string(vc.PodContainer), } - testingImpl.KillContainerFunc = func(sandboxID, containerID string, signal syscall.Signal, all bool) error { + testingImpl.KillContainerFunc = func(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { if !all { return fmt.Errorf("Expecting -all flag = true, Got false") } @@ -220,7 +221,7 @@ func TestKillCLIFunctionEnableAllSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -240,7 +241,7 @@ func TestKillCLIFunctionEnableAllSuccessful(t *testing.T) { vcAnnotations.ContainerTypeKey: string(vc.PodSandbox), } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, annotations), nil } @@ -270,7 +271,7 @@ func TestKillCLIFunctionContainerNotExistFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{}, nil } @@ -297,7 +298,7 @@ func TestKillCLIFunctionInvalidSignalFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -326,7 +327,7 @@ func TestKillCLIFunctionStatePausedSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{string(vcAnnotations.ContainerTypeKey): string(vc.PodContainer)}), nil } @@ -356,7 +357,7 @@ func TestKillCLIFunctionInvalidStateStoppedFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -382,7 +383,7 @@ func TestKillCLIFunctionKillContainerFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } diff --git a/cli/list.go b/cli/list.go index 00f964a89..46baffa03 100644 --- a/cli/list.go +++ b/cli/list.go @@ -7,6 +7,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -16,7 +17,6 @@ import ( "text/tabwriter" "time" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" vc "github.com/kata-containers/runtime/virtcontainers" @@ -114,10 +114,10 @@ To list containers created using a non-default value for "--root": return err } - span, _ := opentracing.StartSpanFromContext(ctx, "list") + span, ctx := trace(ctx, "list") defer span.Finish() - s, err := getContainers(context) + s, err := getContainers(ctx, context) if err != nil { return err } @@ -301,7 +301,7 @@ func getDirOwner(dir string) (uint32, error) { return statType.Uid, nil } -func getContainers(context *cli.Context) ([]fullContainerState, error) { +func getContainers(ctx context.Context, context *cli.Context) ([]fullContainerState, error) { runtimeConfig, ok := context.App.Metadata["runtimeConfig"].(oci.RuntimeConfig) if !ok { return nil, errors.New("invalid runtime config") @@ -309,7 +309,7 @@ func getContainers(context *cli.Context) ([]fullContainerState, error) { latestHypervisorDetails := getHypervisorDetails(&runtimeConfig.HypervisorConfig) - sandboxList, err := vci.ListSandbox() + sandboxList, err := vci.ListSandbox(ctx) if err != nil { return nil, err } diff --git a/cli/list_test.go b/cli/list_test.go index 9ee3280dc..eee924292 100644 --- a/cli/list_test.go +++ b/cli/list_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "encoding/json" "flag" "fmt" @@ -380,7 +381,7 @@ func TestListGetContainersListSandboxFail(t *testing.T) { "runtimeConfig": runtimeConfig, } - _, err = getContainers(ctx) + _, err = getContainers(context.Background(), ctx) assert.Error(err) assert.True(vcmock.IsMockError(err)) } @@ -388,7 +389,7 @@ func TestListGetContainersListSandboxFail(t *testing.T) { func TestListGetContainers(t *testing.T) { assert := assert.New(t) - testingImpl.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + testingImpl.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { // No pre-existing sandboxes return []vc.SandboxStatus{}, nil } @@ -411,7 +412,7 @@ func TestListGetContainers(t *testing.T) { "runtimeConfig": runtimeConfig, } - state, err := getContainers(ctx) + state, err := getContainers(context.Background(), ctx) assert.NoError(err) assert.Equal(state, []fullContainerState(nil)) } @@ -423,7 +424,7 @@ func TestListGetContainersSandboxWithoutContainers(t *testing.T) { MockID: testSandboxID, } - testingImpl.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + testingImpl.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { return []vc.SandboxStatus{ { ID: sandbox.ID(), @@ -450,7 +451,7 @@ func TestListGetContainersSandboxWithoutContainers(t *testing.T) { "runtimeConfig": runtimeConfig, } - state, err := getContainers(ctx) + state, err := getContainers(context.Background(), ctx) assert.NoError(err) assert.Equal(state, []fullContainerState(nil)) } @@ -470,7 +471,7 @@ func TestListGetContainersSandboxWithContainer(t *testing.T) { err = os.MkdirAll(rootfs, testDirMode) assert.NoError(err) - testingImpl.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + testingImpl.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { return []vc.SandboxStatus{ { ID: sandbox.ID(), @@ -497,7 +498,7 @@ func TestListGetContainersSandboxWithContainer(t *testing.T) { ctx.App.Metadata["runtimeConfig"] = runtimeConfig - _, err = getContainers(ctx) + _, err = getContainers(context.Background(), ctx) assert.NoError(err) } @@ -538,7 +539,7 @@ func TestListCLIFunctionFormatFail(t *testing.T) { rootfs := filepath.Join(tmpdir, "rootfs") - testingImpl.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + testingImpl.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { return []vc.SandboxStatus{ { ID: sandbox.ID(), @@ -638,7 +639,7 @@ func TestListCLIFunctionQuiet(t *testing.T) { err = os.MkdirAll(rootfs, testDirMode) assert.NoError(err) - testingImpl.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + testingImpl.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { return []vc.SandboxStatus{ { ID: sandbox.ID(), diff --git a/cli/main.go b/cli/main.go index f3d6ba580..546062b95 100644 --- a/cli/main.go +++ b/cli/main.go @@ -208,23 +208,35 @@ func setupSignalHandler(ctx context.Context) { // setExternalLoggers registers the specified logger with the external // packages which accept a logger to handle their own logging. -func setExternalLoggers(logger *logrus.Entry) { +func setExternalLoggers(ctx context.Context, logger *logrus.Entry) { + var span opentracing.Span + + // Only create a new span if a root span already exists. This is + // required to ensure that this function will not disrupt the root + // span logic by creating a span before the proper root span has been + // created. + + if opentracing.SpanFromContext(ctx) != nil { + span, ctx = trace(ctx, "setExternalLoggers") + defer span.Finish() + } + // Set virtcontainers logger. - vci.SetLogger(logger) + vci.SetLogger(ctx, logger) // Set vm factory logger. - vf.SetLogger(logger) + vf.SetLogger(ctx, logger) // Set the OCI package logger. - oci.SetLogger(logger) + oci.SetLogger(ctx, logger) } // beforeSubcommands is the function to perform preliminary checks // before command-line parsing occurs. -func beforeSubcommands(context *cli.Context) error { - handleShowConfig(context) +func beforeSubcommands(c *cli.Context) error { + handleShowConfig(c) - if userWantsUsage(context) || (context.NArg() == 1 && (context.Args()[0] == checkCmd)) { + if userWantsUsage(c) || (c.NArg() == 1 && (c.Args()[0] == checkCmd)) { // No setup required if the user just // wants to see the usage statement or are // running a command that does not manipulate @@ -232,7 +244,7 @@ func beforeSubcommands(context *cli.Context) error { return nil } - if path := context.GlobalString("log"); path != "" { + if path := c.GlobalString("log"); path != "" { f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND|os.O_SYNC, 0640) if err != nil { return err @@ -240,21 +252,21 @@ func beforeSubcommands(context *cli.Context) error { kataLog.Logger.Out = f } - switch context.GlobalString("log-format") { + switch c.GlobalString("log-format") { case "text": // retain logrus's default. case "json": kataLog.Logger.Formatter = new(logrus.JSONFormatter) default: - return fmt.Errorf("unknown log-format %q", context.GlobalString("log-format")) + return fmt.Errorf("unknown log-format %q", c.GlobalString("log-format")) } var traceRootSpan string // Add the name of the sub-command to each log entry for easier // debugging. - cmdName := context.Args().First() - if context.App.Command(cmdName) != nil { + cmdName := c.Args().First() + if c.App.Command(cmdName) != nil { kataLog = kataLog.WithField("command", cmdName) // Name for the root span (used for tracing) now the @@ -262,16 +274,19 @@ func beforeSubcommands(context *cli.Context) error { traceRootSpan = name + " " + cmdName } - setExternalLoggers(kataLog) + // Since a context is required, pass a new (throw-away) one - we + // cannot use the main context as tracing hasn't been enabled yet + // (meaning any spans created at this point will be silently ignored). + setExternalLoggers(context.Background(), kataLog) ignoreLogging := false - if context.NArg() == 1 && context.Args()[0] == envCmd { + if c.NArg() == 1 && c.Args()[0] == envCmd { // simply report the logging setup ignoreLogging = true } - configFile, runtimeConfig, err := loadConfiguration(context.GlobalString(configFilePathOption), ignoreLogging) + configFile, runtimeConfig, err := loadConfiguration(c.GlobalString(configFilePathOption), ignoreLogging) if err != nil { fatal(err) } @@ -283,13 +298,13 @@ func beforeSubcommands(context *cli.Context) error { // This delays collection of trace data slightly but benefits the user by // ensuring the first span is the name of the sub-command being // invoked from the command-line. - err = setupTracing(context, traceRootSpan) + err = setupTracing(c, traceRootSpan) if err != nil { return err } } - args := strings.Join(context.Args(), " ") + args := strings.Join(c.Args(), " ") fields := logrus.Fields{ "version": version, @@ -300,8 +315,8 @@ func beforeSubcommands(context *cli.Context) error { kataLog.WithFields(fields).Info() // make the data accessible to the sub-commands. - context.App.Metadata["runtimeConfig"] = runtimeConfig - context.App.Metadata["configFile"] = configFile + c.App.Metadata["runtimeConfig"] = runtimeConfig + c.App.Metadata["configFile"] = configFile return nil } @@ -340,6 +355,8 @@ func setupTracing(context *cli.Context, rootSpanName string) error { return err } + span.SetTag("subsystem", "runtime") + // Associate the root span with the context ctx = opentracing.ContextWithSpan(ctx, span) diff --git a/cli/network.go b/cli/network.go index a90ab10fe..34f017407 100644 --- a/cli/network.go +++ b/cli/network.go @@ -6,6 +6,7 @@ package main import ( + "context" "encoding/json" "fmt" "os" @@ -46,7 +47,12 @@ var addIfaceCommand = cli.Command{ ArgsUsage: `add-iface file or - for stdin`, Flags: []cli.Flag{}, Action: func(context *cli.Context) error { - return networkModifyCommand(context.Args().First(), context.Args().Get(1), interfaceType, true) + ctx, err := cliContextToContext(context) + if err != nil { + return err + } + + return networkModifyCommand(ctx, context.Args().First(), context.Args().Get(1), interfaceType, true) }, } @@ -56,7 +62,12 @@ var delIfaceCommand = cli.Command{ ArgsUsage: `del-iface file or - for stdin`, Flags: []cli.Flag{}, Action: func(context *cli.Context) error { - return networkModifyCommand(context.Args().First(), context.Args().Get(1), interfaceType, false) + ctx, err := cliContextToContext(context) + if err != nil { + return err + } + + return networkModifyCommand(ctx, context.Args().First(), context.Args().Get(1), interfaceType, false) }, } @@ -66,7 +77,12 @@ var listIfacesCommand = cli.Command{ ArgsUsage: `list-ifaces `, Flags: []cli.Flag{}, Action: func(context *cli.Context) error { - return networkListCommand(context.Args().First(), interfaceType) + ctx, err := cliContextToContext(context) + if err != nil { + return err + } + + return networkListCommand(ctx, context.Args().First(), interfaceType) }, } @@ -76,7 +92,12 @@ var updateRoutesCommand = cli.Command{ ArgsUsage: `update-routes file or - for stdin`, Flags: []cli.Flag{}, Action: func(context *cli.Context) error { - return networkModifyCommand(context.Args().First(), context.Args().Get(1), routeType, true) + ctx, err := cliContextToContext(context) + if err != nil { + return err + } + + return networkModifyCommand(ctx, context.Args().First(), context.Args().Get(1), routeType, true) }, } @@ -86,12 +107,17 @@ var listRoutesCommand = cli.Command{ ArgsUsage: `list-routes `, Flags: []cli.Flag{}, Action: func(context *cli.Context) error { - return networkListCommand(context.Args().First(), routeType) + ctx, err := cliContextToContext(context) + if err != nil { + return err + } + + return networkListCommand(ctx, context.Args().First(), routeType) }, } -func networkModifyCommand(containerID, input string, opType networkType, add bool) (err error) { - status, sandboxID, err := getExistingContainerInfo(containerID) +func networkModifyCommand(ctx context.Context, containerID, input string, opType networkType, add bool) (err error) { + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -103,7 +129,7 @@ func networkModifyCommand(containerID, input string, opType networkType, add boo "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) // container MUST be running if status.State.State != vc.StateRunning { @@ -131,13 +157,13 @@ func networkModifyCommand(containerID, input string, opType networkType, add boo return err } if add { - resultingInf, err = vci.AddInterface(sandboxID, inf) + resultingInf, err = vci.AddInterface(ctx, sandboxID, inf) if err != nil { kataLog.WithField("resulting-interface", fmt.Sprintf("%+v", resultingInf)). WithError(err).Error("add interface failed") } } else { - resultingInf, err = vci.RemoveInterface(sandboxID, inf) + resultingInf, err = vci.RemoveInterface(ctx, sandboxID, inf) if err != nil { kataLog.WithField("resulting-interface", fmt.Sprintf("%+v", resultingInf)). WithError(err).Error("delete interface failed") @@ -149,7 +175,7 @@ func networkModifyCommand(containerID, input string, opType networkType, add boo if err = json.NewDecoder(f).Decode(&routes); err != nil { return err } - resultingRoutes, err = vci.UpdateRoutes(sandboxID, routes) + resultingRoutes, err = vci.UpdateRoutes(ctx, sandboxID, routes) json.NewEncoder(output).Encode(resultingRoutes) if err != nil { kataLog.WithField("resulting-routes", fmt.Sprintf("%+v", resultingRoutes)). @@ -159,8 +185,8 @@ func networkModifyCommand(containerID, input string, opType networkType, add boo return err } -func networkListCommand(containerID string, opType networkType) (err error) { - status, sandboxID, err := getExistingContainerInfo(containerID) +func networkListCommand(ctx context.Context, containerID string, opType networkType) (err error) { + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -172,7 +198,7 @@ func networkListCommand(containerID string, opType networkType) (err error) { "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) // container MUST be running if status.State.State != vc.StateRunning { @@ -184,7 +210,7 @@ func networkListCommand(containerID string, opType networkType) (err error) { switch opType { case interfaceType: var interfaces []*grpc.Interface - interfaces, err = vci.ListInterfaces(sandboxID) + interfaces, err = vci.ListInterfaces(ctx, sandboxID) if err != nil { kataLog.WithField("existing-interfaces", fmt.Sprintf("%+v", interfaces)). WithError(err).Error("list interfaces failed") @@ -192,7 +218,7 @@ func networkListCommand(containerID string, opType networkType) (err error) { json.NewEncoder(file).Encode(interfaces) case routeType: var routes []*grpc.Route - routes, err = vci.ListRoutes(sandboxID) + routes, err = vci.ListRoutes(ctx, sandboxID) if err != nil { kataLog.WithField("resulting-routes", fmt.Sprintf("%+v", routes)). WithError(err).Error("update routes failed") diff --git a/cli/network_test.go b/cli/network_test.go index 37a63ea04..6079183c3 100644 --- a/cli/network_test.go +++ b/cli/network_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "flag" "io/ioutil" "os" @@ -17,19 +18,19 @@ import ( ) var ( - testAddInterfaceFuncReturnNil = func(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + testAddInterfaceFuncReturnNil = func(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { return nil, nil } - testRemoveInterfaceFuncReturnNil = func(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + testRemoveInterfaceFuncReturnNil = func(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { return nil, nil } - testListInterfacesFuncReturnNil = func(sandboxID string) ([]*grpc.Interface, error) { + testListInterfacesFuncReturnNil = func(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) { return nil, nil } - testUpdateRoutsFuncReturnNil = func(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { + testUpdateRoutsFuncReturnNil = func(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { return nil, nil } - testListRoutesFuncReturnNil = func(sandboxID string) ([]*grpc.Route, error) { + testListRoutesFuncReturnNil = func(ctx context.Context, sandboxID string) ([]*grpc.Route, error) { return nil, nil } ) @@ -51,7 +52,7 @@ func TestNetworkCliFunction(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } diff --git a/cli/oci.go b/cli/oci.go index 7a872aba2..cab765fbf 100644 --- a/cli/oci.go +++ b/cli/oci.go @@ -21,7 +21,6 @@ import ( "github.com/kata-containers/runtime/virtcontainers/pkg/oci" "github.com/opencontainers/runc/libcontainer/utils" specs "github.com/opencontainers/runtime-spec/specs-go" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" ) @@ -47,7 +46,7 @@ var procMountInfo = "/proc/self/mountinfo" var ctrsMapTreePath = "/var/run/kata-containers/containers-mapping" // getContainerInfo returns the container status and its sandbox ID. -func getContainerInfo(containerID string) (vc.ContainerStatus, string, error) { +func getContainerInfo(ctx context.Context, containerID string) (vc.ContainerStatus, string, error) { // container ID MUST be provided. if containerID == "" { return vc.ContainerStatus{}, "", fmt.Errorf("Missing container ID") @@ -64,7 +63,7 @@ func getContainerInfo(containerID string) (vc.ContainerStatus, string, error) { return vc.ContainerStatus{}, "", nil } - ctrStatus, err := vci.StatusContainer(sandboxID, containerID) + ctrStatus, err := vci.StatusContainer(ctx, sandboxID, containerID) if err != nil { return vc.ContainerStatus{}, "", err } @@ -72,8 +71,8 @@ func getContainerInfo(containerID string) (vc.ContainerStatus, string, error) { return ctrStatus, sandboxID, nil } -func getExistingContainerInfo(containerID string) (vc.ContainerStatus, string, error) { - cStatus, sandboxID, err := getContainerInfo(containerID) +func getExistingContainerInfo(ctx context.Context, containerID string) (vc.ContainerStatus, string, error) { + cStatus, sandboxID, err := getContainerInfo(ctx, containerID) if err != nil { return vc.ContainerStatus{}, "", err } @@ -86,14 +85,14 @@ func getExistingContainerInfo(containerID string) (vc.ContainerStatus, string, e return cStatus, sandboxID, nil } -func validCreateParams(containerID, bundlePath string) (string, error) { +func validCreateParams(ctx context.Context, containerID, bundlePath string) (string, error) { // container ID MUST be provided. if containerID == "" { return "", fmt.Errorf("Missing container ID") } // container ID MUST be unique. - cStatus, _, err := getContainerInfo(containerID) + cStatus, _, err := getContainerInfo(ctx, containerID) if err != nil { return "", err } @@ -128,7 +127,7 @@ func validCreateParams(containerID, bundlePath string) (string, error) { // OCI runtime specification. It returns a list of complete paths // that should be created and used for every specified resource. func processCgroupsPath(ctx context.Context, ociSpec oci.CompatOCISpec, isSandbox bool) ([]string, error) { - span, _ := opentracing.StartSpanFromContext(ctx, "processCgroupsPath") + span, _ := trace(ctx, "processCgroupsPath") defer span.Finish() var cgroupsPathList []string @@ -377,7 +376,7 @@ func fetchContainerIDMapping(containerID string) (string, error) { } func addContainerIDMapping(ctx context.Context, containerID, sandboxID string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "addContainerIDMapping") + span, _ := trace(ctx, "addContainerIDMapping") defer span.Finish() if containerID == "" { @@ -404,7 +403,7 @@ func addContainerIDMapping(ctx context.Context, containerID, sandboxID string) e } func delContainerIDMapping(ctx context.Context, containerID string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "delContainerIDMapping") + span, _ := trace(ctx, "delContainerIDMapping") defer span.Finish() if containerID == "" { diff --git a/cli/oci_test.go b/cli/oci_test.go index 4dd6d5dec..7ab3c4940 100644 --- a/cli/oci_test.go +++ b/cli/oci_test.go @@ -66,7 +66,7 @@ var cgroupTestData = []cgroupTestDataType{ func TestGetContainerInfoContainerIDEmptyFailure(t *testing.T) { assert := assert.New(t) - status, _, err := getContainerInfo("") + status, _, err := getContainerInfo(context.Background(), "") assert.Error(err, "This test should fail because containerID is empty") assert.Empty(status.ID, "Expected blank fullID, but got %v", status.ID) @@ -92,7 +92,7 @@ func TestGetContainerInfo(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return containerStatus, nil } @@ -100,7 +100,7 @@ func TestGetContainerInfo(t *testing.T) { testingImpl.StatusContainerFunc = nil }() - status, sandboxID, err := getContainerInfo(testContainerID) + status, sandboxID, err := getContainerInfo(context.Background(), testContainerID) assert.NoError(err) assert.Equal(sandboxID, sandbox.ID()) assert.Equal(status, containerStatus) @@ -108,7 +108,7 @@ func TestGetContainerInfo(t *testing.T) { func TestValidCreateParamsContainerIDEmptyFailure(t *testing.T) { assert := assert.New(t) - _, err := validCreateParams("", "") + _, err := validCreateParams(context.Background(), "", "") assert.Error(err, "This test should fail because containerID is empty") assert.False(vcmock.IsMockError(err)) @@ -116,7 +116,7 @@ func TestValidCreateParamsContainerIDEmptyFailure(t *testing.T) { func TestGetExistingContainerInfoContainerIDEmptyFailure(t *testing.T) { assert := assert.New(t) - status, _, err := getExistingContainerInfo("") + status, _, err := getExistingContainerInfo(context.Background(), "") assert.Error(err, "This test should fail because containerID is empty") assert.Empty(status.ID, "Expected blank fullID, but got %v", status.ID) @@ -133,7 +133,7 @@ func TestValidCreateParamsContainerIDNotUnique(t *testing.T) { err = os.MkdirAll(filepath.Join(ctrsMapTreePath, testContainerID, testSandboxID2), 0750) assert.NoError(err) - _, err = validCreateParams(testContainerID, "") + _, err = validCreateParams(context.Background(), testContainerID, "") assert.Error(err) assert.False(vcmock.IsMockError(err)) @@ -153,7 +153,7 @@ func TestValidCreateParamsInvalidBundle(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - _, err = validCreateParams(testContainerID, bundlePath) + _, err = validCreateParams(context.Background(), testContainerID, bundlePath) // bundle is ENOENT assert.Error(err) assert.False(vcmock.IsMockError(err)) @@ -175,7 +175,7 @@ func TestValidCreateParamsBundleIsAFile(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - _, err = validCreateParams(testContainerID, bundlePath) + _, err = validCreateParams(context.Background(), testContainerID, bundlePath) // bundle exists as a file, not a directory assert.Error(err) assert.False(vcmock.IsMockError(err)) diff --git a/cli/pause.go b/cli/pause.go index 307ae785d..2772dd9c6 100644 --- a/cli/pause.go +++ b/cli/pause.go @@ -9,7 +9,6 @@ package main import ( "context" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -58,16 +57,16 @@ func toggle(c *cli.Context, pause bool) error { } func toggleContainerPause(ctx context.Context, containerID string, pause bool) (err error) { - span, _ := opentracing.StartSpanFromContext(ctx, "pause") + span, _ := trace(ctx, "pause") defer span.Finish() span.SetTag("pause", pause) kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -79,14 +78,14 @@ func toggleContainerPause(ctx context.Context, containerID string, pause bool) ( "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) if pause { - err = vci.PauseContainer(sandboxID, containerID) + err = vci.PauseContainer(ctx, sandboxID, containerID) } else { - err = vci.ResumeContainer(sandboxID, containerID) + err = vci.ResumeContainer(ctx, sandboxID, containerID) } return err diff --git a/cli/pause_test.go b/cli/pause_test.go index 980393699..1ad38537f 100644 --- a/cli/pause_test.go +++ b/cli/pause_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "flag" "io/ioutil" "os" @@ -16,11 +17,11 @@ import ( ) var ( - testPauseContainerFuncReturnNil = func(sandboxID, containerID string) error { + testPauseContainerFuncReturnNil = func(ctx context.Context, sandboxID, containerID string) error { return nil } - testResumeContainerFuncReturnNil = func(sandboxID, containerID string) error { + testResumeContainerFuncReturnNil = func(ctx context.Context, sandboxID, containerID string) error { return nil } ) @@ -38,7 +39,7 @@ func TestPauseCLIFunctionSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -84,7 +85,7 @@ func TestPauseCLIFunctionPauseContainerFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -111,7 +112,7 @@ func TestResumeCLIFunctionSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } @@ -156,7 +157,7 @@ func TestResumeCLIFunctionPauseContainerFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return newSingleContainerStatus(testContainerID, state, map[string]string{}), nil } diff --git a/cli/ps.go b/cli/ps.go index 6780bccde..fff957ccd 100644 --- a/cli/ps.go +++ b/cli/ps.go @@ -11,7 +11,6 @@ import ( "fmt" vc "github.com/kata-containers/runtime/virtcontainers" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -51,7 +50,7 @@ var psCLICommand = cli.Command{ } func ps(ctx context.Context, containerID, format string, args []string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "ps") + span, _ := trace(ctx, "ps") defer span.Finish() if containerID == "" { @@ -59,11 +58,11 @@ func ps(ctx context.Context, containerID, format string, args []string) error { } kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -75,7 +74,7 @@ func ps(ctx context.Context, containerID, format string, args []string) error { "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) @@ -93,7 +92,7 @@ func ps(ctx context.Context, containerID, format string, args []string) error { options.Format = format - msg, err := vci.ProcessListContainer(containerID, sandboxID, options) + msg, err := vci.ProcessListContainer(ctx, containerID, sandboxID, options) if err != nil { return err } diff --git a/cli/ps_test.go b/cli/ps_test.go index b035bf2d8..66e6e7ffa 100644 --- a/cli/ps_test.go +++ b/cli/ps_test.go @@ -53,7 +53,7 @@ func TestPSFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -93,7 +93,7 @@ func TestPSSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ State: vc.State{ State: vc.StateRunning, @@ -105,7 +105,7 @@ func TestPSSuccessful(t *testing.T) { }, nil } - testingImpl.ProcessListContainerFunc = func(sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { + testingImpl.ProcessListContainerFunc = func(ctx context.Context, sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { return []byte("echo,sleep,grep"), nil } diff --git a/cli/run.go b/cli/run.go index 9da73bc90..ac0198d0f 100644 --- a/cli/run.go +++ b/cli/run.go @@ -14,7 +14,6 @@ import ( "syscall" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -82,7 +81,7 @@ var runCLICommand = cli.Command{ func run(ctx context.Context, containerID, bundle, console, consoleSocket, pidFile string, detach bool, runtimeConfig oci.RuntimeConfig) error { - span, ctx := opentracing.StartSpanFromContext(ctx, "run") + span, ctx := trace(ctx, "run") defer span.Finish() consolePath, err := setupConsole(console, consoleSocket) diff --git a/cli/run_test.go b/cli/run_test.go index f43511915..04532f169 100644 --- a/cli/run_test.go +++ b/cli/run_test.go @@ -67,11 +67,11 @@ func TestRunInvalidArgs(t *testing.T) { } // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -230,12 +230,12 @@ func TestRunContainerSuccessful(t *testing.T) { flagCreate := false // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { flagCreate = true return d.sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } @@ -244,7 +244,7 @@ func TestRunContainerSuccessful(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return an empty list on create if !flagCreate { return vc.ContainerStatus{}, nil @@ -260,7 +260,7 @@ func TestRunContainerSuccessful(t *testing.T) { }, nil } - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // now we can kill the fake container workload err := d.process.Kill() assert.NoError(err) @@ -268,11 +268,11 @@ func TestRunContainerSuccessful(t *testing.T) { return d.sandbox.MockContainers[0], nil } - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return d.sandbox.MockContainers[0], nil } @@ -304,12 +304,12 @@ func TestRunContainerDetachSuccessful(t *testing.T) { flagCreate := false // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { flagCreate = true return d.sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } @@ -318,7 +318,7 @@ func TestRunContainerDetachSuccessful(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return an empty list on create if !flagCreate { return vc.ContainerStatus{}, nil @@ -334,7 +334,7 @@ func TestRunContainerDetachSuccessful(t *testing.T) { }, nil } - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // now we can kill the fake container workload err := d.process.Kill() assert.NoError(err) @@ -342,11 +342,11 @@ func TestRunContainerDetachSuccessful(t *testing.T) { return d.sandbox.MockContainers[0], nil } - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return d.sandbox.MockContainers[0], nil } @@ -375,12 +375,12 @@ func TestRunContainerDeleteFail(t *testing.T) { flagCreate := false // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { flagCreate = true return d.sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } @@ -389,7 +389,7 @@ func TestRunContainerDeleteFail(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return an empty list on create if !flagCreate { return vc.ContainerStatus{}, nil @@ -405,7 +405,7 @@ func TestRunContainerDeleteFail(t *testing.T) { }, nil } - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // now we can kill the fake container workload err := d.process.Kill() assert.NoError(err) @@ -413,12 +413,12 @@ func TestRunContainerDeleteFail(t *testing.T) { return d.sandbox.MockContainers[0], nil } - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { // return an error to provoke a failure in delete return nil, fmt.Errorf("DeleteSandboxFunc") } - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // return an error to provoke a failure in delete return d.sandbox.MockContainers[0], fmt.Errorf("DeleteContainerFunc") } @@ -449,12 +449,12 @@ func TestRunContainerWaitFail(t *testing.T) { flagCreate := false // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { flagCreate = true return d.sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return d.sandbox, nil } @@ -463,7 +463,7 @@ func TestRunContainerWaitFail(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return an empty list on create if !flagCreate { return vc.ContainerStatus{}, nil @@ -479,7 +479,7 @@ func TestRunContainerWaitFail(t *testing.T) { }, nil } - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // now we can kill the fake container workload err := d.process.Kill() assert.NoError(err) @@ -490,12 +490,12 @@ func TestRunContainerWaitFail(t *testing.T) { return d.sandbox.MockContainers[0], nil } - testingImpl.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { // return an error to provoke a failure in delete return nil, fmt.Errorf("DeleteSandboxFunc") } - testingImpl.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { // return an error to provoke a failure in delete return d.sandbox.MockContainers[0], fmt.Errorf("DeleteContainerFunc") } @@ -530,12 +530,12 @@ func TestRunContainerStartFail(t *testing.T) { flagCreate := false // fake functions used to run containers - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { flagCreate = true return d.sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { // start fails return nil, fmt.Errorf("StartSandbox") } @@ -545,7 +545,7 @@ func TestRunContainerStartFail(t *testing.T) { defer os.RemoveAll(path) ctrsMapTreePath = path - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return an empty list on create if !flagCreate { return vc.ContainerStatus{}, nil @@ -595,7 +595,7 @@ func TestRunContainerStartFailExistingContainer(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { // return the container status return vc.ContainerStatus{ ID: testContainerID, @@ -605,11 +605,11 @@ func TestRunContainerStartFailExistingContainer(t *testing.T) { }, nil } - testingImpl.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + testingImpl.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return sandbox, nil } - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { // force no containers sandbox.MockContainers = nil diff --git a/cli/spec.go b/cli/spec.go index 21ec5c002..a85da8e8d 100644 --- a/cli/spec.go +++ b/cli/spec.go @@ -13,7 +13,6 @@ import ( "os" "github.com/opencontainers/runc/libcontainer/specconv" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -78,7 +77,7 @@ generate a proper rootless spec file.`, return err } - span, _ := opentracing.StartSpanFromContext(ctx, "spec") + span, _ := trace(ctx, "spec") defer span.Finish() spec := specconv.Example() diff --git a/cli/start.go b/cli/start.go index c9641513b..b39ebbb2b 100644 --- a/cli/start.go +++ b/cli/start.go @@ -12,7 +12,6 @@ import ( vc "github.com/kata-containers/runtime/virtcontainers" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -48,15 +47,15 @@ var startCLICommand = cli.Command{ } func start(ctx context.Context, containerID string) (vc.VCSandbox, error) { - span, _ := opentracing.StartSpanFromContext(ctx, "start") + span, _ := trace(ctx, "start") defer span.Finish() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) // Checks the MUST and MUST NOT from OCI runtime specification - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return nil, err } @@ -68,7 +67,7 @@ func start(ctx context.Context, containerID string) (vc.VCSandbox, error) { "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) @@ -78,10 +77,10 @@ func start(ctx context.Context, containerID string) (vc.VCSandbox, error) { } if containerType.IsSandbox() { - return vci.StartSandbox(sandboxID) + return vci.StartSandbox(ctx, sandboxID) } - c, err := vci.StartContainer(sandboxID, containerID) + c, err := vci.StartContainer(ctx, sandboxID, containerID) if err != nil { return nil, err } diff --git a/cli/start_test.go b/cli/start_test.go index bb7ff6529..f3fb87a59 100644 --- a/cli/start_test.go +++ b/cli/start_test.go @@ -58,7 +58,7 @@ func TestStartSandbox(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -75,7 +75,7 @@ func TestStartSandbox(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + testingImpl.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return sandbox, nil } @@ -98,7 +98,7 @@ func TestStartMissingAnnotation(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{}, @@ -132,7 +132,7 @@ func TestStartContainerSucessFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: testContainerID, Annotations: map[string]string{ @@ -149,7 +149,7 @@ func TestStartContainerSucessFailure(t *testing.T) { assert.Error(err) assert.True(vcmock.IsMockError(err)) - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return sandbox.MockContainers[0], nil } @@ -206,7 +206,7 @@ func TestStartCLIFunctionSuccess(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: testContainerID, Annotations: map[string]string{ @@ -215,7 +215,7 @@ func TestStartCLIFunctionSuccess(t *testing.T) { }, nil } - testingImpl.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + testingImpl.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return sandbox.MockContainers[0], nil } diff --git a/cli/state.go b/cli/state.go index cfc9e5228..33c7c01bf 100644 --- a/cli/state.go +++ b/cli/state.go @@ -13,7 +13,6 @@ import ( "os" "github.com/kata-containers/runtime/virtcontainers/pkg/oci" - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -41,16 +40,16 @@ instance of a container.`, } func state(ctx context.Context, containerID string) error { - span, _ := opentracing.StartSpanFromContext(ctx, "state") + span, _ := trace(ctx, "state") defer span.Finish() kataLog = kataLog.WithField("container", containerID) span.SetTag("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) // Checks the MUST and MUST NOT from OCI runtime specification - status, _, err := getExistingContainerInfo(containerID) + status, _, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } diff --git a/cli/state_test.go b/cli/state_test.go index 688025cbd..db0493103 100644 --- a/cli/state_test.go +++ b/cli/state_test.go @@ -67,7 +67,7 @@ func TestStateSuccessful(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: testContainerID, Annotations: map[string]string{ diff --git a/cli/tracing.go b/cli/tracing.go index 4282143b7..92cbbc605 100644 --- a/cli/tracing.go +++ b/cli/tracing.go @@ -76,3 +76,14 @@ func stopTracing(ctx context.Context) { // report all possible spans to the collector tracerCloser.Close() } + +// trace creates a new tracing span based on the specified name and parent +// context. +func trace(parent context.Context, name string) (opentracing.Span, context.Context) { + span, ctx := opentracing.StartSpanFromContext(parent, name) + + span.SetTag("source", "runtime") + span.SetTag("component", "cli") + + return span, ctx +} diff --git a/cli/update.go b/cli/update.go index cc9eac5c0..4b21ffbfc 100644 --- a/cli/update.go +++ b/cli/update.go @@ -15,7 +15,6 @@ import ( "github.com/docker/go-units" vc "github.com/kata-containers/runtime/virtcontainers" "github.com/opencontainers/runtime-spec/specs-go" - opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -133,7 +132,7 @@ other options are ignored. return err } - span, _ := opentracing.StartSpanFromContext(ctx, "update") + span, _ := trace(ctx, "update") defer span.Finish() if context.Args().Present() == false { @@ -143,10 +142,10 @@ other options are ignored. containerID := context.Args().First() kataLog = kataLog.WithField("container", containerID) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) - status, sandboxID, err := getExistingContainerInfo(containerID) + status, sandboxID, err := getExistingContainerInfo(ctx, containerID) if err != nil { return err } @@ -158,7 +157,7 @@ other options are ignored. "sandbox": sandboxID, }) - setExternalLoggers(kataLog) + setExternalLoggers(ctx, kataLog) span.SetTag("container", containerID) span.SetTag("sandbox", sandboxID) @@ -282,6 +281,6 @@ other options are ignored. r.Pids.Limit = int64(context.Int("pids-limit")) } - return vci.UpdateContainer(sandboxID, containerID, r) + return vci.UpdateContainer(ctx, sandboxID, containerID, r) }, } diff --git a/cli/update_test.go b/cli/update_test.go index 3b8916c22..b08cc769c 100644 --- a/cli/update_test.go +++ b/cli/update_test.go @@ -6,6 +6,7 @@ package main import ( + "context" "flag" "io/ioutil" "os" @@ -71,7 +72,7 @@ func TestUpdateCLIFailure(t *testing.T) { assert.NoError(err) defer os.RemoveAll(path) - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -87,7 +88,7 @@ func TestUpdateCLIFailure(t *testing.T) { assert.Error(err) // resources file does not exist - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -98,7 +99,7 @@ func TestUpdateCLIFailure(t *testing.T) { }, }, nil } - testingImpl.UpdateContainerFunc = func(sandboxID, containerID string, resources specs.LinuxResources) error { + testingImpl.UpdateContainerFunc = func(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error { return nil } defer func() { @@ -160,7 +161,7 @@ func TestUpdateCLISuccessful(t *testing.T) { }, } - testingImpl.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + testingImpl.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{ ID: sandbox.ID(), Annotations: map[string]string{ @@ -171,7 +172,7 @@ func TestUpdateCLISuccessful(t *testing.T) { }, }, nil } - testingImpl.UpdateContainerFunc = func(sandboxID, containerID string, resources specs.LinuxResources) error { + testingImpl.UpdateContainerFunc = func(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error { return nil } defer func() { diff --git a/cli/version.go b/cli/version.go index 10b6676fb..c4d1f695f 100644 --- a/cli/version.go +++ b/cli/version.go @@ -6,7 +6,6 @@ package main import ( - opentracing "github.com/opentracing/opentracing-go" "github.com/urfave/cli" ) @@ -19,7 +18,7 @@ var versionCLICommand = cli.Command{ return err } - span, _ := opentracing.StartSpanFromContext(ctx, "version") + span, _ := trace(ctx, "version") defer span.Finish() cli.VersionPrinter(context) diff --git a/virtcontainers/agent.go b/virtcontainers/agent.go index bf8706d30..9445b2fe1 100644 --- a/virtcontainers/agent.go +++ b/virtcontainers/agent.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "syscall" @@ -129,7 +130,7 @@ type agent interface { // init(). // After init() is called, agent implementations should be initialized and ready // to handle all other Agent interface methods. - init(sandbox *Sandbox, config interface{}) error + init(ctx context.Context, sandbox *Sandbox, config interface{}) error // capabilities should return a structure that specifies the capabilities // supported by the agent. diff --git a/virtcontainers/api.go b/virtcontainers/api.go index 95c6ff042..82ebfe15d 100644 --- a/virtcontainers/api.go +++ b/virtcontainers/api.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "os" "runtime" "syscall" @@ -14,6 +15,7 @@ import ( deviceApi "github.com/kata-containers/runtime/virtcontainers/device/api" deviceConfig "github.com/kata-containers/runtime/virtcontainers/device/config" specs "github.com/opencontainers/runtime-spec/specs-go" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" ) @@ -23,8 +25,31 @@ func init() { var virtLog = logrus.WithField("source", "virtcontainers") +// trace creates a new tracing span based on the specified name and parent +// context. +func trace(parent context.Context, name string) (opentracing.Span, context.Context) { + span, ctx := opentracing.StartSpanFromContext(parent, name) + + // Should not need to be changed (again). + span.SetTag("source", "virtcontainers") + span.SetTag("component", "virtcontainers") + + // Should be reset as new subsystems are entered. + span.SetTag("subsystem", "api") + + return span, ctx +} + +func traceWithSubsys(ctx context.Context, subsys, name string) (opentracing.Span, context.Context) { + span, ctx := opentracing.StartSpanFromContext(ctx, name) + + span.SetTag("subsystem", subsys) + + return span, ctx +} + // SetLogger sets the logger for virtcontainers package. -func SetLogger(logger *logrus.Entry) { +func SetLogger(ctx context.Context, logger *logrus.Entry) { fields := virtLog.Data virtLog = logger.WithFields(fields) @@ -33,8 +58,11 @@ func SetLogger(logger *logrus.Entry) { // CreateSandbox is the virtcontainers sandbox creation entry point. // CreateSandbox creates a sandbox and its containers. It does not start them. -func CreateSandbox(sandboxConfig SandboxConfig, factory Factory) (VCSandbox, error) { - s, err := createSandboxFromConfig(sandboxConfig, factory) +func CreateSandbox(ctx context.Context, sandboxConfig SandboxConfig, factory Factory) (VCSandbox, error) { + span, ctx := trace(ctx, "CreateSandbox") + defer span.Finish() + + s, err := createSandboxFromConfig(ctx, sandboxConfig, factory) if err == nil { s.releaseStatelessSandbox() } @@ -42,11 +70,14 @@ func CreateSandbox(sandboxConfig SandboxConfig, factory Factory) (VCSandbox, err return s, err } -func createSandboxFromConfig(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { +func createSandboxFromConfig(ctx context.Context, sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { + span, ctx := trace(ctx, "createSandboxFromConfig") + defer span.Finish() + var err error // Create the sandbox. - s, err := createSandbox(sandboxConfig, factory) + s, err := createSandbox(ctx, sandboxConfig, factory) if err != nil { return nil, err } @@ -104,7 +135,10 @@ func createSandboxFromConfig(sandboxConfig SandboxConfig, factory Factory) (*San // DeleteSandbox is the virtcontainers sandbox deletion entry point. // DeleteSandbox will stop an already running container and then delete it. -func DeleteSandbox(sandboxID string) (VCSandbox, error) { +func DeleteSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "DeleteSandbox") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandboxID } @@ -116,7 +150,7 @@ func DeleteSandbox(sandboxID string) (VCSandbox, error) { defer unlockSandbox(lockFile) // Fetch the sandbox from storage and create it. - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -134,7 +168,10 @@ func DeleteSandbox(sandboxID string) (VCSandbox, error) { // FetchSandbox will find out and connect to an existing sandbox and // return the sandbox structure. The caller is responsible of calling // VCSandbox.Release() after done with it. -func FetchSandbox(sandboxID string) (VCSandbox, error) { +func FetchSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "FetchSandbox") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandboxID } @@ -146,7 +183,7 @@ func FetchSandbox(sandboxID string) (VCSandbox, error) { defer unlockSandbox(lockFile) // Fetch the sandbox from storage and create it. - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -168,7 +205,10 @@ func FetchSandbox(sandboxID string) (VCSandbox, error) { // StartSandbox will talk to the given hypervisor to start an existing // sandbox and all its containers. // It returns the sandbox ID. -func StartSandbox(sandboxID string) (VCSandbox, error) { +func StartSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "StartSandbox") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandboxID } @@ -180,7 +220,7 @@ func StartSandbox(sandboxID string) (VCSandbox, error) { defer unlockSandbox(lockFile) // Fetch the sandbox from storage and create it. - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -206,7 +246,10 @@ func startSandbox(s *Sandbox) (*Sandbox, error) { // StopSandbox is the virtcontainers sandbox stopping entry point. // StopSandbox will talk to the given agent to stop an existing sandbox and destroy all containers within that sandbox. -func StopSandbox(sandboxID string) (VCSandbox, error) { +func StopSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "StopSandbox") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandbox } @@ -218,7 +261,7 @@ func StopSandbox(sandboxID string) (VCSandbox, error) { defer unlockSandbox(lockFile) // Fetch the sandbox from storage and create it. - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -245,8 +288,11 @@ func StopSandbox(sandboxID string) (VCSandbox, error) { // RunSandbox is the virtcontainers sandbox running entry point. // RunSandbox creates a sandbox and its containers and then it starts them. -func RunSandbox(sandboxConfig SandboxConfig, factory Factory) (VCSandbox, error) { - s, err := createSandboxFromConfig(sandboxConfig, factory) +func RunSandbox(ctx context.Context, sandboxConfig SandboxConfig, factory Factory) (VCSandbox, error) { + span, ctx := trace(ctx, "RunSandbox") + defer span.Finish() + + s, err := createSandboxFromConfig(ctx, sandboxConfig, factory) if err != nil { return nil, err } @@ -262,7 +308,10 @@ func RunSandbox(sandboxConfig SandboxConfig, factory Factory) (VCSandbox, error) } // ListSandbox is the virtcontainers sandbox listing entry point. -func ListSandbox() ([]SandboxStatus, error) { +func ListSandbox(ctx context.Context) ([]SandboxStatus, error) { + span, ctx := trace(ctx, "ListSandbox") + defer span.Finish() + dir, err := os.Open(configStoragePath) if err != nil { if os.IsNotExist(err) { @@ -282,7 +331,7 @@ func ListSandbox() ([]SandboxStatus, error) { var sandboxStatusList []SandboxStatus for _, sandboxID := range sandboxesID { - sandboxStatus, err := StatusSandbox(sandboxID) + sandboxStatus, err := StatusSandbox(ctx, sandboxID) if err != nil { continue } @@ -294,7 +343,10 @@ func ListSandbox() ([]SandboxStatus, error) { } // StatusSandbox is the virtcontainers sandbox status entry point. -func StatusSandbox(sandboxID string) (SandboxStatus, error) { +func StatusSandbox(ctx context.Context, sandboxID string) (SandboxStatus, error) { + span, ctx := trace(ctx, "StatusSandbox") + defer span.Finish() + if sandboxID == "" { return SandboxStatus{}, errNeedSandboxID } @@ -304,7 +356,7 @@ func StatusSandbox(sandboxID string) (SandboxStatus, error) { return SandboxStatus{}, err } - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { unlockSandbox(lockFile) return SandboxStatus{}, err @@ -346,7 +398,10 @@ func StatusSandbox(sandboxID string) (SandboxStatus, error) { // CreateContainer is the virtcontainers container creation entry point. // CreateContainer creates a container on a given sandbox. -func CreateContainer(sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) { +func CreateContainer(ctx context.Context, sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) { + span, ctx := trace(ctx, "CreateContainer") + defer span.Finish() + if sandboxID == "" { return nil, nil, errNeedSandboxID } @@ -357,7 +412,7 @@ func CreateContainer(sandboxID string, containerConfig ContainerConfig) (VCSandb } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, nil, err } @@ -374,7 +429,7 @@ func CreateContainer(sandboxID string, containerConfig ContainerConfig) (VCSandb // DeleteContainer is the virtcontainers container deletion entry point. // DeleteContainer deletes a Container from a Sandbox. If the container is running, // it needs to be stopped first. -func DeleteContainer(sandboxID, containerID string) (VCContainer, error) { +func DeleteContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -389,7 +444,7 @@ func DeleteContainer(sandboxID, containerID string) (VCContainer, error) { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -400,7 +455,7 @@ func DeleteContainer(sandboxID, containerID string) (VCContainer, error) { // StartContainer is the virtcontainers container starting entry point. // StartContainer starts an already created container. -func StartContainer(sandboxID, containerID string) (VCContainer, error) { +func StartContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -415,7 +470,7 @@ func StartContainer(sandboxID, containerID string) (VCContainer, error) { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -431,7 +486,10 @@ func StartContainer(sandboxID, containerID string) (VCContainer, error) { // StopContainer is the virtcontainers container stopping entry point. // StopContainer stops an already running container. -func StopContainer(sandboxID, containerID string) (VCContainer, error) { +func StopContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { + span, ctx := trace(ctx, "StopContainer") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandboxID } @@ -446,7 +504,7 @@ func StopContainer(sandboxID, containerID string) (VCContainer, error) { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -469,7 +527,10 @@ func StopContainer(sandboxID, containerID string) (VCContainer, error) { // EnterContainer is the virtcontainers container command execution entry point. // EnterContainer enters an already running container and runs a given command. -func EnterContainer(sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) { +func EnterContainer(ctx context.Context, sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) { + span, ctx := trace(ctx, "EnterContainer") + defer span.Finish() + if sandboxID == "" { return nil, nil, nil, errNeedSandboxID } @@ -484,7 +545,7 @@ func EnterContainer(sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContai } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, nil, nil, err } @@ -500,7 +561,10 @@ func EnterContainer(sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContai // StatusContainer is the virtcontainers container status entry point. // StatusContainer returns a detailed container status. -func StatusContainer(sandboxID, containerID string) (ContainerStatus, error) { +func StatusContainer(ctx context.Context, sandboxID, containerID string) (ContainerStatus, error) { + span, ctx := trace(ctx, "StatusContainer") + defer span.Finish() + if sandboxID == "" { return ContainerStatus{}, errNeedSandboxID } @@ -514,7 +578,7 @@ func StatusContainer(sandboxID, containerID string) (ContainerStatus, error) { return ContainerStatus{}, err } - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { unlockSandbox(lockFile) return ContainerStatus{}, err @@ -587,7 +651,10 @@ func statusContainer(sandbox *Sandbox, containerID string) (ContainerStatus, err // KillContainer is the virtcontainers entry point to send a signal // to a container running inside a sandbox. If all is true, all processes in // the container will be sent the signal. -func KillContainer(sandboxID, containerID string, signal syscall.Signal, all bool) error { +func KillContainer(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { + span, ctx := trace(ctx, "KillContainer") + defer span.Finish() + if sandboxID == "" { return errNeedSandboxID } @@ -602,7 +669,7 @@ func KillContainer(sandboxID, containerID string, signal syscall.Signal, all boo } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return err } @@ -625,19 +692,28 @@ func KillContainer(sandboxID, containerID string, signal syscall.Signal, all boo // PauseSandbox is the virtcontainers pausing entry point which pauses an // already running sandbox. -func PauseSandbox(sandboxID string) (VCSandbox, error) { - return togglePauseSandbox(sandboxID, true) +func PauseSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "PauseSandbox") + defer span.Finish() + + return togglePauseSandbox(ctx, sandboxID, true) } // ResumeSandbox is the virtcontainers resuming entry point which resumes // (or unpauses) and already paused sandbox. -func ResumeSandbox(sandboxID string) (VCSandbox, error) { - return togglePauseSandbox(sandboxID, false) +func ResumeSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + span, ctx := trace(ctx, "ResumeSandbox") + defer span.Finish() + + return togglePauseSandbox(ctx, sandboxID, false) } // ProcessListContainer is the virtcontainers entry point to list // processes running inside a container -func ProcessListContainer(sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) { +func ProcessListContainer(ctx context.Context, sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) { + span, ctx := trace(ctx, "ProcessListContainer") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandboxID } @@ -652,7 +728,7 @@ func ProcessListContainer(sandboxID, containerID string, options ProcessListOpti } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -669,7 +745,10 @@ func ProcessListContainer(sandboxID, containerID string, options ProcessListOpti // UpdateContainer is the virtcontainers entry point to update // container's resources. -func UpdateContainer(sandboxID, containerID string, resources specs.LinuxResources) error { +func UpdateContainer(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error { + span, ctx := trace(ctx, "UpdateContainer") + defer span.Finish() + if sandboxID == "" { return errNeedSandboxID } @@ -684,7 +763,7 @@ func UpdateContainer(sandboxID, containerID string, resources specs.LinuxResourc } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return err } @@ -695,7 +774,10 @@ func UpdateContainer(sandboxID, containerID string, resources specs.LinuxResourc // StatsContainer is the virtcontainers container stats entry point. // StatsContainer returns a detailed container stats. -func StatsContainer(sandboxID, containerID string) (ContainerStats, error) { +func StatsContainer(ctx context.Context, sandboxID, containerID string) (ContainerStats, error) { + span, ctx := trace(ctx, "StatsContainer") + defer span.Finish() + if sandboxID == "" { return ContainerStats{}, errNeedSandboxID } @@ -710,7 +792,7 @@ func StatsContainer(sandboxID, containerID string) (ContainerStats, error) { defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return ContainerStats{}, err } @@ -719,7 +801,7 @@ func StatsContainer(sandboxID, containerID string) (ContainerStats, error) { return s.StatsContainer(containerID) } -func togglePauseContainer(sandboxID, containerID string, pause bool) error { +func togglePauseContainer(ctx context.Context, sandboxID, containerID string, pause bool) error { if sandboxID == "" { return errNeedSandboxID } @@ -734,7 +816,7 @@ func togglePauseContainer(sandboxID, containerID string, pause bool) error { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return err } @@ -754,17 +836,23 @@ func togglePauseContainer(sandboxID, containerID string, pause bool) error { } // PauseContainer is the virtcontainers container pause entry point. -func PauseContainer(sandboxID, containerID string) error { - return togglePauseContainer(sandboxID, containerID, true) +func PauseContainer(ctx context.Context, sandboxID, containerID string) error { + span, ctx := trace(ctx, "PauseContainer") + defer span.Finish() + + return togglePauseContainer(ctx, sandboxID, containerID, true) } // ResumeContainer is the virtcontainers container resume entry point. -func ResumeContainer(sandboxID, containerID string) error { - return togglePauseContainer(sandboxID, containerID, false) +func ResumeContainer(ctx context.Context, sandboxID, containerID string) error { + span, ctx := trace(ctx, "ResumeContainer") + defer span.Finish() + + return togglePauseContainer(ctx, sandboxID, containerID, false) } // AddDevice will add a device to sandbox -func AddDevice(sandboxID string, info deviceConfig.DeviceInfo) (deviceApi.Device, error) { +func AddDevice(ctx context.Context, sandboxID string, info deviceConfig.DeviceInfo) (deviceApi.Device, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -775,7 +863,7 @@ func AddDevice(sandboxID string, info deviceConfig.DeviceInfo) (deviceApi.Device } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -784,7 +872,7 @@ func AddDevice(sandboxID string, info deviceConfig.DeviceInfo) (deviceApi.Device return s.AddDevice(info) } -func toggleInterface(sandboxID string, inf *grpc.Interface, add bool) (*grpc.Interface, error) { +func toggleInterface(ctx context.Context, sandboxID string, inf *grpc.Interface, add bool) (*grpc.Interface, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -795,7 +883,7 @@ func toggleInterface(sandboxID string, inf *grpc.Interface, add bool) (*grpc.Int } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -806,17 +894,17 @@ func toggleInterface(sandboxID string, inf *grpc.Interface, add bool) (*grpc.Int } // AddInterface is the virtcontainers add interface entry point. -func AddInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { - return toggleInterface(sandboxID, inf, true) +func AddInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + return toggleInterface(ctx, sandboxID, inf, true) } // RemoveInterface is the virtcontainers remove interface entry point. -func RemoveInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { - return toggleInterface(sandboxID, inf, false) +func RemoveInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + return toggleInterface(ctx, sandboxID, inf, false) } // ListInterfaces is the virtcontainers list interfaces entry point. -func ListInterfaces(sandboxID string) ([]*grpc.Interface, error) { +func ListInterfaces(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -827,7 +915,7 @@ func ListInterfaces(sandboxID string) ([]*grpc.Interface, error) { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -836,7 +924,7 @@ func ListInterfaces(sandboxID string) ([]*grpc.Interface, error) { } // UpdateRoutes is the virtcontainers update routes entry point. -func UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { +func UpdateRoutes(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -847,7 +935,7 @@ func UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -855,7 +943,7 @@ func UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) } // ListRoutes is the virtcontainers list routes entry point. -func ListRoutes(sandboxID string) ([]*grpc.Route, error) { +func ListRoutes(ctx context.Context, sandboxID string) ([]*grpc.Route, error) { if sandboxID == "" { return nil, errNeedSandboxID } @@ -866,7 +954,7 @@ func ListRoutes(sandboxID string) ([]*grpc.Route, error) { } defer unlockSandbox(lockFile) - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } diff --git a/virtcontainers/api_test.go b/virtcontainers/api_test.go index 6fc29d0c5..9dacef48f 100644 --- a/virtcontainers/api_test.go +++ b/virtcontainers/api_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "io/ioutil" "os" @@ -200,7 +201,7 @@ func TestCreateSandboxNoopAgentSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(context.Background(), config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -245,7 +246,7 @@ func TestCreateSandboxHyperstartAgentSuccessful(t *testing.T) { proxy.Start() defer proxy.Stop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(context.Background(), config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -286,7 +287,7 @@ func TestCreateSandboxKataAgentSuccessful(t *testing.T) { } defer kataProxyMock.Stop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(context.Background(), config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -303,7 +304,7 @@ func TestCreateSandboxFailing(t *testing.T) { config := SandboxConfig{} - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(context.Background(), config, nil) if p.(*Sandbox) != nil || err == nil { t.Fatal() } @@ -312,9 +313,10 @@ func TestCreateSandboxFailing(t *testing.T) { func TestDeleteSandboxNoopAgentSuccessful(t *testing.T) { cleanUp() + ctx := context.Background() config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -325,7 +327,7 @@ func TestDeleteSandboxNoopAgentSuccessful(t *testing.T) { t.Fatal(err) } - p, err = DeleteSandbox(p.ID()) + p, err = DeleteSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -357,7 +359,9 @@ func TestDeleteSandboxHyperstartAgentSuccessful(t *testing.T) { proxy.Start() defer proxy.Stop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -368,7 +372,7 @@ func TestDeleteSandboxHyperstartAgentSuccessful(t *testing.T) { t.Fatal(err) } - p, err = DeleteSandbox(p.ID()) + p, err = DeleteSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -408,7 +412,8 @@ func TestDeleteSandboxKataAgentSuccessful(t *testing.T) { } defer kataProxyMock.Stop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -419,7 +424,7 @@ func TestDeleteSandboxKataAgentSuccessful(t *testing.T) { t.Fatal(err) } - p, err = DeleteSandbox(p.ID()) + p, err = DeleteSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -436,7 +441,7 @@ func TestDeleteSandboxFailing(t *testing.T) { sandboxDir := filepath.Join(configStoragePath, testSandboxID) os.Remove(sandboxDir) - p, err := DeleteSandbox(testSandboxID) + p, err := DeleteSandbox(context.Background(), testSandboxID) if p != nil || err == nil { t.Fatal() } @@ -447,7 +452,7 @@ func TestStartSandboxNoopAgentSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, _, err := createAndStartSandbox(config) + p, _, err := createAndStartSandbox(context.Background(), config) if p == nil || err != nil { t.Fatal(err) } @@ -477,7 +482,8 @@ func TestStartSandboxHyperstartAgentSuccessful(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } @@ -485,7 +491,7 @@ func TestStartSandboxHyperstartAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestStartSandboxKataAgentSuccessful(t *testing.T) { @@ -517,7 +523,8 @@ func TestStartSandboxKataAgentSuccessful(t *testing.T) { } defer kataProxyMock.Stop() - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } @@ -525,7 +532,7 @@ func TestStartSandboxKataAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestStartSandboxFailing(t *testing.T) { @@ -534,7 +541,7 @@ func TestStartSandboxFailing(t *testing.T) { sandboxDir := filepath.Join(configStoragePath, testSandboxID) os.Remove(sandboxDir) - p, err := StartSandbox(testSandboxID) + p, err := StartSandbox(context.Background(), testSandboxID) if p != nil || err == nil { t.Fatal() } @@ -545,12 +552,13 @@ func TestStopSandboxNoopAgentSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } - vp, err := StopSandbox(p.ID()) + vp, err := StopSandbox(ctx, p.ID()) if vp == nil || err != nil { t.Fatal(err) } @@ -561,7 +569,9 @@ func TestPauseThenResumeSandboxNoopAgentSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } @@ -569,12 +579,12 @@ func TestPauseThenResumeSandboxNoopAgentSuccessful(t *testing.T) { contID := "100" contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } - p, err = PauseSandbox(p.ID()) + p, err = PauseSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -594,7 +604,7 @@ func TestPauseThenResumeSandboxNoopAgentSuccessful(t *testing.T) { fmt.Sprintf("paused container %d has unexpected state", i)) } - p, err = ResumeSandbox(p.ID()) + p, err = ResumeSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -639,12 +649,13 @@ func TestStopSandboxHyperstartAgentSuccessful(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } - p, err = StopSandbox(p.ID()) + p, err = StopSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -679,12 +690,13 @@ func TestStopSandboxKataAgentSuccessful(t *testing.T) { } defer kataProxyMock.Stop() - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } - p, err = StopSandbox(p.ID()) + p, err = StopSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -696,7 +708,7 @@ func TestStopSandboxFailing(t *testing.T) { sandboxDir := filepath.Join(configStoragePath, testSandboxID) os.Remove(sandboxDir) - p, err := StopSandbox(testSandboxID) + p, err := StopSandbox(context.Background(), testSandboxID) if p != nil || err == nil { t.Fatal() } @@ -707,7 +719,7 @@ func TestRunSandboxNoopAgentSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, err := RunSandbox(config, nil) + p, err := RunSandbox(context.Background(), config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -743,7 +755,8 @@ func TestRunSandboxHyperstartAgentSuccessful(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, err := RunSandbox(config, nil) + ctx := context.Background() + p, err := RunSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -757,7 +770,7 @@ func TestRunSandboxHyperstartAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestRunSandboxKataAgentSuccessful(t *testing.T) { @@ -789,7 +802,8 @@ func TestRunSandboxKataAgentSuccessful(t *testing.T) { } defer kataProxyMock.Stop() - p, err := RunSandbox(config, nil) + ctx := context.Background() + p, err := RunSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -803,7 +817,7 @@ func TestRunSandboxKataAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestRunSandboxFailing(t *testing.T) { @@ -811,7 +825,7 @@ func TestRunSandboxFailing(t *testing.T) { config := SandboxConfig{} - p, err := RunSandbox(config, nil) + p, err := RunSandbox(context.Background(), config, nil) if p != nil || err == nil { t.Fatal() } @@ -824,12 +838,13 @@ func TestListSandboxSuccessful(t *testing.T) { config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } - _, err = ListSandbox() + _, err = ListSandbox(ctx) if err != nil { t.Fatal(err) } @@ -840,7 +855,7 @@ func TestListSandboxNoSandboxDirectory(t *testing.T) { os.RemoveAll(configStoragePath) - _, err := ListSandbox() + _, err := ListSandbox(context.Background()) if err != nil { t.Fatal(fmt.Sprintf("unexpected ListSandbox error from non-existent sandbox directory: %v", err)) } @@ -884,12 +899,13 @@ func TestStatusSandboxSuccessfulStateReady(t *testing.T) { }, } - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } - status, err := StatusSandbox(p.ID()) + status, err := StatusSandbox(ctx, p.ID()) if err != nil { t.Fatal(err) } @@ -941,17 +957,18 @@ func TestStatusSandboxSuccessfulStateRunning(t *testing.T) { }, } - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } - p, err = StartSandbox(p.ID()) + p, err = StartSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } - status, err := StatusSandbox(p.ID()) + status, err := StatusSandbox(ctx, p.ID()) if err != nil { t.Fatal(err) } @@ -970,7 +987,8 @@ func TestStatusSandboxFailingFetchSandboxConfig(t *testing.T) { config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -979,7 +997,7 @@ func TestStatusSandboxFailingFetchSandboxConfig(t *testing.T) { os.RemoveAll(path) globalSandboxList.removeSandbox(p.ID()) - _, err = StatusSandbox(p.ID()) + _, err = StatusSandbox(ctx, p.ID()) if err == nil { t.Fatal() } @@ -990,7 +1008,8 @@ func TestStatusPodSandboxFailingFetchSandboxState(t *testing.T) { config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1001,7 +1020,7 @@ func TestStatusPodSandboxFailingFetchSandboxState(t *testing.T) { os.RemoveAll(pImpl.configPath) globalSandboxList.removeSandbox(p.ID()) - _, err = StatusSandbox(p.ID()) + _, err = StatusSandbox(ctx, p.ID()) if err == nil { t.Fatal() } @@ -1025,7 +1044,8 @@ func TestCreateContainerSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1038,7 +1058,7 @@ func TestCreateContainerSuccessful(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1056,12 +1076,13 @@ func TestCreateContainerFailingNoSandbox(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } - p, err = DeleteSandbox(p.ID()) + p, err = DeleteSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -1074,7 +1095,7 @@ func TestCreateContainerFailingNoSandbox(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c != nil || err == nil { t.Fatal(err) } @@ -1086,7 +1107,8 @@ func TestDeleteContainerSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1099,7 +1121,7 @@ func TestDeleteContainerSuccessful(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1110,7 +1132,7 @@ func TestDeleteContainerSuccessful(t *testing.T) { t.Fatal(err) } - c, err = DeleteContainer(p.ID(), contID) + c, err = DeleteContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } @@ -1128,7 +1150,7 @@ func TestDeleteContainerFailingNoSandbox(t *testing.T) { contID := "100" os.RemoveAll(sandboxDir) - c, err := DeleteContainer(testSandboxID, contID) + c, err := DeleteContainer(context.Background(), testSandboxID, contID) if c != nil || err == nil { t.Fatal() } @@ -1140,7 +1162,8 @@ func TestDeleteContainerFailingNoContainer(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1151,7 +1174,7 @@ func TestDeleteContainerFailingNoContainer(t *testing.T) { t.Fatal(err) } - c, err := DeleteContainer(p.ID(), contID) + c, err := DeleteContainer(ctx, p.ID(), contID) if c != nil || err == nil { t.Fatal() } @@ -1163,13 +1186,15 @@ func TestStartContainerNoopAgentSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1180,7 +1205,7 @@ func TestStartContainerNoopAgentSuccessful(t *testing.T) { t.Fatal(err) } - c, err = StartContainer(p.ID(), contID) + c, err = StartContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } @@ -1193,7 +1218,7 @@ func TestStartContainerFailingNoSandbox(t *testing.T) { contID := "100" os.RemoveAll(sandboxDir) - c, err := StartContainer(testSandboxID, contID) + c, err := StartContainer(context.Background(), testSandboxID, contID) if c != nil || err == nil { t.Fatal() } @@ -1205,7 +1230,8 @@ func TestStartContainerFailingNoContainer(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1216,7 +1242,7 @@ func TestStartContainerFailingNoContainer(t *testing.T) { t.Fatal(err) } - c, err := StartContainer(p.ID(), contID) + c, err := StartContainer(ctx, p.ID(), contID) if c != nil || err == nil { t.Fatal() } @@ -1228,7 +1254,8 @@ func TestStartContainerFailingSandboxNotStarted(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1241,7 +1268,7 @@ func TestStartContainerFailingSandboxNotStarted(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1252,7 +1279,7 @@ func TestStartContainerFailingSandboxNotStarted(t *testing.T) { t.Fatal(err) } - _, err = StartContainer(p.ID(), contID) + _, err = StartContainer(ctx, p.ID(), contID) if err == nil { t.Fatal("Function should have failed") } @@ -1264,14 +1291,16 @@ func TestStopContainerNoopAgentSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1282,12 +1311,12 @@ func TestStopContainerNoopAgentSuccessful(t *testing.T) { t.Fatal(err) } - c, err = StartContainer(p.ID(), contID) + c, err = StartContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } - c, err = StopContainer(p.ID(), contID) + c, err = StopContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } @@ -1318,14 +1347,16 @@ func TestStartStopContainerHyperstartAgentSuccessful(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1336,12 +1367,12 @@ func TestStartStopContainerHyperstartAgentSuccessful(t *testing.T) { t.Fatal(err) } - c, err = StartContainer(p.ID(), contID) + c, err = StartContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } - c, err = StopContainer(p.ID(), contID) + c, err = StopContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } @@ -1349,7 +1380,7 @@ func TestStartStopContainerHyperstartAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestStartStopSandboxHyperstartAgentSuccessfulWithCNMNetwork(t *testing.T) { @@ -1376,17 +1407,19 @@ func TestStartStopSandboxHyperstartAgentSuccessfulWithCNMNetwork(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, _, err := createAndStartSandbox(config) + ctx := context.Background() + + p, _, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } - v, err := StopSandbox(p.ID()) + v, err := StopSandbox(ctx, p.ID()) if v == nil || err != nil { t.Fatal(err) } - v, err = DeleteSandbox(p.ID()) + v, err = DeleteSandbox(ctx, p.ID()) if v == nil || err != nil { t.Fatal(err) } @@ -1399,7 +1432,7 @@ func TestStopContainerFailingNoSandbox(t *testing.T) { contID := "100" os.RemoveAll(sandboxDir) - c, err := StopContainer(testSandboxID, contID) + c, err := StopContainer(context.Background(), testSandboxID, contID) if c != nil || err == nil { t.Fatal() } @@ -1411,7 +1444,8 @@ func TestStopContainerFailingNoContainer(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1422,7 +1456,7 @@ func TestStopContainerFailingNoContainer(t *testing.T) { t.Fatal(err) } - c, err := StopContainer(p.ID(), contID) + c, err := StopContainer(ctx, p.ID(), contID) if c != nil || err == nil { t.Fatal() } @@ -1434,14 +1468,16 @@ func testKillContainerFromContReadySuccessful(t *testing.T, signal syscall.Signa contID := "100" config := newTestSandboxConfigNoop() - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1452,7 +1488,7 @@ func testKillContainerFromContReadySuccessful(t *testing.T, signal syscall.Signa t.Fatal(err) } - if err := KillContainer(p.ID(), contID, signal, false); err != nil { + if err := KillContainer(ctx, p.ID(), contID, signal, false); err != nil { t.Fatal() } } @@ -1474,14 +1510,16 @@ func TestEnterContainerNoopAgentSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1492,14 +1530,14 @@ func TestEnterContainerNoopAgentSuccessful(t *testing.T) { t.Fatal(err) } - c, err = StartContainer(p.ID(), contID) + c, err = StartContainer(ctx, p.ID(), contID) if c == nil || err != nil { t.Fatal(err) } cmd := newBasicTestCmd() - _, c, _, err = EnterContainer(p.ID(), contID, cmd) + _, c, _, err = EnterContainer(ctx, p.ID(), contID, cmd) if c == nil || err != nil { t.Fatal(err) } @@ -1530,14 +1568,16 @@ func TestEnterContainerHyperstartAgentSuccessful(t *testing.T) { hyperConfig := config.AgentConfig.(HyperConfig) config.AgentConfig = hyperConfig - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, _, err = CreateContainer(p.ID(), contConfig) + _, _, err = CreateContainer(ctx, p.ID(), contConfig) if err != nil { t.Fatal(err) } @@ -1548,19 +1588,19 @@ func TestEnterContainerHyperstartAgentSuccessful(t *testing.T) { t.Fatal(err) } - _, err = StartContainer(p.ID(), contID) + _, err = StartContainer(ctx, p.ID(), contID) if err != nil { t.Fatal(err) } cmd := newBasicTestCmd() - _, _, _, err = EnterContainer(p.ID(), contID, cmd) + _, _, _, err = EnterContainer(ctx, p.ID(), contID, cmd) if err != nil { t.Fatal(err) } - _, err = StopContainer(p.ID(), contID) + _, err = StopContainer(ctx, p.ID(), contID) if err != nil { t.Fatal(err) } @@ -1568,7 +1608,7 @@ func TestEnterContainerHyperstartAgentSuccessful(t *testing.T) { pImpl, ok := p.(*Sandbox) assert.True(t, ok) - bindUnmountAllRootfs(defaultSharedDir, pImpl) + bindUnmountAllRootfs(ctx, defaultSharedDir, pImpl) } func TestEnterContainerFailingNoSandbox(t *testing.T) { @@ -1580,7 +1620,7 @@ func TestEnterContainerFailingNoSandbox(t *testing.T) { cmd := newBasicTestCmd() - _, c, _, err := EnterContainer(testSandboxID, contID, cmd) + _, c, _, err := EnterContainer(context.Background(), testSandboxID, contID, cmd) if c != nil || err == nil { t.Fatal() } @@ -1592,7 +1632,8 @@ func TestEnterContainerFailingNoContainer(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1605,7 +1646,7 @@ func TestEnterContainerFailingNoContainer(t *testing.T) { cmd := newBasicTestCmd() - _, c, _, err := EnterContainer(p.ID(), contID, cmd) + _, c, _, err := EnterContainer(ctx, p.ID(), contID, cmd) if c != nil || err == nil { t.Fatal() } @@ -1617,14 +1658,16 @@ func TestEnterContainerFailingContNotStarted(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, sandboxDir, err := createAndStartSandbox(config) + ctx := context.Background() + + p, sandboxDir, err := createAndStartSandbox(ctx, config) if p == nil || err != nil { t.Fatal(err) } contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1637,7 +1680,7 @@ func TestEnterContainerFailingContNotStarted(t *testing.T) { cmd := newBasicTestCmd() - _, c, _, err = EnterContainer(p.ID(), contID, cmd) + _, c, _, err = EnterContainer(ctx, p.ID(), contID, cmd) if c == nil || err != nil { t.Fatal() } @@ -1649,7 +1692,8 @@ func TestStatusContainerSuccessful(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1662,7 +1706,7 @@ func TestStatusContainerSuccessful(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1673,7 +1717,7 @@ func TestStatusContainerSuccessful(t *testing.T) { t.Fatal(err) } - status, err := StatusContainer(p.ID(), contID) + status, err := StatusContainer(ctx, p.ID(), contID) if err != nil { t.Fatal(err) } @@ -1700,7 +1744,8 @@ func TestStatusContainerStateReady(t *testing.T) { contID := "101" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1713,7 +1758,7 @@ func TestStatusContainerStateReady(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } @@ -1725,7 +1770,7 @@ func TestStatusContainerStateReady(t *testing.T) { } // fresh lookup - p2, err := fetchSandbox(p.ID()) + p2, err := fetchSandbox(ctx, p.ID()) if err != nil { t.Fatal(err) } @@ -1764,12 +1809,13 @@ func TestStatusContainerStateRunning(t *testing.T) { contID := "101" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } - p, err = StartSandbox(p.ID()) + p, err = StartSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -1782,12 +1828,12 @@ func TestStatusContainerStateRunning(t *testing.T) { contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) if c == nil || err != nil { t.Fatal(err) } - c, err = StartContainer(p.ID(), c.ID()) + c, err = StartContainer(ctx, p.ID(), c.ID()) if c == nil || err != nil { t.Fatal(err) } @@ -1799,7 +1845,7 @@ func TestStatusContainerStateRunning(t *testing.T) { } // fresh lookup - p2, err := fetchSandbox(p.ID()) + p2, err := fetchSandbox(ctx, p.ID()) if err != nil { t.Fatal(err) } @@ -1837,7 +1883,8 @@ func TestStatusContainerFailing(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1848,7 +1895,7 @@ func TestStatusContainerFailing(t *testing.T) { os.RemoveAll(pImpl.configPath) globalSandboxList.removeSandbox(p.ID()) - _, err = StatusContainer(p.ID(), contID) + _, err = StatusContainer(ctx, p.ID(), contID) if err == nil { t.Fatal() } @@ -1860,7 +1907,8 @@ func TestStatsContainerFailing(t *testing.T) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if p == nil || err != nil { t.Fatal(err) } @@ -1871,7 +1919,7 @@ func TestStatsContainerFailing(t *testing.T) { os.RemoveAll(pImpl.configPath) globalSandboxList.removeSandbox(p.ID()) - _, err = StatsContainer(p.ID(), contID) + _, err = StatsContainer(ctx, p.ID(), contID) if err == nil { t.Fatal() } @@ -1883,21 +1931,22 @@ func TestStatsContainer(t *testing.T) { assert := assert.New(t) contID := "100" - _, err := StatsContainer("", "") + ctx := context.Background() + _, err := StatsContainer(ctx, "", "") assert.Error(err) - _, err = StatsContainer("abc", "") + _, err = StatsContainer(ctx, "abc", "") assert.Error(err) - _, err = StatsContainer("abc", "abc") + _, err = StatsContainer(ctx, "abc", "abc") assert.Error(err) config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(ctx, config, nil) assert.NoError(err) assert.NotNil(p) - p, err = StartSandbox(p.ID()) + p, err = StartSandbox(ctx, p.ID()) if p == nil || err != nil { t.Fatal(err) } @@ -1907,17 +1956,17 @@ func TestStatsContainer(t *testing.T) { defer os.RemoveAll(pImpl.configPath) contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) assert.NoError(err) assert.NotNil(c) - _, err = StatsContainer(pImpl.id, "xyz") + _, err = StatsContainer(ctx, pImpl.id, "xyz") assert.Error(err) - _, err = StatsContainer("xyz", contID) + _, err = StatsContainer(ctx, "xyz", contID) assert.Error(err) - stats, err := StatsContainer(pImpl.id, contID) + stats, err := StatsContainer(ctx, pImpl.id, contID) assert.NoError(err) assert.Equal(stats, ContainerStats{}) } @@ -1933,17 +1982,18 @@ func TestProcessListContainer(t *testing.T) { Args: []string{"-ef"}, } - _, err := ProcessListContainer("", "", options) + ctx := context.Background() + _, err := ProcessListContainer(ctx, "", "", options) assert.Error(err) - _, err = ProcessListContainer("xyz", "", options) + _, err = ProcessListContainer(ctx, "xyz", "", options) assert.Error(err) - _, err = ProcessListContainer("xyz", "xyz", options) + _, err = ProcessListContainer(ctx, "xyz", "xyz", options) assert.Error(err) config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + p, err := CreateSandbox(ctx, config, nil) assert.NoError(err) assert.NotNil(p) @@ -1952,17 +2002,17 @@ func TestProcessListContainer(t *testing.T) { defer os.RemoveAll(pImpl.configPath) contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(p.ID(), contConfig) + _, c, err := CreateContainer(ctx, p.ID(), contConfig) assert.NoError(err) assert.NotNil(c) - _, err = ProcessListContainer(pImpl.id, "xyz", options) + _, err = ProcessListContainer(ctx, pImpl.id, "xyz", options) assert.Error(err) - _, err = ProcessListContainer("xyz", contID, options) + _, err = ProcessListContainer(ctx, "xyz", contID, options) assert.Error(err) - _, err = ProcessListContainer(pImpl.id, contID, options) + _, err = ProcessListContainer(ctx, pImpl.id, contID, options) // Sandbox not running, impossible to ps the container assert.Error(err) } @@ -2031,11 +2081,11 @@ func createNewContainerConfigs(numOfContainers int) []ContainerConfig { // createAndStartSandbox handles the common test operation of creating and // starting a sandbox. -func createAndStartSandbox(config SandboxConfig) (sandbox VCSandbox, sandboxDir string, +func createAndStartSandbox(ctx context.Context, config SandboxConfig) (sandbox VCSandbox, sandboxDir string, err error) { // Create sandbox - sandbox, err = CreateSandbox(config, nil) + sandbox, err = CreateSandbox(ctx, config, nil) if sandbox == nil || err != nil { return nil, "", err } @@ -2047,7 +2097,7 @@ func createAndStartSandbox(config SandboxConfig) (sandbox VCSandbox, sandboxDir } // Start sandbox - sandbox, err = StartSandbox(sandbox.ID()) + sandbox, err = StartSandbox(ctx, sandbox.ID()) if sandbox == nil || err != nil { return nil, "", err } @@ -2056,40 +2106,44 @@ func createAndStartSandbox(config SandboxConfig) (sandbox VCSandbox, sandboxDir } func createStartStopDeleteSandbox(b *testing.B, sandboxConfig SandboxConfig) { - p, _, err := createAndStartSandbox(sandboxConfig) + ctx := context.Background() + + p, _, err := createAndStartSandbox(ctx, sandboxConfig) if p == nil || err != nil { b.Fatalf("Could not create and start sandbox: %s", err) } // Stop sandbox - _, err = StopSandbox(p.ID()) + _, err = StopSandbox(ctx, p.ID()) if err != nil { b.Fatalf("Could not stop sandbox: %s", err) } // Delete sandbox - _, err = DeleteSandbox(p.ID()) + _, err = DeleteSandbox(ctx, p.ID()) if err != nil { b.Fatalf("Could not delete sandbox: %s", err) } } func createStartStopDeleteContainers(b *testing.B, sandboxConfig SandboxConfig, contConfigs []ContainerConfig) { + ctx := context.Background() + // Create sandbox - p, err := CreateSandbox(sandboxConfig, nil) + p, err := CreateSandbox(ctx, sandboxConfig, nil) if err != nil { b.Fatalf("Could not create sandbox: %s", err) } // Start sandbox - _, err = StartSandbox(p.ID()) + _, err = StartSandbox(ctx, p.ID()) if err != nil { b.Fatalf("Could not start sandbox: %s", err) } // Create containers for _, contConfig := range contConfigs { - _, _, err := CreateContainer(p.ID(), contConfig) + _, _, err := CreateContainer(ctx, p.ID(), contConfig) if err != nil { b.Fatalf("Could not create container %s: %s", contConfig.ID, err) } @@ -2097,7 +2151,7 @@ func createStartStopDeleteContainers(b *testing.B, sandboxConfig SandboxConfig, // Start containers for _, contConfig := range contConfigs { - _, err := StartContainer(p.ID(), contConfig.ID) + _, err := StartContainer(ctx, p.ID(), contConfig.ID) if err != nil { b.Fatalf("Could not start container %s: %s", contConfig.ID, err) } @@ -2105,7 +2159,7 @@ func createStartStopDeleteContainers(b *testing.B, sandboxConfig SandboxConfig, // Stop containers for _, contConfig := range contConfigs { - _, err := StopContainer(p.ID(), contConfig.ID) + _, err := StopContainer(ctx, p.ID(), contConfig.ID) if err != nil { b.Fatalf("Could not stop container %s: %s", contConfig.ID, err) } @@ -2113,20 +2167,20 @@ func createStartStopDeleteContainers(b *testing.B, sandboxConfig SandboxConfig, // Delete containers for _, contConfig := range contConfigs { - _, err := DeleteContainer(p.ID(), contConfig.ID) + _, err := DeleteContainer(ctx, p.ID(), contConfig.ID) if err != nil { b.Fatalf("Could not delete container %s: %s", contConfig.ID, err) } } // Stop sandbox - _, err = StopSandbox(p.ID()) + _, err = StopSandbox(ctx, p.ID()) if err != nil { b.Fatalf("Could not stop sandbox: %s", err) } // Delete sandbox - _, err = DeleteSandbox(p.ID()) + _, err = DeleteSandbox(ctx, p.ID()) if err != nil { b.Fatalf("Could not delete sandbox: %s", err) } @@ -2216,12 +2270,14 @@ func TestFetchSandbox(t *testing.T) { config := newTestSandboxConfigNoop() - s, err := CreateSandbox(config, nil) + ctx := context.Background() + + s, err := CreateSandbox(ctx, config, nil) if s == nil || err != nil { t.Fatal(err) } - fetched, err := FetchSandbox(s.ID()) + fetched, err := FetchSandbox(ctx, s.ID()) assert.Nil(t, err, "%v", err) assert.True(t, fetched != s, "fetched stateless sandboxes should not match") } @@ -2232,12 +2288,15 @@ func TestFetchStatefulSandbox(t *testing.T) { config := newTestSandboxConfigNoop() config.Stateful = true - s, err := CreateSandbox(config, nil) + + ctx := context.Background() + + s, err := CreateSandbox(ctx, config, nil) if s == nil || err != nil { t.Fatal(err) } - fetched, err := FetchSandbox(s.ID()) + fetched, err := FetchSandbox(ctx, s.ID()) assert.Nil(t, err, "%v", err) assert.Equal(t, fetched, s, "fetched stateful sandboxed should match") } @@ -2245,7 +2304,7 @@ func TestFetchStatefulSandbox(t *testing.T) { func TestFetchNonExistingSandbox(t *testing.T) { cleanUp() - _, err := FetchSandbox("some-non-existing-sandbox-name") + _, err := FetchSandbox(context.Background(), "some-non-existing-sandbox-name") assert.NotNil(t, err, "fetch non-existing sandbox should fail") } @@ -2254,7 +2313,7 @@ func TestReleaseSandbox(t *testing.T) { config := newTestSandboxConfigNoop() - s, err := CreateSandbox(config, nil) + s, err := CreateSandbox(context.Background(), config, nil) if s == nil || err != nil { t.Fatal(err) } @@ -2269,6 +2328,8 @@ func TestUpdateContainer(t *testing.T) { cleanUp() + ctx := context.Background() + period := uint64(1000) quota := int64(2000) assert := assert.New(t) @@ -2278,21 +2339,21 @@ func TestUpdateContainer(t *testing.T) { Quota: "a, }, } - err := UpdateContainer("", "", resources) + err := UpdateContainer(ctx, "", "", resources) assert.Error(err) - err = UpdateContainer("abc", "", resources) + err = UpdateContainer(ctx, "abc", "", resources) assert.Error(err) contID := "100" config := newTestSandboxConfigNoop() - s, sandboxDir, err := createAndStartSandbox(config) + s, sandboxDir, err := createAndStartSandbox(ctx, config) assert.NoError(err) assert.NotNil(s) contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(s.ID(), contConfig) + _, c, err := CreateContainer(ctx, s.ID(), contConfig) assert.NoError(err) assert.NotNil(c) @@ -2300,10 +2361,10 @@ func TestUpdateContainer(t *testing.T) { _, err = os.Stat(contDir) assert.NoError(err) - _, err = StartContainer(s.ID(), contID) + _, err = StartContainer(ctx, s.ID(), contID) assert.NoError(err) - err = UpdateContainer(s.ID(), contID, resources) + err = UpdateContainer(ctx, s.ID(), contID, resources) assert.NoError(err) } @@ -2314,22 +2375,24 @@ func TestPauseResumeContainer(t *testing.T) { cleanUp() + ctx := context.Background() + assert := assert.New(t) - err := PauseContainer("", "") + err := PauseContainer(ctx, "", "") assert.Error(err) - err = PauseContainer("abc", "") + err = PauseContainer(ctx, "abc", "") assert.Error(err) contID := "100" config := newTestSandboxConfigNoop() - s, sandboxDir, err := createAndStartSandbox(config) + s, sandboxDir, err := createAndStartSandbox(ctx, config) assert.NoError(err) assert.NotNil(s) contConfig := newTestContainerConfigNoop(contID) - _, c, err := CreateContainer(s.ID(), contConfig) + _, c, err := CreateContainer(ctx, s.ID(), contConfig) assert.NoError(err) assert.NotNil(c) @@ -2337,13 +2400,13 @@ func TestPauseResumeContainer(t *testing.T) { _, err = os.Stat(contDir) assert.NoError(err) - _, err = StartContainer(s.ID(), contID) + _, err = StartContainer(ctx, s.ID(), contID) assert.NoError(err) - err = PauseContainer(s.ID(), contID) + err = PauseContainer(ctx, s.ID(), contID) assert.NoError(err) - err = ResumeContainer(s.ID(), contID) + err = ResumeContainer(ctx, s.ID(), contID) assert.NoError(err) } @@ -2367,10 +2430,12 @@ func TestNetworkOperation(t *testing.T) { } inf.IPAddresses = append(inf.IPAddresses, &ip) - _, err := AddInterface("", inf) + ctx := context.Background() + + _, err := AddInterface(ctx, "", inf) assert.Error(err) - _, err = AddInterface("abc", inf) + _, err = AddInterface(ctx, "abc", inf) assert.Error(err) netNSPath, err := createNetNS() @@ -2383,22 +2448,22 @@ func TestNetworkOperation(t *testing.T) { NetNSPath: netNSPath, } - s, _, err := createAndStartSandbox(config) + s, _, err := createAndStartSandbox(ctx, config) assert.NoError(err) assert.NotNil(s) - _, err = AddInterface(s.ID(), inf) + _, err = AddInterface(ctx, s.ID(), inf) assert.Error(err) - _, err = RemoveInterface(s.ID(), inf) + _, err = RemoveInterface(ctx, s.ID(), inf) assert.NoError(err) - _, err = ListInterfaces(s.ID()) + _, err = ListInterfaces(ctx, s.ID()) assert.NoError(err) - _, err = UpdateRoutes(s.ID(), nil) + _, err = UpdateRoutes(ctx, s.ID(), nil) assert.NoError(err) - _, err = ListRoutes(s.ID()) + _, err = ListRoutes(ctx, s.ID()) assert.NoError(err) } diff --git a/virtcontainers/cnm.go b/virtcontainers/cnm.go index e565ce0e8..f0b64cfd6 100644 --- a/virtcontainers/cnm.go +++ b/virtcontainers/cnm.go @@ -6,29 +6,59 @@ package virtcontainers import ( + "context" + + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" ) // cnm is a network implementation for the CNM plugin. type cnm struct { + ctx context.Context } -func cnmLogger() *logrus.Entry { +func (n *cnm) Logger() *logrus.Entry { return virtLog.WithField("subsystem", "cnm") } +func (n *cnm) trace(name string) (opentracing.Span, context.Context) { + if n.ctx == nil { + n.Logger().WithField("type", "bug").Error("trace called before context set") + n.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(n.ctx, name) + + span.SetTag("subsystem", "network") + span.SetTag("type", "cnm") + + return span, ctx +} + // init initializes the network, setting a new network namespace for the CNM network. -func (n *cnm) init(config NetworkConfig) (string, bool, error) { +func (n *cnm) init(ctx context.Context, config NetworkConfig) (string, bool, error) { + // Set context + n.ctx = ctx + + span, _ := n.trace("init") + defer span.Finish() + return initNetworkCommon(config) } // run runs a callback in the specified network namespace. func (n *cnm) run(networkNSPath string, cb func() error) error { + span, _ := n.trace("run") + defer span.Finish() + return runNetworkCommon(networkNSPath, cb) } // add adds all needed interfaces inside the network namespace for the CNM network. func (n *cnm) add(sandbox *Sandbox, config NetworkConfig, netNsPath string, netNsCreated bool) (NetworkNamespace, error) { + span, _ := n.trace("add") + defer span.Finish() + endpoints, err := createEndpointsFromScan(netNsPath, config) if err != nil { return NetworkNamespace{}, err @@ -50,6 +80,18 @@ func (n *cnm) add(sandbox *Sandbox, config NetworkConfig, netNsPath string, netN // remove network endpoints in the network namespace. It also deletes the network // namespace in case the namespace has been created by us. func (n *cnm) remove(sandbox *Sandbox, networkNS NetworkNamespace, netNsCreated bool) error { + // Set the context again. + // + // This is required since when deleting networks, the init() method is + // not called since the network config state is simply read from disk. + // However, the context part of that state is not stored fully since + // context.Context is an interface type meaning all the trace metadata + // stored in the on-disk network config file is missing. + n.ctx = sandbox.ctx + + span, _ := n.trace("remove") + defer span.Finish() + if err := removeNetworkCommon(networkNS, netNsCreated); err != nil { return err } diff --git a/virtcontainers/container.go b/virtcontainers/container.go index ffa8aab65..e14d78d37 100644 --- a/virtcontainers/container.go +++ b/virtcontainers/container.go @@ -7,6 +7,7 @@ package virtcontainers import ( + "context" "encoding/hex" "fmt" "io" @@ -17,6 +18,7 @@ import ( "github.com/kata-containers/runtime/virtcontainers/pkg/annotations" specs "github.com/opencontainers/runtime-spec/specs-go" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" @@ -261,6 +263,8 @@ type Container struct { devices []ContainerDevice systemMountsInfo SystemMountsInfo + + ctx context.Context } // ID returns the container identifier string. @@ -276,6 +280,19 @@ func (c *Container) Logger() *logrus.Entry { }) } +func (c *Container) trace(name string) (opentracing.Span, context.Context) { + if c.ctx == nil { + c.Logger().WithField("type", "bug").Error("trace called before context set") + c.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(c.ctx, name) + + span.SetTag("subsystem", "container") + + return span, ctx +} + // Sandbox returns the sandbox handler related to this container. func (c *Container) Sandbox() VCSandbox { return c.sandbox @@ -468,7 +485,7 @@ func (c *Container) mountSharedDirMounts(hostSharedDir, guestSharedDir string) ( filename := fmt.Sprintf("%s-%s-%s", c.id, hex.EncodeToString(randBytes), filepath.Base(m.Destination)) mountDest := filepath.Join(hostSharedDir, c.sandbox.id, filename) - if err := bindMount(m.Source, mountDest, false); err != nil { + if err := bindMount(c.ctx, m.Source, mountDest, false); err != nil { return nil, err } @@ -503,8 +520,15 @@ func (c *Container) mountSharedDirMounts(hostSharedDir, guestSharedDir string) ( } func (c *Container) unmountHostMounts() error { + var span opentracing.Span + span, c.ctx = c.trace("unmountHostMounts") + defer span.Finish() + for _, m := range c.mounts { if m.HostPath != "" { + span, _ := c.trace("unmount") + span.SetTag("host-path", m.HostPath) + logger := c.Logger().WithField("host-path", m.HostPath) if err := syscall.Unmount(m.HostPath, 0); err != nil { // Unable to unmount paths could be a really big problem here @@ -520,6 +544,8 @@ func (c *Container) unmountHostMounts() error { logger.WithError(err).Warn("Could not be removed") return err } + + span.Finish() } } @@ -528,6 +554,9 @@ func (c *Container) unmountHostMounts() error { // newContainer creates a Container structure from a sandbox and a container configuration. func newContainer(sandbox *Sandbox, contConfig ContainerConfig) (*Container, error) { + span, _ := sandbox.trace("newContainer") + defer span.Finish() + if contConfig.valid() == false { return &Container{}, fmt.Errorf("Invalid container configuration") } @@ -544,6 +573,7 @@ func newContainer(sandbox *Sandbox, contConfig ContainerConfig) (*Container, err state: State{}, process: Process{}, mounts: contConfig.Mounts, + ctx: sandbox.ctx, } state, err := c.sandbox.storage.fetchContainerState(c.sandboxID, c.id) @@ -790,6 +820,9 @@ func (c *Container) start() error { } func (c *Container) stop() error { + span, _ := c.trace("stop") + defer span.Finish() + // In case the container status has been updated implicitly because // the container process has terminated, it might be possible that // someone try to stop the container, and we don't want to issue an @@ -811,6 +844,9 @@ func (c *Container) stop() error { } defer func() { + span, _ := c.trace("stopShim") + defer span.Finish() + // If shim is still running something went wrong // Make sure we stop the shim process if running, _ := isShimRunning(c.process.Pid); running { diff --git a/virtcontainers/example_pod_run_test.go b/virtcontainers/example_pod_run_test.go index 55e32e03e..b1a76e309 100644 --- a/virtcontainers/example_pod_run_test.go +++ b/virtcontainers/example_pod_run_test.go @@ -6,6 +6,7 @@ package virtcontainers_test import ( + "context" "fmt" "strings" @@ -68,7 +69,7 @@ func Example_createAndStartSandbox() { Containers: []vc.ContainerConfig{container}, } - _, err := vc.RunSandbox(sandboxConfig, nil) + _, err := vc.RunSandbox(context.Background(), sandboxConfig, nil) if err != nil { fmt.Printf("Could not run sandbox: %s", err) } diff --git a/virtcontainers/factory.go b/virtcontainers/factory.go index ad4f22311..45306a5f0 100644 --- a/virtcontainers/factory.go +++ b/virtcontainers/factory.go @@ -5,11 +5,13 @@ package virtcontainers +import "context" + // Factory controls how a new VM is created. type Factory interface { // GetVM gets a new VM from the factory. - GetVM(config VMConfig) (*VM, error) + GetVM(ctx context.Context, config VMConfig) (*VM, error) // CloseFactory closes and cleans up the factory. - CloseFactory() + CloseFactory(ctx context.Context) } diff --git a/virtcontainers/factory/base/base.go b/virtcontainers/factory/base/base.go index 449bdddf6..98f5b2767 100644 --- a/virtcontainers/factory/base/base.go +++ b/virtcontainers/factory/base/base.go @@ -5,7 +5,11 @@ package base -import vc "github.com/kata-containers/runtime/virtcontainers" +import ( + "context" + + vc "github.com/kata-containers/runtime/virtcontainers" +) // FactoryBase is vm factory's internal base factory interfaces. // The difference between FactoryBase and Factory is that the Factory @@ -17,8 +21,8 @@ type FactoryBase interface { Config() vc.VMConfig // GetBaseVM returns a paused VM created by the base factory. - GetBaseVM() (*vc.VM, error) + GetBaseVM(ctx context.Context) (*vc.VM, error) // CloseFactory closes the base factory. - CloseFactory() + CloseFactory(ctx context.Context) } diff --git a/virtcontainers/factory/cache/cache.go b/virtcontainers/factory/cache/cache.go index f008617d6..edc130223 100644 --- a/virtcontainers/factory/cache/cache.go +++ b/virtcontainers/factory/cache/cache.go @@ -7,6 +7,7 @@ package cache import ( + "context" "fmt" "sync" @@ -24,7 +25,7 @@ type cache struct { } // New creates a new cached vm factory. -func New(count uint, b base.FactoryBase) base.FactoryBase { +func New(ctx context.Context, count uint, b base.FactoryBase) base.FactoryBase { if count < 1 { return b } @@ -36,10 +37,10 @@ func New(count uint, b base.FactoryBase) base.FactoryBase { c.wg.Add(1) go func() { for { - vm, err := b.GetBaseVM() + vm, err := b.GetBaseVM(ctx) if err != nil { c.wg.Done() - c.CloseFactory() + c.CloseFactory(ctx) return } @@ -62,7 +63,7 @@ func (c *cache) Config() vc.VMConfig { } // GetBaseVM returns a base VM from cache factory's base factory. -func (c *cache) GetBaseVM() (*vc.VM, error) { +func (c *cache) GetBaseVM(ctx context.Context) (*vc.VM, error) { vm, ok := <-c.cacheCh if ok { return vm, nil @@ -71,13 +72,13 @@ func (c *cache) GetBaseVM() (*vc.VM, error) { } // CloseFactory closes the cache factory. -func (c *cache) CloseFactory() { +func (c *cache) CloseFactory(ctx context.Context) { c.closeOnce.Do(func() { for len(c.closed) < cap(c.closed) { // send sufficient closed signal c.closed <- 0 } c.wg.Wait() close(c.cacheCh) - c.base.CloseFactory() + c.base.CloseFactory(ctx) }) } diff --git a/virtcontainers/factory/cache/cache_test.go b/virtcontainers/factory/cache/cache_test.go index 3ff1b32f6..800d3eb1b 100644 --- a/virtcontainers/factory/cache/cache_test.go +++ b/virtcontainers/factory/cache/cache_test.go @@ -6,6 +6,7 @@ package cache import ( + "context" "io/ioutil" "testing" @@ -29,16 +30,18 @@ func TestTemplateFactory(t *testing.T) { HypervisorConfig: hyperConfig, } + ctx := context.Background() + // New - f := New(2, direct.New(vmConfig)) + f := New(ctx, 2, direct.New(ctx, vmConfig)) // Config assert.Equal(f.Config(), vmConfig) // GetBaseVM - _, err := f.GetBaseVM() + _, err := f.GetBaseVM(ctx) assert.Nil(err) // CloseFactory - f.CloseFactory() + f.CloseFactory(ctx) } diff --git a/virtcontainers/factory/direct/direct.go b/virtcontainers/factory/direct/direct.go index db1f6c854..1cc59f52e 100644 --- a/virtcontainers/factory/direct/direct.go +++ b/virtcontainers/factory/direct/direct.go @@ -7,6 +7,8 @@ package direct import ( + "context" + vc "github.com/kata-containers/runtime/virtcontainers" "github.com/kata-containers/runtime/virtcontainers/factory/base" ) @@ -16,7 +18,7 @@ type direct struct { } // New returns a new direct vm factory. -func New(config vc.VMConfig) base.FactoryBase { +func New(ctx context.Context, config vc.VMConfig) base.FactoryBase { return &direct{config} } @@ -26,8 +28,8 @@ func (d *direct) Config() vc.VMConfig { } // GetBaseVM create a new VM directly. -func (d *direct) GetBaseVM() (*vc.VM, error) { - vm, err := vc.NewVM(d.config) +func (d *direct) GetBaseVM(ctx context.Context) (*vc.VM, error) { + vm, err := vc.NewVM(ctx, d.config) if err != nil { return nil, err } @@ -42,5 +44,5 @@ func (d *direct) GetBaseVM() (*vc.VM, error) { } // CloseFactory closes the direct vm factory. -func (d *direct) CloseFactory() { +func (d *direct) CloseFactory(ctx context.Context) { } diff --git a/virtcontainers/factory/direct/direct_test.go b/virtcontainers/factory/direct/direct_test.go index f12664c88..58be358a0 100644 --- a/virtcontainers/factory/direct/direct_test.go +++ b/virtcontainers/factory/direct/direct_test.go @@ -6,6 +6,7 @@ package direct import ( + "context" "io/ioutil" "testing" @@ -28,16 +29,18 @@ func TestTemplateFactory(t *testing.T) { HypervisorConfig: hyperConfig, } + ctx := context.Background() + // New - f := New(vmConfig) + f := New(ctx, vmConfig) // Config assert.Equal(f.Config(), vmConfig) // GetBaseVM - _, err := f.GetBaseVM() + _, err := f.GetBaseVM(ctx) assert.Nil(err) // CloseFactory - f.CloseFactory() + f.CloseFactory(ctx) } diff --git a/virtcontainers/factory/factory.go b/virtcontainers/factory/factory.go index e1c125c9d..7ad69c5f7 100644 --- a/virtcontainers/factory/factory.go +++ b/virtcontainers/factory/factory.go @@ -6,6 +6,7 @@ package factory import ( + "context" "fmt" "reflect" @@ -14,6 +15,7 @@ import ( "github.com/kata-containers/runtime/virtcontainers/factory/cache" "github.com/kata-containers/runtime/virtcontainers/factory/direct" "github.com/kata-containers/runtime/virtcontainers/factory/template" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" ) @@ -35,8 +37,19 @@ type factory struct { base base.FactoryBase } +func trace(parent context.Context, name string) (opentracing.Span, context.Context) { + span, ctx := opentracing.StartSpanFromContext(parent, name) + + span.SetTag("subsystem", "factory") + + return span, ctx +} + // NewFactory returns a working factory. -func NewFactory(config Config, fetchOnly bool) (vc.Factory, error) { +func NewFactory(ctx context.Context, config Config, fetchOnly bool) (vc.Factory, error) { + span, _ := trace(ctx, "NewFactory") + defer span.Finish() + err := config.validate() if err != nil { return nil, err @@ -54,21 +67,21 @@ func NewFactory(config Config, fetchOnly bool) (vc.Factory, error) { return nil, err } } else { - b = template.New(config.VMConfig) + b = template.New(ctx, config.VMConfig) } } else { - b = direct.New(config.VMConfig) + b = direct.New(ctx, config.VMConfig) } if config.Cache > 0 { - b = cache.New(config.Cache, b) + b = cache.New(ctx, config.Cache, b) } return &factory{b}, nil } // SetLogger sets the logger for the factory. -func SetLogger(logger logrus.FieldLogger) { +func SetLogger(ctx context.Context, logger logrus.FieldLogger) { fields := logrus.Fields{ "source": "virtcontainers", } @@ -117,7 +130,10 @@ func (f *factory) checkConfig(config vc.VMConfig) error { } // GetVM returns a working blank VM created by the factory. -func (f *factory) GetVM(config vc.VMConfig) (*vc.VM, error) { +func (f *factory) GetVM(ctx context.Context, config vc.VMConfig) (*vc.VM, error) { + span, _ := trace(ctx, "GetVM") + defer span.Finish() + hypervisorConfig := config.HypervisorConfig err := config.Valid() if err != nil { @@ -128,11 +144,11 @@ func (f *factory) GetVM(config vc.VMConfig) (*vc.VM, error) { err = f.checkConfig(config) if err != nil { f.log().WithError(err).Info("fallback to direct factory vm") - return direct.New(config).GetBaseVM() + return direct.New(ctx, config).GetBaseVM(ctx) } f.log().Info("get base VM") - vm, err := f.base.GetBaseVM() + vm, err := f.base.GetBaseVM(ctx) if err != nil { f.log().WithError(err).Error("failed to get base VM") return nil, err @@ -186,6 +202,6 @@ func (f *factory) GetVM(config vc.VMConfig) (*vc.VM, error) { } // CloseFactory closes the factory. -func (f *factory) CloseFactory() { - f.base.CloseFactory() +func (f *factory) CloseFactory(ctx context.Context) { + f.base.CloseFactory(ctx) } diff --git a/virtcontainers/factory/factory_test.go b/virtcontainers/factory/factory_test.go index 239bd608c..12a45a62a 100644 --- a/virtcontainers/factory/factory_test.go +++ b/virtcontainers/factory/factory_test.go @@ -6,6 +6,7 @@ package factory import ( + "context" "io/ioutil" "testing" @@ -20,9 +21,10 @@ func TestNewFactory(t *testing.T) { assert := assert.New(t) - _, err := NewFactory(config, true) + ctx := context.Background() + _, err := NewFactory(ctx, config, true) assert.Error(err) - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Error(err) config.VMConfig = vc.VMConfig{ @@ -30,7 +32,7 @@ func TestNewFactory(t *testing.T) { AgentType: vc.NoopAgentType, } - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Error(err) testDir, _ := ioutil.TempDir("", "vmfactory-tmp-") @@ -41,29 +43,29 @@ func TestNewFactory(t *testing.T) { } // direct - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Nil(err) - _, err = NewFactory(config, true) + _, err = NewFactory(ctx, config, true) assert.Nil(err) // template config.Template = true - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Nil(err) - _, err = NewFactory(config, true) + _, err = NewFactory(ctx, config, true) assert.Error(err) // Cache config.Cache = 10 - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Nil(err) - _, err = NewFactory(config, true) + _, err = NewFactory(ctx, config, true) assert.Error(err) config.Template = false - _, err = NewFactory(config, false) + _, err = NewFactory(ctx, config, false) assert.Nil(err) - _, err = NewFactory(config, true) + _, err = NewFactory(ctx, config, true) assert.Error(err) } @@ -72,14 +74,15 @@ func TestFactorySetLogger(t *testing.T) { testLog := logrus.WithFields(logrus.Fields{"testfield": "foobar"}) testLog.Level = logrus.DebugLevel - SetLogger(testLog) + SetLogger(context.Background(), testLog) var config Config config.VMConfig.HypervisorConfig = vc.HypervisorConfig{ KernelPath: "foo", ImagePath: "bar", } - vf, err := NewFactory(config, false) + ctx := context.Background() + vf, err := NewFactory(ctx, config, false) assert.Nil(err) f, ok := vf.(*factory) @@ -166,66 +169,68 @@ func TestFactoryGetVM(t *testing.T) { HypervisorConfig: hyperConfig, } + ctx := context.Background() + // direct factory - f, err := NewFactory(Config{VMConfig: vmConfig}, false) + f, err := NewFactory(ctx, Config{VMConfig: vmConfig}, false) assert.Nil(err) - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) - f.CloseFactory() + f.CloseFactory(ctx) // template factory - f, err = NewFactory(Config{Template: true, VMConfig: vmConfig}, false) + f, err = NewFactory(ctx, Config{Template: true, VMConfig: vmConfig}, false) assert.Nil(err) - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) - f.CloseFactory() + f.CloseFactory(ctx) // fetch template factory - f, err = NewFactory(Config{Template: true, VMConfig: vmConfig}, false) + f, err = NewFactory(ctx, Config{Template: true, VMConfig: vmConfig}, false) assert.Nil(err) - _, err = NewFactory(Config{Template: true, VMConfig: vmConfig}, true) + _, err = NewFactory(ctx, Config{Template: true, VMConfig: vmConfig}, true) assert.Error(err) - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) - f.CloseFactory() + f.CloseFactory(ctx) // cache factory over direct factory - f, err = NewFactory(Config{Cache: 2, VMConfig: vmConfig}, false) + f, err = NewFactory(ctx, Config{Cache: 2, VMConfig: vmConfig}, false) assert.Nil(err) - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) - f.CloseFactory() + f.CloseFactory(ctx) // cache factory over template factory - f, err = NewFactory(Config{Template: true, Cache: 2, VMConfig: vmConfig}, false) + f, err = NewFactory(ctx, Config{Template: true, Cache: 2, VMConfig: vmConfig}, false) assert.Nil(err) - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) // CPU hotplug vmConfig.HypervisorConfig.DefaultVCPUs++ - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) // Memory hotplug vmConfig.HypervisorConfig.DefaultMemSz += 128 - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) // checkConfig fall back vmConfig.HypervisorConfig.Mlock = true - _, err = f.GetVM(vmConfig) + _, err = f.GetVM(ctx, vmConfig) assert.Nil(err) - f.CloseFactory() + f.CloseFactory(ctx) } diff --git a/virtcontainers/factory/template/template.go b/virtcontainers/factory/template/template.go index 55dddc67c..1203780d0 100644 --- a/virtcontainers/factory/template/template.go +++ b/virtcontainers/factory/template/template.go @@ -7,6 +7,7 @@ package template import ( + "context" "fmt" "os" "syscall" @@ -37,20 +38,20 @@ func Fetch(config vc.VMConfig) (base.FactoryBase, error) { } // New creates a new VM template factory. -func New(config vc.VMConfig) base.FactoryBase { +func New(ctx context.Context, config vc.VMConfig) base.FactoryBase { statePath := vc.RunVMStoragePath + "/template" t := &template{statePath, config} err := t.prepareTemplateFiles() if err != nil { // fallback to direct factory if template is not supported. - return direct.New(config) + return direct.New(ctx, config) } - err = t.createTemplateVM() + err = t.createTemplateVM(ctx) if err != nil { // fallback to direct factory if template is not supported. - return direct.New(config) + return direct.New(ctx, config) } return t @@ -62,12 +63,12 @@ func (t *template) Config() vc.VMConfig { } // GetBaseVM creates a new paused VM from the template VM. -func (t *template) GetBaseVM() (*vc.VM, error) { - return t.createFromTemplateVM() +func (t *template) GetBaseVM(ctx context.Context) (*vc.VM, error) { + return t.createFromTemplateVM(ctx) } // CloseFactory cleans up the template VM. -func (t *template) CloseFactory() { +func (t *template) CloseFactory(ctx context.Context) { syscall.Unmount(t.statePath, 0) os.RemoveAll(t.statePath) } @@ -92,7 +93,7 @@ func (t *template) prepareTemplateFiles() error { return nil } -func (t *template) createTemplateVM() error { +func (t *template) createTemplateVM(ctx context.Context) error { // create the template vm config := t.config config.HypervisorConfig.BootToBeTemplate = true @@ -100,7 +101,7 @@ func (t *template) createTemplateVM() error { config.HypervisorConfig.MemoryPath = t.statePath + "/memory" config.HypervisorConfig.DevicesStatePath = t.statePath + "/state" - vm, err := vc.NewVM(config) + vm, err := vc.NewVM(ctx, config) if err != nil { return err } @@ -122,14 +123,14 @@ func (t *template) createTemplateVM() error { return nil } -func (t *template) createFromTemplateVM() (*vc.VM, error) { +func (t *template) createFromTemplateVM(ctx context.Context) (*vc.VM, error) { config := t.config config.HypervisorConfig.BootToBeTemplate = false config.HypervisorConfig.BootFromTemplate = true config.HypervisorConfig.MemoryPath = t.statePath + "/memory" config.HypervisorConfig.DevicesStatePath = t.statePath + "/state" - return vc.NewVM(config) + return vc.NewVM(ctx, config) } func (t *template) checkTemplateVM() error { diff --git a/virtcontainers/factory/template/template_test.go b/virtcontainers/factory/template/template_test.go index a8b7c7ba7..21e23a48b 100644 --- a/virtcontainers/factory/template/template_test.go +++ b/virtcontainers/factory/template/template_test.go @@ -6,6 +6,7 @@ package template import ( + "context" "io/ioutil" "os" "testing" @@ -29,14 +30,16 @@ func TestTemplateFactory(t *testing.T) { HypervisorConfig: hyperConfig, } + ctx := context.Background() + // New - f := New(vmConfig) + f := New(ctx, vmConfig) // Config assert.Equal(f.Config(), vmConfig) // GetBaseVM - _, err := f.GetBaseVM() + _, err := f.GetBaseVM(ctx) assert.Nil(err) // Fetch @@ -58,13 +61,13 @@ func TestTemplateFactory(t *testing.T) { err = tt.checkTemplateVM() assert.Nil(err) - err = tt.createTemplateVM() + err = tt.createTemplateVM(ctx) assert.Nil(err) - _, err = tt.GetBaseVM() + _, err = tt.GetBaseVM(ctx) assert.Nil(err) // CloseFactory - f.CloseFactory() - tt.CloseFactory() + f.CloseFactory(ctx) + tt.CloseFactory(ctx) } diff --git a/virtcontainers/filesystem.go b/virtcontainers/filesystem.go index 139cbff1b..0723a39bb 100644 --- a/virtcontainers/filesystem.go +++ b/virtcontainers/filesystem.go @@ -6,12 +6,14 @@ package virtcontainers import ( + "context" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/kata-containers/runtime/virtcontainers/device/api" @@ -115,7 +117,7 @@ var RunVMStoragePath = filepath.Join("/run", storagePathSuffix, vmPathSuffix) // The default resource storage implementation is filesystem. type resourceStorage interface { // Create all resources for a sandbox - createAllResources(sandbox *Sandbox) error + createAllResources(ctx context.Context, sandbox *Sandbox) error // Resources URIs functions return both the URI // for the actual resource and the URI base. @@ -155,14 +157,37 @@ type resourceStorage interface { // filesystem is a resourceStorage interface implementation for a local filesystem. type filesystem struct { + ctx context.Context } // Logger returns a logrus logger appropriate for logging filesystem messages func (fs *filesystem) Logger() *logrus.Entry { - return virtLog.WithField("subsystem", "filesystem") + return virtLog.WithFields(logrus.Fields{ + "subsystem": "storage", + "type": "filesystem", + }) } -func (fs *filesystem) createAllResources(sandbox *Sandbox) (err error) { +func (fs *filesystem) trace(name string) (opentracing.Span, context.Context) { + if fs.ctx == nil { + fs.Logger().WithField("type", "bug").Error("trace called before context set") + fs.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(fs.ctx, name) + + span.SetTag("subsystem", "storage") + span.SetTag("type", "filesystem") + + return span, ctx +} + +func (fs *filesystem) createAllResources(ctx context.Context, sandbox *Sandbox) (err error) { + fs.ctx = ctx + + span, _ := fs.trace("createAllResources") + defer span.Finish() + for _, resource := range []sandboxResource{stateFileType, configFileType} { _, path, _ := fs.sandboxURI(sandbox.id, resource) err = os.MkdirAll(path, dirMode) @@ -389,6 +414,33 @@ func resourceNeedsContainerID(sandboxSpecific bool, resource sandboxResource) bo } } +func resourceName(resource sandboxResource) string { + switch resource { + case agentFileType: + return "agentFileType" + case configFileType: + return "configFileType" + case devicesFileType: + return "devicesFileType" + case devicesIDFileType: + return "devicesIDFileType" + case hypervisorFileType: + return "hypervisorFileType" + case lockFileType: + return "lockFileType" + case mountsFileType: + return "mountsFileType" + case networkFileType: + return "networkFileType" + case processFileType: + return "processFileType" + case stateFileType: + return "stateFileType" + default: + return "" + } +} + func resourceDir(sandboxSpecific bool, sandboxID, containerID string, resource sandboxResource) (string, error) { if sandboxID == "" { return "", errNeedSandboxID @@ -635,6 +687,17 @@ func (fs *filesystem) storeResource(sandboxSpecific bool, sandboxID, containerID } func (fs *filesystem) fetchResource(sandboxSpecific bool, sandboxID, containerID string, resource sandboxResource, data interface{}) error { + var span opentracing.Span + + if fs.ctx != nil { + span, _ = fs.trace("fetchResource") + defer span.Finish() + + span.SetTag("sandbox", sandboxID) + span.SetTag("container", containerID) + span.SetTag("resource", resourceName(resource)) + } + if err := fs.commonResourceChecks(sandboxSpecific, sandboxID, containerID, resource); err != nil { return err } @@ -715,6 +778,9 @@ func (fs *filesystem) storeHypervisorState(sandboxID string, state interface{}) } func (fs *filesystem) storeAgentState(sandboxID string, state interface{}) error { + span, _ := fs.trace("storeAgentState") + defer span.Finish() + agentFile, _, err := fs.resourceURI(true, sandboxID, "", agentFileType) if err != nil { return err diff --git a/virtcontainers/filesystem_test.go b/virtcontainers/filesystem_test.go index 43ba93947..e6ca121a3 100644 --- a/virtcontainers/filesystem_test.go +++ b/virtcontainers/filesystem_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "io/ioutil" "os" @@ -55,7 +56,7 @@ func TestFilesystemCreateAllResourcesSuccessful(t *testing.T) { os.RemoveAll(runPath) } - err := fs.createAllResources(sandbox) + err := fs.createAllResources(context.Background(), sandbox) if err != nil { t.Fatal(err) } @@ -102,7 +103,7 @@ func TestFilesystemCreateAllResourcesFailingSandboxIDEmpty(t *testing.T) { sandbox := &Sandbox{} - err := fs.createAllResources(sandbox) + err := fs.createAllResources(context.Background(), sandbox) if err == nil { t.Fatal() } @@ -120,7 +121,7 @@ func TestFilesystemCreateAllResourcesFailingContainerIDEmpty(t *testing.T) { containers: containers, } - err := fs.createAllResources(sandbox) + err := fs.createAllResources(context.Background(), sandbox) if err == nil { t.Fatal() } diff --git a/virtcontainers/hack/virtc/main.go b/virtcontainers/hack/virtc/main.go index 20a182b31..d4d9421c1 100644 --- a/virtcontainers/hack/virtc/main.go +++ b/virtcontainers/hack/virtc/main.go @@ -6,6 +6,7 @@ package main import ( + "context" "errors" "fmt" "os" @@ -24,6 +25,8 @@ var virtcLog *logrus.Entry var listFormat = "%s\t%s\t%s\t%s\n" var statusFormat = "%s\t%s\n" +var ctx = context.Background() + var ( errNeedContainerID = errors.New("Container ID cannot be empty") errNeedSandboxID = errors.New("Sandbox ID cannot be empty") @@ -322,7 +325,7 @@ func runSandbox(context *cli.Context) error { return fmt.Errorf("Could not build sandbox config: %s", err) } - _, err = vc.RunSandbox(sandboxConfig, nil) + _, err = vc.RunSandbox(ctx, sandboxConfig, nil) if err != nil { return fmt.Errorf("Could not run sandbox: %s", err) } @@ -336,7 +339,7 @@ func createSandbox(context *cli.Context) error { return fmt.Errorf("Could not build sandbox config: %s", err) } - p, err := vc.CreateSandbox(sandboxConfig, nil) + p, err := vc.CreateSandbox(ctx, sandboxConfig, nil) if err != nil { return fmt.Errorf("Could not create sandbox: %s", err) } @@ -363,7 +366,7 @@ func checkContainerArgs(context *cli.Context, f func(context *cli.Context) error } func deleteSandbox(context *cli.Context) error { - p, err := vc.DeleteSandbox(context.String("id")) + p, err := vc.DeleteSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not delete sandbox: %s", err) } @@ -374,7 +377,7 @@ func deleteSandbox(context *cli.Context) error { } func startSandbox(context *cli.Context) error { - p, err := vc.StartSandbox(context.String("id")) + p, err := vc.StartSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not start sandbox: %s", err) } @@ -385,7 +388,7 @@ func startSandbox(context *cli.Context) error { } func stopSandbox(context *cli.Context) error { - p, err := vc.StopSandbox(context.String("id")) + p, err := vc.StopSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not stop sandbox: %s", err) } @@ -396,7 +399,7 @@ func stopSandbox(context *cli.Context) error { } func pauseSandbox(context *cli.Context) error { - p, err := vc.PauseSandbox(context.String("id")) + p, err := vc.PauseSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not pause sandbox: %s", err) } @@ -407,7 +410,7 @@ func pauseSandbox(context *cli.Context) error { } func resumeSandbox(context *cli.Context) error { - p, err := vc.ResumeSandbox(context.String("id")) + p, err := vc.ResumeSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not resume sandbox: %s", err) } @@ -418,7 +421,7 @@ func resumeSandbox(context *cli.Context) error { } func listSandboxes(context *cli.Context) error { - sandboxStatusList, err := vc.ListSandbox() + sandboxStatusList, err := vc.ListSandbox(ctx) if err != nil { return fmt.Errorf("Could not list sandbox: %s", err) } @@ -437,7 +440,7 @@ func listSandboxes(context *cli.Context) error { } func statusSandbox(context *cli.Context) error { - sandboxStatus, err := vc.StatusSandbox(context.String("id")) + sandboxStatus, err := vc.StatusSandbox(ctx, context.String("id")) if err != nil { return fmt.Errorf("Could not get sandbox status: %s", err) } @@ -610,7 +613,7 @@ func createContainer(context *cli.Context) error { Cmd: cmd, } - _, c, err := vc.CreateContainer(context.String("sandbox-id"), containerConfig) + _, c, err := vc.CreateContainer(ctx, context.String("sandbox-id"), containerConfig) if err != nil { return fmt.Errorf("Could not create container: %s", err) } @@ -621,7 +624,7 @@ func createContainer(context *cli.Context) error { } func deleteContainer(context *cli.Context) error { - c, err := vc.DeleteContainer(context.String("sandbox-id"), context.String("id")) + c, err := vc.DeleteContainer(ctx, context.String("sandbox-id"), context.String("id")) if err != nil { return fmt.Errorf("Could not delete container: %s", err) } @@ -632,7 +635,7 @@ func deleteContainer(context *cli.Context) error { } func startContainer(context *cli.Context) error { - c, err := vc.StartContainer(context.String("sandbox-id"), context.String("id")) + c, err := vc.StartContainer(ctx, context.String("sandbox-id"), context.String("id")) if err != nil { return fmt.Errorf("Could not start container: %s", err) } @@ -643,7 +646,7 @@ func startContainer(context *cli.Context) error { } func stopContainer(context *cli.Context) error { - c, err := vc.StopContainer(context.String("sandbox-id"), context.String("id")) + c, err := vc.StopContainer(ctx, context.String("sandbox-id"), context.String("id")) if err != nil { return fmt.Errorf("Could not stop container: %s", err) } @@ -676,7 +679,7 @@ func enterContainer(context *cli.Context) error { Console: console, } - _, c, _, err := vc.EnterContainer(context.String("sandbox-id"), context.String("id"), cmd) + _, c, _, err := vc.EnterContainer(ctx, context.String("sandbox-id"), context.String("id"), cmd) if err != nil { return fmt.Errorf("Could not enter container: %s", err) } @@ -687,7 +690,7 @@ func enterContainer(context *cli.Context) error { } func statusContainer(context *cli.Context) error { - contStatus, err := vc.StatusContainer(context.String("sandbox-id"), context.String("id")) + contStatus, err := vc.StatusContainer(ctx, context.String("sandbox-id"), context.String("id")) if err != nil { return fmt.Errorf("Could not get container status: %s", err) } @@ -926,7 +929,7 @@ func main() { } // Set virtcontainers logger. - vc.SetLogger(virtcLog) + vc.SetLogger(ctx, virtcLog) return nil } diff --git a/virtcontainers/hook.go b/virtcontainers/hook.go index d5f3025df..fb751fd85 100644 --- a/virtcontainers/hook.go +++ b/virtcontainers/hook.go @@ -7,15 +7,19 @@ package virtcontainers import ( "bytes" + "context" "encoding/json" "fmt" "os" "os/exec" + "strings" "syscall" "time" vcAnnotations "github.com/kata-containers/runtime/virtcontainers/pkg/annotations" specs "github.com/opencontainers/runtime-spec/specs-go" + opentracing "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go/log" "github.com/sirupsen/logrus" ) @@ -48,7 +52,22 @@ func buildHookState(processID int, s *Sandbox) specs.State { } } +func (h *Hook) trace(ctx context.Context, name string) (opentracing.Span, context.Context) { + return traceWithSubsys(ctx, "hook", name) +} + +func (h *Hooks) trace(ctx context.Context, name string) (opentracing.Span, context.Context) { + return traceWithSubsys(ctx, "hooks", name) +} + func (h *Hook) runHook(s *Sandbox) error { + span, _ := h.trace(s.ctx, "runHook") + defer span.Finish() + + span.LogFields( + log.String("hook-name", h.Path), + log.String("hook-args", strings.Join(h.Args, " "))) + state := buildHookState(os.Getpid(), s) stateJSON, err := json.Marshal(state) if err != nil { @@ -100,6 +119,9 @@ func (h *Hook) runHook(s *Sandbox) error { } func (h *Hooks) preStartHooks(s *Sandbox) error { + span, _ := h.trace(s.ctx, "preStartHooks") + defer span.Finish() + if len(h.PreStartHooks) == 0 { return nil } @@ -120,6 +142,9 @@ func (h *Hooks) preStartHooks(s *Sandbox) error { } func (h *Hooks) postStartHooks(s *Sandbox) error { + span, _ := h.trace(s.ctx, "postStartHooks") + defer span.Finish() + if len(h.PostStartHooks) == 0 { return nil } @@ -140,6 +165,9 @@ func (h *Hooks) postStartHooks(s *Sandbox) error { } func (h *Hooks) postStopHooks(s *Sandbox) error { + span, _ := h.trace(s.ctx, "postStopHooks") + defer span.Finish() + if len(h.PostStopHooks) == 0 { return nil } diff --git a/virtcontainers/hook_test.go b/virtcontainers/hook_test.go index a8c335870..cdf41339c 100644 --- a/virtcontainers/hook_test.go +++ b/virtcontainers/hook_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "io/ioutil" "os" "path/filepath" @@ -90,6 +91,7 @@ func createTestSandbox() *Sandbox { annotationsLock: &sync.RWMutex{}, config: c, id: testSandboxID, + ctx: context.Background(), } } diff --git a/virtcontainers/hyperstart_agent.go b/virtcontainers/hyperstart_agent.go index 5c1181887..a355540d7 100644 --- a/virtcontainers/hyperstart_agent.go +++ b/virtcontainers/hyperstart_agent.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "net" "net/url" @@ -82,6 +83,8 @@ type hyper struct { state HyperAgentState sockets []Socket + + ctx context.Context } type hyperstartProxyCmd struct { @@ -258,7 +261,10 @@ func fsMapFromDevices(c *Container) ([]*hyperstart.FsmapDescriptor, error) { } // init is the agent initialization implementation for hyperstart. -func (h *hyper) init(sandbox *Sandbox, config interface{}) (err error) { +func (h *hyper) init(ctx context.Context, sandbox *Sandbox, config interface{}) (err error) { + // save + h.ctx = ctx + switch c := config.(type) { case HyperConfig: // Create agent sockets from paths provided through @@ -503,8 +509,8 @@ func (h *hyper) startOneContainer(sandbox *Sandbox, c *Container) error { container.Fstype = c.state.Fstype } else { - if err := bindMountContainerRootfs(defaultSharedDir, sandbox.id, c.id, c.rootFs, false); err != nil { - bindUnmountAllRootfs(defaultSharedDir, sandbox) + if err := bindMountContainerRootfs(c.ctx, defaultSharedDir, sandbox.id, c.id, c.rootFs, false); err != nil { + bindUnmountAllRootfs(c.ctx, defaultSharedDir, sandbox) return err } } @@ -514,7 +520,7 @@ func (h *hyper) startOneContainer(sandbox *Sandbox, c *Container) error { // Handle container mounts newMounts, err := c.mountSharedDirMounts(defaultSharedDir, "") if err != nil { - bindUnmountAllRootfs(defaultSharedDir, sandbox) + bindUnmountAllRootfs(c.ctx, defaultSharedDir, sandbox) return err } @@ -599,7 +605,7 @@ func (h *hyper) stopOneContainer(sandboxID string, c Container) error { } if c.state.Fstype == "" { - if err := bindUnmountContainerRootfs(defaultSharedDir, sandboxID, c.id); err != nil { + if err := bindUnmountContainerRootfs(c.ctx, defaultSharedDir, sandboxID, c.id); err != nil { return err } } diff --git a/virtcontainers/hypervisor.go b/virtcontainers/hypervisor.go index e0de00c1a..1ace568ab 100644 --- a/virtcontainers/hypervisor.go +++ b/virtcontainers/hypervisor.go @@ -7,6 +7,7 @@ package virtcontainers import ( "bufio" + "context" "fmt" "os" "runtime" @@ -545,7 +546,8 @@ func RunningOnVMM(cpuInfoPath string) (bool, error) { // hypervisor is the virtcontainers hypervisor interface. // The default hypervisor implementation is Qemu. type hypervisor interface { - init(id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error + init(ctx context.Context, id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error + createSandbox() error startSandbox() error waitSandbox(timeout int) error diff --git a/virtcontainers/implementation.go b/virtcontainers/implementation.go index 81727dd5a..98459a632 100644 --- a/virtcontainers/implementation.go +++ b/virtcontainers/implementation.go @@ -10,6 +10,7 @@ package virtcontainers import ( + "context" "syscall" "github.com/kata-containers/agent/protocols/grpc" @@ -25,152 +26,152 @@ type VCImpl struct { } // SetLogger implements the VC function of the same name. -func (impl *VCImpl) SetLogger(logger *logrus.Entry) { - SetLogger(logger) +func (impl *VCImpl) SetLogger(ctx context.Context, logger *logrus.Entry) { + SetLogger(ctx, logger) } // SetFactory implements the VC function of the same name. -func (impl *VCImpl) SetFactory(factory Factory) { +func (impl *VCImpl) SetFactory(ctx context.Context, factory Factory) { impl.factory = factory } // CreateSandbox implements the VC function of the same name. -func (impl *VCImpl) CreateSandbox(sandboxConfig SandboxConfig) (VCSandbox, error) { - return CreateSandbox(sandboxConfig, impl.factory) +func (impl *VCImpl) CreateSandbox(ctx context.Context, sandboxConfig SandboxConfig) (VCSandbox, error) { + return CreateSandbox(ctx, sandboxConfig, impl.factory) } // DeleteSandbox implements the VC function of the same name. -func (impl *VCImpl) DeleteSandbox(sandboxID string) (VCSandbox, error) { - return DeleteSandbox(sandboxID) +func (impl *VCImpl) DeleteSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return DeleteSandbox(ctx, sandboxID) } // StartSandbox implements the VC function of the same name. -func (impl *VCImpl) StartSandbox(sandboxID string) (VCSandbox, error) { - return StartSandbox(sandboxID) +func (impl *VCImpl) StartSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return StartSandbox(ctx, sandboxID) } // StopSandbox implements the VC function of the same name. -func (impl *VCImpl) StopSandbox(sandboxID string) (VCSandbox, error) { - return StopSandbox(sandboxID) +func (impl *VCImpl) StopSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return StopSandbox(ctx, sandboxID) } // RunSandbox implements the VC function of the same name. -func (impl *VCImpl) RunSandbox(sandboxConfig SandboxConfig) (VCSandbox, error) { - return RunSandbox(sandboxConfig, impl.factory) +func (impl *VCImpl) RunSandbox(ctx context.Context, sandboxConfig SandboxConfig) (VCSandbox, error) { + return RunSandbox(ctx, sandboxConfig, impl.factory) } // ListSandbox implements the VC function of the same name. -func (impl *VCImpl) ListSandbox() ([]SandboxStatus, error) { - return ListSandbox() +func (impl *VCImpl) ListSandbox(ctx context.Context) ([]SandboxStatus, error) { + return ListSandbox(ctx) } // FetchSandbox will find out and connect to an existing sandbox and // return the sandbox structure. -func (impl *VCImpl) FetchSandbox(sandboxID string) (VCSandbox, error) { - return FetchSandbox(sandboxID) +func (impl *VCImpl) FetchSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return FetchSandbox(ctx, sandboxID) } // StatusSandbox implements the VC function of the same name. -func (impl *VCImpl) StatusSandbox(sandboxID string) (SandboxStatus, error) { - return StatusSandbox(sandboxID) +func (impl *VCImpl) StatusSandbox(ctx context.Context, sandboxID string) (SandboxStatus, error) { + return StatusSandbox(ctx, sandboxID) } // PauseSandbox implements the VC function of the same name. -func (impl *VCImpl) PauseSandbox(sandboxID string) (VCSandbox, error) { - return PauseSandbox(sandboxID) +func (impl *VCImpl) PauseSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return PauseSandbox(ctx, sandboxID) } // ResumeSandbox implements the VC function of the same name. -func (impl *VCImpl) ResumeSandbox(sandboxID string) (VCSandbox, error) { - return ResumeSandbox(sandboxID) +func (impl *VCImpl) ResumeSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) { + return ResumeSandbox(ctx, sandboxID) } // CreateContainer implements the VC function of the same name. -func (impl *VCImpl) CreateContainer(sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) { - return CreateContainer(sandboxID, containerConfig) +func (impl *VCImpl) CreateContainer(ctx context.Context, sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) { + return CreateContainer(ctx, sandboxID, containerConfig) } // DeleteContainer implements the VC function of the same name. -func (impl *VCImpl) DeleteContainer(sandboxID, containerID string) (VCContainer, error) { - return DeleteContainer(sandboxID, containerID) +func (impl *VCImpl) DeleteContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { + return DeleteContainer(ctx, sandboxID, containerID) } // StartContainer implements the VC function of the same name. -func (impl *VCImpl) StartContainer(sandboxID, containerID string) (VCContainer, error) { - return StartContainer(sandboxID, containerID) +func (impl *VCImpl) StartContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { + return StartContainer(ctx, sandboxID, containerID) } // StopContainer implements the VC function of the same name. -func (impl *VCImpl) StopContainer(sandboxID, containerID string) (VCContainer, error) { - return StopContainer(sandboxID, containerID) +func (impl *VCImpl) StopContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) { + return StopContainer(ctx, sandboxID, containerID) } // EnterContainer implements the VC function of the same name. -func (impl *VCImpl) EnterContainer(sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) { - return EnterContainer(sandboxID, containerID, cmd) +func (impl *VCImpl) EnterContainer(ctx context.Context, sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) { + return EnterContainer(ctx, sandboxID, containerID, cmd) } // StatusContainer implements the VC function of the same name. -func (impl *VCImpl) StatusContainer(sandboxID, containerID string) (ContainerStatus, error) { - return StatusContainer(sandboxID, containerID) +func (impl *VCImpl) StatusContainer(ctx context.Context, sandboxID, containerID string) (ContainerStatus, error) { + return StatusContainer(ctx, sandboxID, containerID) } // StatsContainer implements the VC function of the same name. -func (impl *VCImpl) StatsContainer(sandboxID, containerID string) (ContainerStats, error) { - return StatsContainer(sandboxID, containerID) +func (impl *VCImpl) StatsContainer(ctx context.Context, sandboxID, containerID string) (ContainerStats, error) { + return StatsContainer(ctx, sandboxID, containerID) } // KillContainer implements the VC function of the same name. -func (impl *VCImpl) KillContainer(sandboxID, containerID string, signal syscall.Signal, all bool) error { - return KillContainer(sandboxID, containerID, signal, all) +func (impl *VCImpl) KillContainer(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { + return KillContainer(ctx, sandboxID, containerID, signal, all) } // ProcessListContainer implements the VC function of the same name. -func (impl *VCImpl) ProcessListContainer(sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) { - return ProcessListContainer(sandboxID, containerID, options) +func (impl *VCImpl) ProcessListContainer(ctx context.Context, sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) { + return ProcessListContainer(ctx, sandboxID, containerID, options) } // UpdateContainer implements the VC function of the same name. -func (impl *VCImpl) UpdateContainer(sandboxID, containerID string, resources specs.LinuxResources) error { - return UpdateContainer(sandboxID, containerID, resources) +func (impl *VCImpl) UpdateContainer(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error { + return UpdateContainer(ctx, sandboxID, containerID, resources) } // PauseContainer implements the VC function of the same name. -func (impl *VCImpl) PauseContainer(sandboxID, containerID string) error { - return PauseContainer(sandboxID, containerID) +func (impl *VCImpl) PauseContainer(ctx context.Context, sandboxID, containerID string) error { + return PauseContainer(ctx, sandboxID, containerID) } // ResumeContainer implements the VC function of the same name. -func (impl *VCImpl) ResumeContainer(sandboxID, containerID string) error { - return ResumeContainer(sandboxID, containerID) +func (impl *VCImpl) ResumeContainer(ctx context.Context, sandboxID, containerID string) error { + return ResumeContainer(ctx, sandboxID, containerID) } // AddDevice will add a device to sandbox -func (impl *VCImpl) AddDevice(sandboxID string, info config.DeviceInfo) (api.Device, error) { - return AddDevice(sandboxID, info) +func (impl *VCImpl) AddDevice(ctx context.Context, sandboxID string, info config.DeviceInfo) (api.Device, error) { + return AddDevice(ctx, sandboxID, info) } // AddInterface implements the VC function of the same name. -func (impl *VCImpl) AddInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { - return AddInterface(sandboxID, inf) +func (impl *VCImpl) AddInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + return AddInterface(ctx, sandboxID, inf) } // RemoveInterface implements the VC function of the same name. -func (impl *VCImpl) RemoveInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { - return RemoveInterface(sandboxID, inf) +func (impl *VCImpl) RemoveInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { + return RemoveInterface(ctx, sandboxID, inf) } // ListInterfaces implements the VC function of the same name. -func (impl *VCImpl) ListInterfaces(sandboxID string) ([]*grpc.Interface, error) { - return ListInterfaces(sandboxID) +func (impl *VCImpl) ListInterfaces(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) { + return ListInterfaces(ctx, sandboxID) } // UpdateRoutes implements the VC function of the same name. -func (impl *VCImpl) UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { - return UpdateRoutes(sandboxID, routes) +func (impl *VCImpl) UpdateRoutes(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { + return UpdateRoutes(ctx, sandboxID, routes) } // ListRoutes implements the VC function of the same name. -func (impl *VCImpl) ListRoutes(sandboxID string) ([]*grpc.Route, error) { - return ListRoutes(sandboxID) +func (impl *VCImpl) ListRoutes(ctx context.Context, sandboxID string) ([]*grpc.Route, error) { + return ListRoutes(ctx, sandboxID) } diff --git a/virtcontainers/interfaces.go b/virtcontainers/interfaces.go index e83ee3744..1d9921b06 100644 --- a/virtcontainers/interfaces.go +++ b/virtcontainers/interfaces.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "io" "syscall" @@ -18,40 +19,40 @@ import ( // VC is the Virtcontainers interface type VC interface { - SetLogger(logger *logrus.Entry) - SetFactory(Factory) + SetLogger(ctx context.Context, logger *logrus.Entry) + SetFactory(ctx context.Context, factory Factory) - CreateSandbox(sandboxConfig SandboxConfig) (VCSandbox, error) - DeleteSandbox(sandboxID string) (VCSandbox, error) - FetchSandbox(sandboxID string) (VCSandbox, error) - ListSandbox() ([]SandboxStatus, error) - PauseSandbox(sandboxID string) (VCSandbox, error) - ResumeSandbox(sandboxID string) (VCSandbox, error) - RunSandbox(sandboxConfig SandboxConfig) (VCSandbox, error) - StartSandbox(sandboxID string) (VCSandbox, error) - StatusSandbox(sandboxID string) (SandboxStatus, error) - StopSandbox(sandboxID string) (VCSandbox, error) + CreateSandbox(ctx context.Context, sandboxConfig SandboxConfig) (VCSandbox, error) + DeleteSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) + FetchSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) + ListSandbox(ctx context.Context) ([]SandboxStatus, error) + PauseSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) + ResumeSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) + RunSandbox(ctx context.Context, sandboxConfig SandboxConfig) (VCSandbox, error) + StartSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) + StatusSandbox(ctx context.Context, sandboxID string) (SandboxStatus, error) + StopSandbox(ctx context.Context, sandboxID string) (VCSandbox, error) - CreateContainer(sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) - DeleteContainer(sandboxID, containerID string) (VCContainer, error) - EnterContainer(sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) - KillContainer(sandboxID, containerID string, signal syscall.Signal, all bool) error - StartContainer(sandboxID, containerID string) (VCContainer, error) - StatusContainer(sandboxID, containerID string) (ContainerStatus, error) - StatsContainer(sandboxID, containerID string) (ContainerStats, error) - StopContainer(sandboxID, containerID string) (VCContainer, error) - ProcessListContainer(sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) - UpdateContainer(sandboxID, containerID string, resources specs.LinuxResources) error - PauseContainer(sandboxID, containerID string) error - ResumeContainer(sandboxID, containerID string) error + CreateContainer(ctx context.Context, sandboxID string, containerConfig ContainerConfig) (VCSandbox, VCContainer, error) + DeleteContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) + EnterContainer(ctx context.Context, sandboxID, containerID string, cmd Cmd) (VCSandbox, VCContainer, *Process, error) + KillContainer(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error + StartContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) + StatusContainer(ctx context.Context, sandboxID, containerID string) (ContainerStatus, error) + StatsContainer(ctx context.Context, sandboxID, containerID string) (ContainerStats, error) + StopContainer(ctx context.Context, sandboxID, containerID string) (VCContainer, error) + ProcessListContainer(ctx context.Context, sandboxID, containerID string, options ProcessListOptions) (ProcessList, error) + UpdateContainer(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error + PauseContainer(ctx context.Context, sandboxID, containerID string) error + ResumeContainer(ctx context.Context, sandboxID, containerID string) error - AddDevice(sandboxID string, info config.DeviceInfo) (api.Device, error) + AddDevice(ctx context.Context, sandboxID string, info config.DeviceInfo) (api.Device, error) - AddInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) - RemoveInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) - ListInterfaces(sandboxID string) ([]*grpc.Interface, error) - UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) - ListRoutes(sandboxID string) ([]*grpc.Route, error) + AddInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) + RemoveInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) + ListInterfaces(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) + UpdateRoutes(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) + ListRoutes(ctx context.Context, sandboxID string) ([]*grpc.Route, error) } // VCSandbox is the Sandbox interface diff --git a/virtcontainers/kata_agent.go b/virtcontainers/kata_agent.go index 141b6eef8..cffbc7f24 100644 --- a/virtcontainers/kata_agent.go +++ b/virtcontainers/kata_agent.go @@ -24,6 +24,7 @@ import ( ns "github.com/kata-containers/runtime/virtcontainers/pkg/nsenter" "github.com/kata-containers/runtime/virtcontainers/pkg/uuid" "github.com/kata-containers/runtime/virtcontainers/utils" + opentracing "github.com/opentracing/opentracing-go" "github.com/gogo/protobuf/proto" "github.com/opencontainers/runtime-spec/specs-go" @@ -96,6 +97,21 @@ type kataAgent struct { proxyBuiltIn bool vmSocket interface{} + ctx context.Context +} + +func (k *kataAgent) trace(name string) (opentracing.Span, context.Context) { + if k.ctx == nil { + k.Logger().WithField("type", "bug").Error("trace called before context set") + k.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(k.ctx, name) + + span.SetTag("subsystem", "agent") + span.SetTag("type", "kata") + + return span, ctx } func (k *kataAgent) Logger() *logrus.Entry { @@ -135,7 +151,13 @@ func (k *kataAgent) generateVMSocket(id string, c KataAgentConfig) error { return nil } -func (k *kataAgent) init(sandbox *Sandbox, config interface{}) (err error) { +func (k *kataAgent) init(ctx context.Context, sandbox *Sandbox, config interface{}) (err error) { + // save + k.ctx = sandbox.ctx + + span, _ := k.trace("init") + defer span.Finish() + switch c := config.(type) { case KataAgentConfig: if err := k.generateVMSocket(sandbox.id, c); err != nil { @@ -240,6 +262,9 @@ func (k *kataAgent) configure(h hypervisor, id, sharePath string, builtin bool, } func (k *kataAgent) createSandbox(sandbox *Sandbox) error { + span, _ := k.trace("createSandbox") + defer span.Finish() + return k.configure(sandbox.hypervisor, sandbox.id, k.getSharePath(sandbox.id), k.proxyBuiltIn, nil) } @@ -321,6 +346,9 @@ func cmdEnvsToStringSlice(ev []EnvVar) []string { } func (k *kataAgent) exec(sandbox *Sandbox, c Container, cmd Cmd) (*Process, error) { + span, _ := k.trace("exec") + defer span.Finish() + var kataProcess *grpc.Process kataProcess, err := cmdToKataProcess(cmd) @@ -354,6 +382,8 @@ func (k *kataAgent) exec(sandbox *Sandbox, c Container, cmd Cmd) (*Process, erro } func (k *kataAgent) generateInterfacesAndRoutes(networkNS NetworkNamespace) ([]*grpc.Interface, []*grpc.Route, error) { + span, _ := k.trace("generateInterfacesAndRoutes") + defer span.Finish() if networkNS.NetNsPath == "" { return nil, nil, nil @@ -517,6 +547,9 @@ func (k *kataAgent) listRoutes() ([]*grpc.Route, error) { } func (k *kataAgent) startProxy(sandbox *Sandbox) error { + span, _ := k.trace("startProxy") + defer span.Finish() + var err error if k.proxy == nil { @@ -569,6 +602,9 @@ func (k *kataAgent) startProxy(sandbox *Sandbox) error { } func (k *kataAgent) startSandbox(sandbox *Sandbox) error { + span, _ := k.trace("startSandbox") + defer span.Finish() + err := k.startProxy(sandbox) if err != nil { return err @@ -642,6 +678,9 @@ func (k *kataAgent) startSandbox(sandbox *Sandbox) error { } func (k *kataAgent) stopSandbox(sandbox *Sandbox) error { + span, _ := k.trace("stopSandbox") + defer span.Finish() + if k.proxy == nil { return errorMissingProxy } @@ -811,7 +850,7 @@ func (k *kataAgent) rollbackFailingContainerCreation(c *Container) { k.Logger().WithError(err2).Error("rollback failed unmountHostMounts()") } - if err2 := bindUnmountContainerRootfs(kataHostSharedDir, c.sandbox.id, c.id); err2 != nil { + if err2 := bindUnmountContainerRootfs(k.ctx, kataHostSharedDir, c.sandbox.id, c.id); err2 != nil { k.Logger().WithError(err2).Error("rollback failed bindUnmountContainerRootfs()") } } @@ -861,7 +900,7 @@ func (k *kataAgent) buildContainerRootfs(sandbox *Sandbox, c *Container, rootPat // (kataGuestSharedDir) is already mounted in the // guest. We only need to mount the rootfs from // the host and it will show up in the guest. - if err := bindMountContainerRootfs(kataHostSharedDir, sandbox.id, c.id, c.rootFs, false); err != nil { + if err := bindMountContainerRootfs(k.ctx, kataHostSharedDir, sandbox.id, c.id, c.rootFs, false); err != nil { return nil, err } @@ -869,6 +908,9 @@ func (k *kataAgent) buildContainerRootfs(sandbox *Sandbox, c *Container, rootPat } func (k *kataAgent) createContainer(sandbox *Sandbox, c *Container) (p *Process, err error) { + span, _ := k.trace("createContainer") + defer span.Finish() + ociSpecJSON, ok := c.config.Annotations[vcAnnotations.ConfigJSONKey] if !ok { return nil, errorMissingOCISpec @@ -1101,6 +1143,9 @@ func (k *kataAgent) handlePidNamespace(grpcSpec *grpc.Spec, sandbox *Sandbox) (b } func (k *kataAgent) startContainer(sandbox *Sandbox, c *Container) error { + span, _ := k.trace("startContainer") + defer span.Finish() + req := &grpc.StartContainerRequest{ ContainerId: c.id, } @@ -1110,6 +1155,9 @@ func (k *kataAgent) startContainer(sandbox *Sandbox, c *Container) error { } func (k *kataAgent) stopContainer(sandbox *Sandbox, c Container) error { + span, _ := k.trace("stopContainer") + defer span.Finish() + req := &grpc.RemoveContainerRequest{ ContainerId: c.id, } @@ -1122,7 +1170,7 @@ func (k *kataAgent) stopContainer(sandbox *Sandbox, c Container) error { return err } - if err := bindUnmountContainerRootfs(kataHostSharedDir, sandbox.id, c.id); err != nil { + if err := bindUnmountContainerRootfs(k.ctx, kataHostSharedDir, sandbox.id, c.id); err != nil { return err } @@ -1261,6 +1309,9 @@ func (k *kataAgent) connect() error { return nil } + span, _ := k.trace("connect") + defer span.Finish() + // This is for the first connection only, to prevent race k.Lock() defer k.Unlock() @@ -1281,6 +1332,9 @@ func (k *kataAgent) connect() error { } func (k *kataAgent) disconnect() error { + span, _ := k.trace("disconnect") + defer span.Finish() + k.Lock() defer k.Unlock() @@ -1300,6 +1354,9 @@ func (k *kataAgent) disconnect() error { // check grpc server is serving func (k *kataAgent) check() error { + span, _ := k.trace("check") + defer span.Finish() + _, err := k.sendReq(&grpc.CheckRequest{}) if err != nil { err = fmt.Errorf("Failed to check if grpc server is working: %s", err) @@ -1308,6 +1365,9 @@ func (k *kataAgent) check() error { } func (k *kataAgent) waitProcess(c *Container, processID string) (int32, error) { + span, _ := k.trace("waitProcess") + defer span.Finish() + resp, err := k.sendReq(&grpc.WaitProcessRequest{ ContainerId: c.id, ExecId: processID, @@ -1428,6 +1488,10 @@ func (k *kataAgent) installReqFunc(c *kataclient.AgentClient) { } func (k *kataAgent) sendReq(request interface{}) (interface{}, error) { + span, _ := k.trace("sendReq") + span.SetTag("request", request) + defer span.Finish() + if err := k.connect(); err != nil { return nil, err } @@ -1443,7 +1507,7 @@ func (k *kataAgent) sendReq(request interface{}) (interface{}, error) { message := request.(proto.Message) k.Logger().WithField("name", msgName).WithField("req", message.String()).Debug("sending request") - return handler(context.Background(), request) + return handler(k.ctx, request) } // readStdout and readStderr are special that we cannot differentiate them with the request types... @@ -1473,7 +1537,7 @@ func (k *kataAgent) readProcessStderr(c *Container, processID string, data []byt type readFn func(context.Context, *grpc.ReadStreamRequest, ...golangGrpc.CallOption) (*grpc.ReadStreamResponse, error) func (k *kataAgent) readProcessStream(containerID, processID string, data []byte, read readFn) (int, error) { - resp, err := read(context.Background(), &grpc.ReadStreamRequest{ + resp, err := read(k.ctx, &grpc.ReadStreamRequest{ ContainerId: containerID, ExecId: processID, Len: uint32(len(data))}) diff --git a/virtcontainers/mock_hypervisor.go b/virtcontainers/mock_hypervisor.go index 85e599ebc..a9fc3617c 100644 --- a/virtcontainers/mock_hypervisor.go +++ b/virtcontainers/mock_hypervisor.go @@ -5,11 +5,13 @@ package virtcontainers +import "context" + type mockHypervisor struct { vCPUs uint32 } -func (m *mockHypervisor) init(id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error { +func (m *mockHypervisor) init(ctx context.Context, id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error { err := hypervisorConfig.valid() if err != nil { return err diff --git a/virtcontainers/mock_hypervisor_test.go b/virtcontainers/mock_hypervisor_test.go index ccde7c2ab..9e0f9c3ba 100644 --- a/virtcontainers/mock_hypervisor_test.go +++ b/virtcontainers/mock_hypervisor_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "testing" ) @@ -25,8 +26,10 @@ func TestMockHypervisorInit(t *testing.T) { storage: &filesystem{}, } + ctx := context.Background() + // wrong config - if err := m.init(sandbox.config.ID, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err == nil { + if err := m.init(ctx, sandbox.config.ID, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err == nil { t.Fatal() } @@ -37,7 +40,7 @@ func TestMockHypervisorInit(t *testing.T) { } // right config - if err := m.init(sandbox.config.ID, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { + if err := m.init(ctx, sandbox.config.ID, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { t.Fatal(err) } } diff --git a/virtcontainers/mount.go b/virtcontainers/mount.go index dba252287..a9a0350ef 100644 --- a/virtcontainers/mount.go +++ b/virtcontainers/mount.go @@ -7,6 +7,7 @@ package virtcontainers import ( "bufio" + "context" "errors" "fmt" "io" @@ -229,7 +230,10 @@ const mountPerm = os.FileMode(0755) // * evaluate all symlinks // * ensure the source exists // * recursively create the destination -func bindMount(source, destination string, readonly bool) error { +func bindMount(ctx context.Context, source, destination string, readonly bool) error { + span, _ := trace(ctx, "bindMount") + defer span.Finish() + if source == "" { return fmt.Errorf("source must be specified") } @@ -259,10 +263,13 @@ func bindMount(source, destination string, readonly bool) error { // bindMountContainerRootfs bind mounts a container rootfs into a 9pfs shared // directory between the guest and the host. -func bindMountContainerRootfs(sharedDir, sandboxID, cID, cRootFs string, readonly bool) error { +func bindMountContainerRootfs(ctx context.Context, sharedDir, sandboxID, cID, cRootFs string, readonly bool) error { + span, _ := trace(ctx, "bindMountContainerRootfs") + defer span.Finish() + rootfsDest := filepath.Join(sharedDir, sandboxID, cID, rootfsDir) - return bindMount(cRootFs, rootfsDest, readonly) + return bindMount(ctx, cRootFs, rootfsDest, readonly) } // Mount describes a container mount. @@ -288,20 +295,26 @@ type Mount struct { BlockDeviceID string } -func bindUnmountContainerRootfs(sharedDir, sandboxID, cID string) error { +func bindUnmountContainerRootfs(ctx context.Context, sharedDir, sandboxID, cID string) error { + span, _ := trace(ctx, "bindUnmountContainerRootfs") + defer span.Finish() + rootfsDest := filepath.Join(sharedDir, sandboxID, cID, rootfsDir) syscall.Unmount(rootfsDest, 0) return nil } -func bindUnmountAllRootfs(sharedDir string, sandbox *Sandbox) { +func bindUnmountAllRootfs(ctx context.Context, sharedDir string, sandbox *Sandbox) { + span, _ := trace(ctx, "bindUnmountAllRootfs") + defer span.Finish() + for _, c := range sandbox.containers { c.unmountHostMounts() if c.state.Fstype == "" { // Need to check for error returned by this call. // See: https://github.com/containers/virtcontainers/issues/295 - bindUnmountContainerRootfs(sharedDir, sandbox.id, c.id) + bindUnmountContainerRootfs(c.ctx, sharedDir, sandbox.id, c.id) } } } diff --git a/virtcontainers/mount_test.go b/virtcontainers/mount_test.go index f12ca7108..3b67c9688 100644 --- a/virtcontainers/mount_test.go +++ b/virtcontainers/mount_test.go @@ -7,6 +7,7 @@ package virtcontainers import ( "bytes" + "context" "fmt" "os" "os/exec" @@ -212,7 +213,7 @@ func TestGetDeviceForPathBindMount(t *testing.T) { defer os.Remove(dest) - err = bindMount(source, dest, false) + err = bindMount(context.Background(), source, dest, false) if err != nil { t.Fatal(err) } diff --git a/virtcontainers/network.go b/virtcontainers/network.go index 17d94315c..92602b2d9 100644 --- a/virtcontainers/network.go +++ b/virtcontainers/network.go @@ -7,6 +7,7 @@ package virtcontainers import ( "bufio" + "context" "encoding/hex" "encoding/json" "fmt" @@ -1417,7 +1418,7 @@ func createEndpointsFromScan(networkNSPath string, config NetworkConfig) ([]Endp } if isPhysical { - cnmLogger().WithField("interface", netInfo.Iface.Name).Info("Physical network interface found") + networkLogger().WithField("interface", netInfo.Iface.Name).Info("Physical network interface found") endpoint, err = createPhysicalEndpoint(netInfo) } else { var socketPath string @@ -1429,7 +1430,7 @@ func createEndpointsFromScan(networkNSPath string, config NetworkConfig) ([]Endp } if socketPath != "" { - cnmLogger().WithField("interface", netInfo.Iface.Name).Info("VhostUser network interface found") + networkLogger().WithField("interface", netInfo.Iface.Name).Info("VhostUser network interface found") endpoint, err = createVhostUserEndpoint(netInfo, socketPath) } else { endpoint, err = createVirtualNetworkEndpoint(idx, netInfo.Iface.Name, config.InterworkingModel) @@ -1581,7 +1582,7 @@ func vhostUserSocketPath(info interface{}) (string, error) { // between VM netns and the host network physical interface. type network interface { // init initializes the network, setting a new network namespace. - init(config NetworkConfig) (string, bool, error) + init(ctx context.Context, config NetworkConfig) (string, bool, error) // run runs a callback function in a specified network namespace. run(networkNSPath string, cb func() error) error diff --git a/virtcontainers/noop_agent.go b/virtcontainers/noop_agent.go index d5073166e..5c9eec843 100644 --- a/virtcontainers/noop_agent.go +++ b/virtcontainers/noop_agent.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "syscall" "github.com/kata-containers/agent/protocols/grpc" @@ -23,7 +24,7 @@ func (n *noopAgent) startProxy(sandbox *Sandbox) error { } // init initializes the Noop agent, i.e. it does nothing. -func (n *noopAgent) init(sandbox *Sandbox, config interface{}) error { +func (n *noopAgent) init(ctx context.Context, sandbox *Sandbox, config interface{}) error { return nil } diff --git a/virtcontainers/noop_agent_test.go b/virtcontainers/noop_agent_test.go index 39b689abb..144c8dff6 100644 --- a/virtcontainers/noop_agent_test.go +++ b/virtcontainers/noop_agent_test.go @@ -7,6 +7,7 @@ package virtcontainers import ( + "context" "testing" ) @@ -14,14 +15,15 @@ func testCreateNoopContainer() (*Sandbox, *Container, error) { contID := "100" config := newTestSandboxConfigNoop() - p, err := CreateSandbox(config, nil) + ctx := context.Background() + p, err := CreateSandbox(ctx, config, nil) if err != nil { return nil, nil, err } contConfig := newTestContainerConfigNoop(contID) - p, c, err := CreateContainer(p.ID(), contConfig) + p, c, err := CreateContainer(ctx, p.ID(), contConfig) if err != nil { return nil, nil, err } @@ -33,7 +35,7 @@ func TestNoopAgentInit(t *testing.T) { n := &noopAgent{} sandbox := &Sandbox{} - err := n.init(sandbox, nil) + err := n.init(context.Background(), sandbox, nil) if err != nil { t.Fatal(err) } diff --git a/virtcontainers/noop_network.go b/virtcontainers/noop_network.go index e4ef40875..3af7d7d09 100644 --- a/virtcontainers/noop_network.go +++ b/virtcontainers/noop_network.go @@ -5,6 +5,8 @@ package virtcontainers +import "context" + // noopNetwork a.k.a. NO-OP Network is an empty network implementation, for // testing and mocking purposes. type noopNetwork struct { @@ -12,7 +14,7 @@ type noopNetwork struct { // init initializes the network, setting a new network namespace for the Noop network. // It does nothing. -func (n *noopNetwork) init(config NetworkConfig) (string, bool, error) { +func (n *noopNetwork) init(ctx context.Context, config NetworkConfig) (string, bool, error) { return "", true, nil } diff --git a/virtcontainers/pkg/hyperstart/hyperstart.go b/virtcontainers/pkg/hyperstart/hyperstart.go index 44548bd4c..893af0b9c 100644 --- a/virtcontainers/pkg/hyperstart/hyperstart.go +++ b/virtcontainers/pkg/hyperstart/hyperstart.go @@ -6,6 +6,7 @@ package hyperstart import ( + "context" "encoding/binary" "encoding/json" "fmt" @@ -123,7 +124,7 @@ type Hyperstart struct { var hyperLog = logrus.FieldLogger(logrus.New()) // SetLogger sets the logger for hyperstart package. -func SetLogger(logger logrus.FieldLogger) { +func SetLogger(ctx context.Context, logger logrus.FieldLogger) { hyperLog = logger.WithFields(logrus.Fields{ "source": "virtcontainers", "subsystem": "hyperstart", diff --git a/virtcontainers/pkg/oci/utils.go b/virtcontainers/pkg/oci/utils.go index ec01db9c6..499e2c1c5 100644 --- a/virtcontainers/pkg/oci/utils.go +++ b/virtcontainers/pkg/oci/utils.go @@ -6,6 +6,7 @@ package oci import ( + "context" "encoding/json" "errors" "fmt" @@ -134,7 +135,7 @@ var ociLog = logrus.WithFields(logrus.Fields{ }) // SetLogger sets the logger for oci package. -func SetLogger(logger *logrus.Entry) { +func SetLogger(ctx context.Context, logger *logrus.Entry) { fields := ociLog.Data ociLog = logger.WithFields(fields) } diff --git a/virtcontainers/pkg/vcmock/mock.go b/virtcontainers/pkg/vcmock/mock.go index 4c74b0065..279f43590 100644 --- a/virtcontainers/pkg/vcmock/mock.go +++ b/virtcontainers/pkg/vcmock/mock.go @@ -16,6 +16,7 @@ package vcmock import ( + "context" "fmt" "syscall" @@ -32,266 +33,266 @@ import ( const mockErrorPrefix = "vcmock forced failure" // SetLogger implements the VC function of the same name. -func (m *VCMock) SetLogger(logger *logrus.Entry) { +func (m *VCMock) SetLogger(ctx context.Context, logger *logrus.Entry) { if m.SetLoggerFunc != nil { - m.SetLoggerFunc(logger) + m.SetLoggerFunc(ctx, logger) } } // SetFactory implements the VC function of the same name. -func (m *VCMock) SetFactory(factory vc.Factory) { +func (m *VCMock) SetFactory(ctx context.Context, factory vc.Factory) { if m.SetFactoryFunc != nil { - m.SetFactoryFunc(factory) + m.SetFactoryFunc(ctx, factory) } } // CreateSandbox implements the VC function of the same name. -func (m *VCMock) CreateSandbox(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { +func (m *VCMock) CreateSandbox(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { if m.CreateSandboxFunc != nil { - return m.CreateSandboxFunc(sandboxConfig) + return m.CreateSandboxFunc(ctx, sandboxConfig) } return nil, fmt.Errorf("%s: %s (%+v): sandboxConfig: %v", mockErrorPrefix, getSelf(), m, sandboxConfig) } // DeleteSandbox implements the VC function of the same name. -func (m *VCMock) DeleteSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) DeleteSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.DeleteSandboxFunc != nil { - return m.DeleteSandboxFunc(sandboxID) + return m.DeleteSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // FetchSandbox implements the VC function of the same name. -func (m *VCMock) FetchSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) FetchSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.FetchSandboxFunc != nil { - return m.FetchSandboxFunc(sandboxID) + return m.FetchSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // StartSandbox implements the VC function of the same name. -func (m *VCMock) StartSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) StartSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.StartSandboxFunc != nil { - return m.StartSandboxFunc(sandboxID) + return m.StartSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // StopSandbox implements the VC function of the same name. -func (m *VCMock) StopSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) StopSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.StopSandboxFunc != nil { - return m.StopSandboxFunc(sandboxID) + return m.StopSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // RunSandbox implements the VC function of the same name. -func (m *VCMock) RunSandbox(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { +func (m *VCMock) RunSandbox(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { if m.RunSandboxFunc != nil { - return m.RunSandboxFunc(sandboxConfig) + return m.RunSandboxFunc(ctx, sandboxConfig) } return nil, fmt.Errorf("%s: %s (%+v): sandboxConfig: %v", mockErrorPrefix, getSelf(), m, sandboxConfig) } // ListSandbox implements the VC function of the same name. -func (m *VCMock) ListSandbox() ([]vc.SandboxStatus, error) { +func (m *VCMock) ListSandbox(ctx context.Context) ([]vc.SandboxStatus, error) { if m.ListSandboxFunc != nil { - return m.ListSandboxFunc() + return m.ListSandboxFunc(ctx) } return nil, fmt.Errorf("%s: %s", mockErrorPrefix, getSelf()) } // StatusSandbox implements the VC function of the same name. -func (m *VCMock) StatusSandbox(sandboxID string) (vc.SandboxStatus, error) { +func (m *VCMock) StatusSandbox(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) { if m.StatusSandboxFunc != nil { - return m.StatusSandboxFunc(sandboxID) + return m.StatusSandboxFunc(ctx, sandboxID) } return vc.SandboxStatus{}, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // PauseSandbox implements the VC function of the same name. -func (m *VCMock) PauseSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) PauseSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.PauseSandboxFunc != nil { - return m.PauseSandboxFunc(sandboxID) + return m.PauseSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // ResumeSandbox implements the VC function of the same name. -func (m *VCMock) ResumeSandbox(sandboxID string) (vc.VCSandbox, error) { +func (m *VCMock) ResumeSandbox(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { if m.ResumeSandboxFunc != nil { - return m.ResumeSandboxFunc(sandboxID) + return m.ResumeSandboxFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // CreateContainer implements the VC function of the same name. -func (m *VCMock) CreateContainer(sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { +func (m *VCMock) CreateContainer(ctx context.Context, sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { if m.CreateContainerFunc != nil { - return m.CreateContainerFunc(sandboxID, containerConfig) + return m.CreateContainerFunc(ctx, sandboxID, containerConfig) } return nil, nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerConfig: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerConfig) } // DeleteContainer implements the VC function of the same name. -func (m *VCMock) DeleteContainer(sandboxID, containerID string) (vc.VCContainer, error) { +func (m *VCMock) DeleteContainer(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { if m.DeleteContainerFunc != nil { - return m.DeleteContainerFunc(sandboxID, containerID) + return m.DeleteContainerFunc(ctx, sandboxID, containerID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // StartContainer implements the VC function of the same name. -func (m *VCMock) StartContainer(sandboxID, containerID string) (vc.VCContainer, error) { +func (m *VCMock) StartContainer(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { if m.StartContainerFunc != nil { - return m.StartContainerFunc(sandboxID, containerID) + return m.StartContainerFunc(ctx, sandboxID, containerID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // StopContainer implements the VC function of the same name. -func (m *VCMock) StopContainer(sandboxID, containerID string) (vc.VCContainer, error) { +func (m *VCMock) StopContainer(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { if m.StopContainerFunc != nil { - return m.StopContainerFunc(sandboxID, containerID) + return m.StopContainerFunc(ctx, sandboxID, containerID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // EnterContainer implements the VC function of the same name. -func (m *VCMock) EnterContainer(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { +func (m *VCMock) EnterContainer(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { if m.EnterContainerFunc != nil { - return m.EnterContainerFunc(sandboxID, containerID, cmd) + return m.EnterContainerFunc(ctx, sandboxID, containerID, cmd) } return nil, nil, nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v, cmd: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID, cmd) } // StatusContainer implements the VC function of the same name. -func (m *VCMock) StatusContainer(sandboxID, containerID string) (vc.ContainerStatus, error) { +func (m *VCMock) StatusContainer(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { if m.StatusContainerFunc != nil { - return m.StatusContainerFunc(sandboxID, containerID) + return m.StatusContainerFunc(ctx, sandboxID, containerID) } return vc.ContainerStatus{}, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // StatsContainer implements the VC function of the same name. -func (m *VCMock) StatsContainer(sandboxID, containerID string) (vc.ContainerStats, error) { +func (m *VCMock) StatsContainer(ctx context.Context, sandboxID, containerID string) (vc.ContainerStats, error) { if m.StatsContainerFunc != nil { - return m.StatsContainerFunc(sandboxID, containerID) + return m.StatsContainerFunc(ctx, sandboxID, containerID) } return vc.ContainerStats{}, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // KillContainer implements the VC function of the same name. -func (m *VCMock) KillContainer(sandboxID, containerID string, signal syscall.Signal, all bool) error { +func (m *VCMock) KillContainer(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { if m.KillContainerFunc != nil { - return m.KillContainerFunc(sandboxID, containerID, signal, all) + return m.KillContainerFunc(ctx, sandboxID, containerID, signal, all) } return fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v, signal: %v, all: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID, signal, all) } // ProcessListContainer implements the VC function of the same name. -func (m *VCMock) ProcessListContainer(sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { +func (m *VCMock) ProcessListContainer(ctx context.Context, sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { if m.ProcessListContainerFunc != nil { - return m.ProcessListContainerFunc(sandboxID, containerID, options) + return m.ProcessListContainerFunc(ctx, sandboxID, containerID, options) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // UpdateContainer implements the VC function of the same name. -func (m *VCMock) UpdateContainer(sandboxID, containerID string, resources specs.LinuxResources) error { +func (m *VCMock) UpdateContainer(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error { if m.UpdateContainerFunc != nil { - return m.UpdateContainerFunc(sandboxID, containerID, resources) + return m.UpdateContainerFunc(ctx, sandboxID, containerID, resources) } return fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // PauseContainer implements the VC function of the same name. -func (m *VCMock) PauseContainer(sandboxID, containerID string) error { +func (m *VCMock) PauseContainer(ctx context.Context, sandboxID, containerID string) error { if m.PauseContainerFunc != nil { - return m.PauseContainerFunc(sandboxID, containerID) + return m.PauseContainerFunc(ctx, sandboxID, containerID) } return fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // ResumeContainer implements the VC function of the same name. -func (m *VCMock) ResumeContainer(sandboxID, containerID string) error { +func (m *VCMock) ResumeContainer(ctx context.Context, sandboxID, containerID string) error { if m.ResumeContainerFunc != nil { - return m.ResumeContainerFunc(sandboxID, containerID) + return m.ResumeContainerFunc(ctx, sandboxID, containerID) } return fmt.Errorf("%s: %s (%+v): sandboxID: %v, containerID: %v", mockErrorPrefix, getSelf(), m, sandboxID, containerID) } // AddDevice implements the VC function of the same name. -func (m *VCMock) AddDevice(sandboxID string, info config.DeviceInfo) (api.Device, error) { +func (m *VCMock) AddDevice(ctx context.Context, sandboxID string, info config.DeviceInfo) (api.Device, error) { if m.AddDeviceFunc != nil { - return m.AddDeviceFunc(sandboxID, info) + return m.AddDeviceFunc(ctx, sandboxID, info) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // AddInterface implements the VC function of the same name. -func (m *VCMock) AddInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { +func (m *VCMock) AddInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { if m.AddInterfaceFunc != nil { - return m.AddInterfaceFunc(sandboxID, inf) + return m.AddInterfaceFunc(ctx, sandboxID, inf) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // RemoveInterface implements the VC function of the same name. -func (m *VCMock) RemoveInterface(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { +func (m *VCMock) RemoveInterface(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) { if m.RemoveInterfaceFunc != nil { - return m.RemoveInterfaceFunc(sandboxID, inf) + return m.RemoveInterfaceFunc(ctx, sandboxID, inf) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // ListInterfaces implements the VC function of the same name. -func (m *VCMock) ListInterfaces(sandboxID string) ([]*grpc.Interface, error) { +func (m *VCMock) ListInterfaces(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) { if m.ListInterfacesFunc != nil { - return m.ListInterfacesFunc(sandboxID) + return m.ListInterfacesFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // UpdateRoutes implements the VC function of the same name. -func (m *VCMock) UpdateRoutes(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { +func (m *VCMock) UpdateRoutes(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) { if m.UpdateRoutesFunc != nil { - return m.UpdateRoutesFunc(sandboxID, routes) + return m.UpdateRoutesFunc(ctx, sandboxID, routes) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) } // ListRoutes implements the VC function of the same name. -func (m *VCMock) ListRoutes(sandboxID string) ([]*grpc.Route, error) { +func (m *VCMock) ListRoutes(ctx context.Context, sandboxID string) ([]*grpc.Route, error) { if m.ListRoutesFunc != nil { - return m.ListRoutesFunc(sandboxID) + return m.ListRoutesFunc(ctx, sandboxID) } return nil, fmt.Errorf("%s: %s (%+v): sandboxID: %v", mockErrorPrefix, getSelf(), m, sandboxID) diff --git a/virtcontainers/pkg/vcmock/mock_test.go b/virtcontainers/pkg/vcmock/mock_test.go index 2dc53a312..983a11baf 100644 --- a/virtcontainers/pkg/vcmock/mock_test.go +++ b/virtcontainers/pkg/vcmock/mock_test.go @@ -6,6 +6,7 @@ package vcmock import ( + "context" "reflect" "syscall" "testing" @@ -102,14 +103,15 @@ func TestVCMockSetLogger(t *testing.T) { logger := logrus.NewEntry(logrus.New()) assert.Equal(loggerTriggered, 0) - m.SetLogger(logger) + ctx := context.Background() + m.SetLogger(ctx, logger) assert.Equal(loggerTriggered, 0) - m.SetLoggerFunc = func(logger logrus.FieldLogger) { + m.SetLoggerFunc = func(ctx context.Context, logger *logrus.Entry) { loggerTriggered = 1 } - m.SetLogger(logger) + m.SetLogger(ctx, logger) assert.Equal(loggerTriggered, 1) } @@ -119,22 +121,23 @@ func TestVCMockCreateSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.CreateSandboxFunc) - _, err := m.CreateSandbox(vc.SandboxConfig{}) + ctx := context.Background() + _, err := m.CreateSandbox(ctx, vc.SandboxConfig{}) assert.Error(err) assert.True(IsMockError(err)) - m.CreateSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + m.CreateSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.CreateSandbox(vc.SandboxConfig{}) + sandbox, err := m.CreateSandbox(ctx, vc.SandboxConfig{}) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.CreateSandboxFunc = nil - _, err = m.CreateSandbox(vc.SandboxConfig{}) + _, err = m.CreateSandbox(ctx, vc.SandboxConfig{}) assert.Error(err) assert.True(IsMockError(err)) } @@ -145,22 +148,23 @@ func TestVCMockDeleteSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.DeleteSandboxFunc) - _, err := m.DeleteSandbox(testSandboxID) + ctx := context.Background() + _, err := m.DeleteSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.DeleteSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + m.DeleteSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.DeleteSandbox(testSandboxID) + sandbox, err := m.DeleteSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.DeleteSandboxFunc = nil - _, err = m.DeleteSandbox(testSandboxID) + _, err = m.DeleteSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -171,22 +175,23 @@ func TestVCMockListSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.ListSandboxFunc) - _, err := m.ListSandbox() + ctx := context.Background() + _, err := m.ListSandbox(ctx) assert.Error(err) assert.True(IsMockError(err)) - m.ListSandboxFunc = func() ([]vc.SandboxStatus, error) { + m.ListSandboxFunc = func(ctx context.Context) ([]vc.SandboxStatus, error) { return []vc.SandboxStatus{}, nil } - sandboxes, err := m.ListSandbox() + sandboxes, err := m.ListSandbox(ctx) assert.NoError(err) assert.Equal(sandboxes, []vc.SandboxStatus{}) // reset m.ListSandboxFunc = nil - _, err = m.ListSandbox() + _, err = m.ListSandbox(ctx) assert.Error(err) assert.True(IsMockError(err)) } @@ -197,22 +202,23 @@ func TestVCMockPauseSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.PauseSandboxFunc) - _, err := m.PauseSandbox(testSandboxID) + ctx := context.Background() + _, err := m.PauseSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.PauseSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + m.PauseSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.PauseSandbox(testSandboxID) + sandbox, err := m.PauseSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.PauseSandboxFunc = nil - _, err = m.PauseSandbox(testSandboxID) + _, err = m.PauseSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -223,22 +229,23 @@ func TestVCMockResumeSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.ResumeSandboxFunc) - _, err := m.ResumeSandbox(testSandboxID) + ctx := context.Background() + _, err := m.ResumeSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.ResumeSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + m.ResumeSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.ResumeSandbox(testSandboxID) + sandbox, err := m.ResumeSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.ResumeSandboxFunc = nil - _, err = m.ResumeSandbox(testSandboxID) + _, err = m.ResumeSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -249,22 +256,23 @@ func TestVCMockRunSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.RunSandboxFunc) - _, err := m.RunSandbox(vc.SandboxConfig{}) + ctx := context.Background() + _, err := m.RunSandbox(ctx, vc.SandboxConfig{}) assert.Error(err) assert.True(IsMockError(err)) - m.RunSandboxFunc = func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { + m.RunSandboxFunc = func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.RunSandbox(vc.SandboxConfig{}) + sandbox, err := m.RunSandbox(ctx, vc.SandboxConfig{}) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.RunSandboxFunc = nil - _, err = m.RunSandbox(vc.SandboxConfig{}) + _, err = m.RunSandbox(ctx, vc.SandboxConfig{}) assert.Error(err) assert.True(IsMockError(err)) } @@ -275,22 +283,23 @@ func TestVCMockStartSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.StartSandboxFunc) - _, err := m.StartSandbox(testSandboxID) + ctx := context.Background() + _, err := m.StartSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.StartSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + m.StartSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.StartSandbox(testSandboxID) + sandbox, err := m.StartSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.StartSandboxFunc = nil - _, err = m.StartSandbox(testSandboxID) + _, err = m.StartSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -301,22 +310,23 @@ func TestVCMockStatusSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.StatusSandboxFunc) - _, err := m.StatusSandbox(testSandboxID) + ctx := context.Background() + _, err := m.StatusSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.StatusSandboxFunc = func(sandboxID string) (vc.SandboxStatus, error) { + m.StatusSandboxFunc = func(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) { return vc.SandboxStatus{}, nil } - sandbox, err := m.StatusSandbox(testSandboxID) + sandbox, err := m.StatusSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, vc.SandboxStatus{}) // reset m.StatusSandboxFunc = nil - _, err = m.StatusSandbox(testSandboxID) + _, err = m.StatusSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -327,22 +337,23 @@ func TestVCMockStopSandbox(t *testing.T) { m := &VCMock{} assert.Nil(m.StopSandboxFunc) - _, err := m.StopSandbox(testSandboxID) + ctx := context.Background() + _, err := m.StopSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) - m.StopSandboxFunc = func(sandboxID string) (vc.VCSandbox, error) { + m.StopSandboxFunc = func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.StopSandbox(testSandboxID) + sandbox, err := m.StopSandbox(ctx, testSandboxID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.StopSandboxFunc = nil - _, err = m.StopSandbox(testSandboxID) + _, err = m.StopSandbox(ctx, testSandboxID) assert.Error(err) assert.True(IsMockError(err)) } @@ -353,16 +364,17 @@ func TestVCMockCreateContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.CreateContainerFunc) + ctx := context.Background() config := vc.ContainerConfig{} - _, _, err := m.CreateContainer(testSandboxID, config) + _, _, err := m.CreateContainer(ctx, testSandboxID, config) assert.Error(err) assert.True(IsMockError(err)) - m.CreateContainerFunc = func(sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { + m.CreateContainerFunc = func(ctx context.Context, sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) { return &Sandbox{}, &Container{}, nil } - sandbox, container, err := m.CreateContainer(testSandboxID, config) + sandbox, container, err := m.CreateContainer(ctx, testSandboxID, config) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) assert.Equal(container, &Container{}) @@ -370,7 +382,7 @@ func TestVCMockCreateContainer(t *testing.T) { // reset m.CreateContainerFunc = nil - _, _, err = m.CreateContainer(testSandboxID, config) + _, _, err = m.CreateContainer(ctx, testSandboxID, config) assert.Error(err) assert.True(IsMockError(err)) } @@ -381,22 +393,23 @@ func TestVCMockDeleteContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.DeleteContainerFunc) - _, err := m.DeleteContainer(testSandboxID, testContainerID) + ctx := context.Background() + _, err := m.DeleteContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) - m.DeleteContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + m.DeleteContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &Container{}, nil } - container, err := m.DeleteContainer(testSandboxID, testContainerID) + container, err := m.DeleteContainer(ctx, testSandboxID, testContainerID) assert.NoError(err) assert.Equal(container, &Container{}) // reset m.DeleteContainerFunc = nil - _, err = m.DeleteContainer(testSandboxID, testContainerID) + _, err = m.DeleteContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) } @@ -407,16 +420,17 @@ func TestVCMockEnterContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.EnterContainerFunc) + ctx := context.Background() cmd := vc.Cmd{} - _, _, _, err := m.EnterContainer(testSandboxID, testContainerID, cmd) + _, _, _, err := m.EnterContainer(ctx, testSandboxID, testContainerID, cmd) assert.Error(err) assert.True(IsMockError(err)) - m.EnterContainerFunc = func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { + m.EnterContainerFunc = func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) { return &Sandbox{}, &Container{}, &vc.Process{}, nil } - sandbox, container, process, err := m.EnterContainer(testSandboxID, testContainerID, cmd) + sandbox, container, process, err := m.EnterContainer(ctx, testSandboxID, testContainerID, cmd) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) assert.Equal(container, &Container{}) @@ -425,7 +439,7 @@ func TestVCMockEnterContainer(t *testing.T) { // reset m.EnterContainerFunc = nil - _, _, _, err = m.EnterContainer(testSandboxID, testContainerID, cmd) + _, _, _, err = m.EnterContainer(ctx, testSandboxID, testContainerID, cmd) assert.Error(err) assert.True(IsMockError(err)) } @@ -436,20 +450,21 @@ func TestVCMockKillContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.KillContainerFunc) + ctx := context.Background() sig := syscall.SIGTERM for _, all := range []bool{true, false} { - err := m.KillContainer(testSandboxID, testContainerID, sig, all) + err := m.KillContainer(ctx, testSandboxID, testContainerID, sig, all) assert.Error(err) assert.True(IsMockError(err)) } - m.KillContainerFunc = func(sandboxID, containerID string, signal syscall.Signal, all bool) error { + m.KillContainerFunc = func(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error { return nil } for _, all := range []bool{true, false} { - err := m.KillContainer(testSandboxID, testContainerID, sig, all) + err := m.KillContainer(ctx, testSandboxID, testContainerID, sig, all) assert.NoError(err) } @@ -457,7 +472,7 @@ func TestVCMockKillContainer(t *testing.T) { m.KillContainerFunc = nil for _, all := range []bool{true, false} { - err := m.KillContainer(testSandboxID, testContainerID, sig, all) + err := m.KillContainer(ctx, testSandboxID, testContainerID, sig, all) assert.Error(err) assert.True(IsMockError(err)) } @@ -469,22 +484,23 @@ func TestVCMockStartContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.StartContainerFunc) - _, err := m.StartContainer(testSandboxID, testContainerID) + ctx := context.Background() + _, err := m.StartContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) - m.StartContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + m.StartContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &Container{}, nil } - container, err := m.StartContainer(testSandboxID, testContainerID) + container, err := m.StartContainer(ctx, testSandboxID, testContainerID) assert.NoError(err) assert.Equal(container, &Container{}) // reset m.StartContainerFunc = nil - _, err = m.StartContainer(testSandboxID, testContainerID) + _, err = m.StartContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) } @@ -495,22 +511,23 @@ func TestVCMockStatusContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.StatusContainerFunc) - _, err := m.StatusContainer(testSandboxID, testContainerID) + ctx := context.Background() + _, err := m.StatusContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) - m.StatusContainerFunc = func(sandboxID, containerID string) (vc.ContainerStatus, error) { + m.StatusContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) { return vc.ContainerStatus{}, nil } - status, err := m.StatusContainer(testSandboxID, testContainerID) + status, err := m.StatusContainer(ctx, testSandboxID, testContainerID) assert.NoError(err) assert.Equal(status, vc.ContainerStatus{}) // reset m.StatusContainerFunc = nil - _, err = m.StatusContainer(testSandboxID, testContainerID) + _, err = m.StatusContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) } @@ -521,23 +538,24 @@ func TestVCMockStatsContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.StatsContainerFunc) - _, err := m.StatsContainer(testSandboxID, testContainerID) + ctx := context.Background() + _, err := m.StatsContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) - m.StatsContainerFunc = func(sandboxID, containerID string) (vc.ContainerStats, error) { + m.StatsContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStats, error) { return vc.ContainerStats{}, nil } - stats, err := m.StatsContainer(testSandboxID, testContainerID) + stats, err := m.StatsContainer(ctx, testSandboxID, testContainerID) assert.NoError(err) assert.Equal(stats, vc.ContainerStats{}) // reset m.StatsContainerFunc = nil - _, err = m.StatsContainer(testSandboxID, testContainerID) + _, err = m.StatsContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) } @@ -548,22 +566,23 @@ func TestVCMockStopContainer(t *testing.T) { m := &VCMock{} assert.Nil(m.StopContainerFunc) - _, err := m.StopContainer(testSandboxID, testContainerID) + ctx := context.Background() + _, err := m.StopContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) - m.StopContainerFunc = func(sandboxID, containerID string) (vc.VCContainer, error) { + m.StopContainerFunc = func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) { return &Container{}, nil } - container, err := m.StopContainer(testSandboxID, testContainerID) + container, err := m.StopContainer(ctx, testSandboxID, testContainerID) assert.NoError(err) assert.Equal(container, &Container{}) // reset m.StopContainerFunc = nil - _, err = m.StopContainer(testSandboxID, testContainerID) + _, err = m.StopContainer(ctx, testSandboxID, testContainerID) assert.Error(err) assert.True(IsMockError(err)) } @@ -579,24 +598,25 @@ func TestVCMockProcessListContainer(t *testing.T) { Args: []string{"-ef"}, } - _, err := m.ProcessListContainer(testSandboxID, testContainerID, options) + ctx := context.Background() + _, err := m.ProcessListContainer(ctx, testSandboxID, testContainerID, options) assert.Error(err) assert.True(IsMockError(err)) processList := vc.ProcessList("hi") - m.ProcessListContainerFunc = func(sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { + m.ProcessListContainerFunc = func(ctx context.Context, sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) { return processList, nil } - pList, err := m.ProcessListContainer(testSandboxID, testContainerID, options) + pList, err := m.ProcessListContainer(ctx, testSandboxID, testContainerID, options) assert.NoError(err) assert.Equal(pList, processList) // reset m.ProcessListContainerFunc = nil - _, err = m.ProcessListContainer(testSandboxID, testContainerID, options) + _, err = m.ProcessListContainer(ctx, testSandboxID, testContainerID, options) assert.Error(err) assert.True(IsMockError(err)) } @@ -608,22 +628,23 @@ func TestVCMockFetchSandbox(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.FetchSandboxFunc) - _, err := m.FetchSandbox(config.ID) + ctx := context.Background() + _, err := m.FetchSandbox(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) - m.FetchSandboxFunc = func(id string) (vc.VCSandbox, error) { + m.FetchSandboxFunc = func(ctx context.Context, id string) (vc.VCSandbox, error) { return &Sandbox{}, nil } - sandbox, err := m.FetchSandbox(config.ID) + sandbox, err := m.FetchSandbox(ctx, config.ID) assert.NoError(err) assert.Equal(sandbox, &Sandbox{}) // reset m.FetchSandboxFunc = nil - _, err = m.FetchSandbox(config.ID) + _, err = m.FetchSandbox(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) @@ -636,21 +657,22 @@ func TestVCMockPauseContainer(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.PauseContainerFunc) - err := m.PauseContainer(config.ID, config.ID) + ctx := context.Background() + err := m.PauseContainer(ctx, config.ID, config.ID) assert.Error(err) assert.True(IsMockError(err)) - m.PauseContainerFunc = func(sid, cid string) error { + m.PauseContainerFunc = func(ctx context.Context, sid, cid string) error { return nil } - err = m.PauseContainer(config.ID, config.ID) + err = m.PauseContainer(ctx, config.ID, config.ID) assert.NoError(err) // reset m.PauseContainerFunc = nil - err = m.PauseContainer(config.ID, config.ID) + err = m.PauseContainer(ctx, config.ID, config.ID) assert.Error(err) assert.True(IsMockError(err)) } @@ -662,21 +684,22 @@ func TestVCMockResumeContainer(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.ResumeContainerFunc) - err := m.ResumeContainer(config.ID, config.ID) + ctx := context.Background() + err := m.ResumeContainer(ctx, config.ID, config.ID) assert.Error(err) assert.True(IsMockError(err)) - m.ResumeContainerFunc = func(sid, cid string) error { + m.ResumeContainerFunc = func(ctx context.Context, sid, cid string) error { return nil } - err = m.ResumeContainer(config.ID, config.ID) + err = m.ResumeContainer(ctx, config.ID, config.ID) assert.NoError(err) // reset m.ResumeContainerFunc = nil - err = m.ResumeContainer(config.ID, config.ID) + err = m.ResumeContainer(ctx, config.ID, config.ID) assert.Error(err) assert.True(IsMockError(err)) } @@ -697,18 +720,19 @@ func TestVCMockSetVMFactory(t *testing.T) { HypervisorConfig: hyperConfig, } - f, err := factory.NewFactory(factory.Config{VMConfig: vmConfig}, false) + ctx := context.Background() + f, err := factory.NewFactory(ctx, factory.Config{VMConfig: vmConfig}, false) assert.Nil(err) assert.Equal(factoryTriggered, 0) - m.SetFactory(f) + m.SetFactory(ctx, f) assert.Equal(factoryTriggered, 0) - m.SetFactoryFunc = func(factory vc.Factory) { + m.SetFactoryFunc = func(ctx context.Context, factory vc.Factory) { factoryTriggered = 1 } - m.SetFactory(f) + m.SetFactory(ctx, f) assert.Equal(factoryTriggered, 1) } @@ -719,21 +743,22 @@ func TestVCMockAddInterface(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.AddInterfaceFunc) - _, err := m.AddInterface(config.ID, nil) + ctx := context.Background() + _, err := m.AddInterface(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) - m.AddInterfaceFunc = func(sid string, inf *grpc.Interface) (*grpc.Interface, error) { + m.AddInterfaceFunc = func(ctx context.Context, sid string, inf *grpc.Interface) (*grpc.Interface, error) { return nil, nil } - _, err = m.AddInterface(config.ID, nil) + _, err = m.AddInterface(ctx, config.ID, nil) assert.NoError(err) // reset m.AddInterfaceFunc = nil - _, err = m.AddInterface(config.ID, nil) + _, err = m.AddInterface(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) } @@ -745,21 +770,22 @@ func TestVCMockRemoveInterface(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.RemoveInterfaceFunc) - _, err := m.RemoveInterface(config.ID, nil) + ctx := context.Background() + _, err := m.RemoveInterface(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) - m.RemoveInterfaceFunc = func(sid string, inf *grpc.Interface) (*grpc.Interface, error) { + m.RemoveInterfaceFunc = func(ctx context.Context, sid string, inf *grpc.Interface) (*grpc.Interface, error) { return nil, nil } - _, err = m.RemoveInterface(config.ID, nil) + _, err = m.RemoveInterface(ctx, config.ID, nil) assert.NoError(err) // reset m.RemoveInterfaceFunc = nil - _, err = m.RemoveInterface(config.ID, nil) + _, err = m.RemoveInterface(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) } @@ -771,21 +797,22 @@ func TestVCMockListInterfaces(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.ListInterfacesFunc) - _, err := m.ListInterfaces(config.ID) + ctx := context.Background() + _, err := m.ListInterfaces(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) - m.ListInterfacesFunc = func(sid string) ([]*grpc.Interface, error) { + m.ListInterfacesFunc = func(ctx context.Context, sid string) ([]*grpc.Interface, error) { return nil, nil } - _, err = m.ListInterfaces(config.ID) + _, err = m.ListInterfaces(ctx, config.ID) assert.NoError(err) // reset m.ListInterfacesFunc = nil - _, err = m.ListInterfaces(config.ID) + _, err = m.ListInterfaces(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) } @@ -797,21 +824,22 @@ func TestVCMockUpdateRoutes(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.UpdateRoutesFunc) - _, err := m.UpdateRoutes(config.ID, nil) + ctx := context.Background() + _, err := m.UpdateRoutes(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) - m.UpdateRoutesFunc = func(sid string, routes []*grpc.Route) ([]*grpc.Route, error) { + m.UpdateRoutesFunc = func(ctx context.Context, sid string, routes []*grpc.Route) ([]*grpc.Route, error) { return nil, nil } - _, err = m.UpdateRoutes(config.ID, nil) + _, err = m.UpdateRoutes(ctx, config.ID, nil) assert.NoError(err) // reset m.UpdateRoutesFunc = nil - _, err = m.UpdateRoutes(config.ID, nil) + _, err = m.UpdateRoutes(ctx, config.ID, nil) assert.Error(err) assert.True(IsMockError(err)) } @@ -823,21 +851,22 @@ func TestVCMockListRoutes(t *testing.T) { config := &vc.SandboxConfig{} assert.Nil(m.ListRoutesFunc) - _, err := m.ListRoutes(config.ID) + ctx := context.Background() + _, err := m.ListRoutes(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) - m.ListRoutesFunc = func(sid string) ([]*grpc.Route, error) { + m.ListRoutesFunc = func(ctx context.Context, sid string) ([]*grpc.Route, error) { return nil, nil } - _, err = m.ListRoutes(config.ID) + _, err = m.ListRoutes(ctx, config.ID) assert.NoError(err) // reset m.ListRoutesFunc = nil - _, err = m.ListRoutes(config.ID) + _, err = m.ListRoutes(ctx, config.ID) assert.Error(err) assert.True(IsMockError(err)) } diff --git a/virtcontainers/pkg/vcmock/types.go b/virtcontainers/pkg/vcmock/types.go index 1c7237f13..bf06258fd 100644 --- a/virtcontainers/pkg/vcmock/types.go +++ b/virtcontainers/pkg/vcmock/types.go @@ -6,6 +6,7 @@ package vcmock import ( + "context" "syscall" "github.com/kata-containers/agent/protocols/grpc" @@ -38,38 +39,38 @@ type Container struct { // VCMock is a type that provides an implementation of the VC interface. // It is used for testing. type VCMock struct { - SetLoggerFunc func(logger logrus.FieldLogger) - SetFactoryFunc func(factory vc.Factory) + SetLoggerFunc func(ctx context.Context, logger *logrus.Entry) + SetFactoryFunc func(ctx context.Context, factory vc.Factory) - CreateSandboxFunc func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) - DeleteSandboxFunc func(sandboxID string) (vc.VCSandbox, error) - ListSandboxFunc func() ([]vc.SandboxStatus, error) - FetchSandboxFunc func(sandboxID string) (vc.VCSandbox, error) - PauseSandboxFunc func(sandboxID string) (vc.VCSandbox, error) - ResumeSandboxFunc func(sandboxID string) (vc.VCSandbox, error) - RunSandboxFunc func(sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) - StartSandboxFunc func(sandboxID string) (vc.VCSandbox, error) - StatusSandboxFunc func(sandboxID string) (vc.SandboxStatus, error) - StatsContainerFunc func(sandboxID, containerID string) (vc.ContainerStats, error) - StopSandboxFunc func(sandboxID string) (vc.VCSandbox, error) + CreateSandboxFunc func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) + DeleteSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) + ListSandboxFunc func(ctx context.Context) ([]vc.SandboxStatus, error) + FetchSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) + PauseSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) + ResumeSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) + RunSandboxFunc func(ctx context.Context, sandboxConfig vc.SandboxConfig) (vc.VCSandbox, error) + StartSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) + StatusSandboxFunc func(ctx context.Context, sandboxID string) (vc.SandboxStatus, error) + StatsContainerFunc func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStats, error) + StopSandboxFunc func(ctx context.Context, sandboxID string) (vc.VCSandbox, error) - CreateContainerFunc func(sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) - DeleteContainerFunc func(sandboxID, containerID string) (vc.VCContainer, error) - EnterContainerFunc func(sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) - KillContainerFunc func(sandboxID, containerID string, signal syscall.Signal, all bool) error - StartContainerFunc func(sandboxID, containerID string) (vc.VCContainer, error) - StatusContainerFunc func(sandboxID, containerID string) (vc.ContainerStatus, error) - StopContainerFunc func(sandboxID, containerID string) (vc.VCContainer, error) - ProcessListContainerFunc func(sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) - UpdateContainerFunc func(sandboxID, containerID string, resources specs.LinuxResources) error - PauseContainerFunc func(sandboxID, containerID string) error - ResumeContainerFunc func(sandboxID, containerID string) error + CreateContainerFunc func(ctx context.Context, sandboxID string, containerConfig vc.ContainerConfig) (vc.VCSandbox, vc.VCContainer, error) + DeleteContainerFunc func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) + EnterContainerFunc func(ctx context.Context, sandboxID, containerID string, cmd vc.Cmd) (vc.VCSandbox, vc.VCContainer, *vc.Process, error) + KillContainerFunc func(ctx context.Context, sandboxID, containerID string, signal syscall.Signal, all bool) error + StartContainerFunc func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) + StatusContainerFunc func(ctx context.Context, sandboxID, containerID string) (vc.ContainerStatus, error) + StopContainerFunc func(ctx context.Context, sandboxID, containerID string) (vc.VCContainer, error) + ProcessListContainerFunc func(ctx context.Context, sandboxID, containerID string, options vc.ProcessListOptions) (vc.ProcessList, error) + UpdateContainerFunc func(ctx context.Context, sandboxID, containerID string, resources specs.LinuxResources) error + PauseContainerFunc func(ctx context.Context, sandboxID, containerID string) error + ResumeContainerFunc func(ctx context.Context, sandboxID, containerID string) error - AddDeviceFunc func(sandboxID string, info config.DeviceInfo) (api.Device, error) + AddDeviceFunc func(ctx context.Context, sandboxID string, info config.DeviceInfo) (api.Device, error) - AddInterfaceFunc func(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) - RemoveInterfaceFunc func(sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) - ListInterfacesFunc func(sandboxID string) ([]*grpc.Interface, error) - UpdateRoutesFunc func(sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) - ListRoutesFunc func(sandboxID string) ([]*grpc.Route, error) + AddInterfaceFunc func(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) + RemoveInterfaceFunc func(ctx context.Context, sandboxID string, inf *grpc.Interface) (*grpc.Interface, error) + ListInterfacesFunc func(ctx context.Context, sandboxID string) ([]*grpc.Interface, error) + UpdateRoutesFunc func(ctx context.Context, sandboxID string, routes []*grpc.Route) ([]*grpc.Route, error) + ListRoutesFunc func(ctx context.Context, sandboxID string) ([]*grpc.Route, error) } diff --git a/virtcontainers/qemu.go b/virtcontainers/qemu.go index 6563a00c8..7af48a67d 100644 --- a/virtcontainers/qemu.go +++ b/virtcontainers/qemu.go @@ -17,6 +17,7 @@ import ( govmmQemu "github.com/intel/govmm/qemu" "github.com/kata-containers/runtime/virtcontainers/pkg/uuid" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/kata-containers/runtime/virtcontainers/device/config" @@ -67,6 +68,8 @@ type qemu struct { // fds is a list of file descriptors inherited by QEMU process // they'll be closed once QEMU process is running fds []*os.File + + ctx context.Context } const ( @@ -152,6 +155,9 @@ func (q *qemu) kernelParameters() string { // Adds all capabilities supported by qemu implementation of hypervisor interface func (q *qemu) capabilities() capabilities { + span, _ := q.trace("capabilities") + defer span.Finish() + return q.arch.capabilities() } @@ -176,8 +182,28 @@ func (q *qemu) qemuPath() (string, error) { return p, nil } +func (q *qemu) trace(name string) (opentracing.Span, context.Context) { + if q.ctx == nil { + q.Logger().WithField("type", "bug").Error("trace called before context set") + q.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(q.ctx, name) + + span.SetTag("subsystem", "hypervisor") + span.SetTag("type", "qemu") + + return span, ctx +} + // init intializes the Qemu structure. -func (q *qemu) init(id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error { +func (q *qemu) init(ctx context.Context, id string, hypervisorConfig *HypervisorConfig, vmConfig Resources, storage resourceStorage) error { + // save + q.ctx = ctx + + span, _ := q.trace("init") + defer span.Finish() + err := hypervisorConfig.valid() if err != nil { return err @@ -298,7 +324,7 @@ func (q *qemu) createQmpSocket() ([]govmmQemu.QMPSocket, error) { } q.qmpMonitorCh = qmpChannel{ - ctx: context.Background(), + ctx: q.ctx, path: monitorSockPath, } @@ -364,6 +390,9 @@ func (q *qemu) setupTemplate(knobs *govmmQemu.Knobs, memory *govmmQemu.Memory) g // createSandbox is the Hypervisor sandbox creation implementation for govmmQemu. func (q *qemu) createSandbox() error { + span, _ := q.trace("createSandbox") + defer span.Finish() + machine, err := q.getQemuMachine() if err != nil { return err @@ -467,6 +496,9 @@ func (q *qemu) createSandbox() error { // startSandbox will start the Sandbox's VM. func (q *qemu) startSandbox() error { + span, _ := q.trace("startSandbox") + defer span.Finish() + if q.config.Debug { params := q.arch.kernelParameters(q.config.Debug) strParams := SerializeParams(params, "=") @@ -511,6 +543,9 @@ func (q *qemu) startSandbox() error { // waitSandbox will wait for the Sandbox's VM to be up and running. func (q *qemu) waitSandbox(timeout int) error { + span, _ := q.trace("waitSandbox") + defer span.Finish() + if timeout < 0 { return fmt.Errorf("Invalid timeout %ds", timeout) } @@ -562,6 +597,9 @@ func (q *qemu) waitSandbox(timeout int) error { // stopSandbox will stop the Sandbox's VM. func (q *qemu) stopSandbox() error { + span, _ := q.trace("stopSandbox") + defer span.Finish() + q.Logger().Info("Stopping Sandbox") err := q.qmpSetup() @@ -584,6 +622,9 @@ func (q *qemu) stopSandbox() error { } func (q *qemu) togglePauseSandbox(pause bool) error { + span, _ := q.trace("togglePauseSandbox") + defer span.Finish() + err := q.qmpSetup() if err != nil { return err @@ -864,6 +905,9 @@ func (q *qemu) hotplugDevice(devInfo interface{}, devType deviceType, op operati } func (q *qemu) hotplugAddDevice(devInfo interface{}, devType deviceType) (interface{}, error) { + span, _ := q.trace("hotplugAddDevice") + defer span.Finish() + data, err := q.hotplugDevice(devInfo, devType, addDevice) if err != nil { return data, err @@ -873,6 +917,9 @@ func (q *qemu) hotplugAddDevice(devInfo interface{}, devType deviceType) (interf } func (q *qemu) hotplugRemoveDevice(devInfo interface{}, devType deviceType) (interface{}, error) { + span, _ := q.trace("hotplugRemoveDevice") + defer span.Finish() + data, err := q.hotplugDevice(devInfo, devType, removeDevice) if err != nil { return data, err @@ -1030,15 +1077,24 @@ func (q *qemu) hotplugAddMemory(memDev *memoryDevice) error { } func (q *qemu) pauseSandbox() error { + span, _ := q.trace("pauseSandbox") + defer span.Finish() + return q.togglePauseSandbox(true) } func (q *qemu) resumeSandbox() error { + span, _ := q.trace("resumeSandbox") + defer span.Finish() + return q.togglePauseSandbox(false) } // addDevice will add extra devices to Qemu command line. func (q *qemu) addDevice(devInfo interface{}, devType deviceType) error { + span, _ := q.trace("addDevice") + defer span.Finish() + switch v := devInfo.(type) { case Volume: q.qemuConfig.Devices = q.arch.append9PVolume(q.qemuConfig.Devices, v) @@ -1065,6 +1121,9 @@ func (q *qemu) addDevice(devInfo interface{}, devType deviceType) error { // getSandboxConsole builds the path of the console where we can read // logs coming from the sandbox. func (q *qemu) getSandboxConsole(id string) (string, error) { + span, _ := q.trace("getSandboxConsole") + defer span.Finish() + return utils.BuildSocketPath(RunVMStoragePath, id, consoleSocket) } @@ -1101,6 +1160,9 @@ func (q *qemu) saveSandbox() error { } func (q *qemu) disconnect() { + span, _ := q.trace("disconnect") + defer span.Finish() + q.qmpShutdown() } diff --git a/virtcontainers/qemu_test.go b/virtcontainers/qemu_test.go index 791d299ae..08f9cbf6b 100644 --- a/virtcontainers/qemu_test.go +++ b/virtcontainers/qemu_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "io/ioutil" "os" @@ -86,7 +87,7 @@ func TestQemuInit(t *testing.T) { t.Fatalf("Could not create parent directory %s: %v", parentDir, err) } - if err := q.init(sandbox.id, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { + if err := q.init(context.Background(), sandbox.id, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { t.Fatal(err) } @@ -117,7 +118,7 @@ func TestQemuInitMissingParentDirFail(t *testing.T) { t.Fatal(err) } - if err := q.init(sandbox.id, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { + if err := q.init(context.Background(), sandbox.id, &sandbox.config.HypervisorConfig, sandbox.config.VMConfig, sandbox.storage); err != nil { t.Fatalf("Qemu init() is not expected to fail because of missing parent directory for storage: %v", err) } } diff --git a/virtcontainers/sandbox.go b/virtcontainers/sandbox.go index 1ac8e65a4..9c2d9af28 100644 --- a/virtcontainers/sandbox.go +++ b/virtcontainers/sandbox.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "fmt" "io" "net" @@ -17,6 +18,7 @@ import ( "github.com/containernetworking/plugins/pkg/ns" specs "github.com/opencontainers/runtime-spec/specs-go" + opentracing "github.com/opentracing/opentracing-go" "github.com/sirupsen/logrus" "github.com/kata-containers/agent/protocols/grpc" @@ -360,6 +362,19 @@ type SandboxConfig struct { Stateful bool } +func (s *Sandbox) trace(name string) (opentracing.Span, context.Context) { + if s.ctx == nil { + s.Logger().WithField("type", "bug").Error("trace called before context set") + s.ctx = context.Background() + } + + span, ctx := opentracing.StartSpanFromContext(s.ctx, name) + + span.SetTag("subsystem", "sandbox") + + return span, ctx +} + func (s *Sandbox) startProxy() error { // If the proxy is KataBuiltInProxyType type, it needs to restart the proxy @@ -477,6 +492,8 @@ type Sandbox struct { shmSize uint64 sharePidNs bool stateful bool + + ctx context.Context } // ID returns the sandbox identifier string. @@ -667,7 +684,10 @@ func (s *Sandbox) IOStream(containerID, processID string) (io.WriteCloser, io.Re return c.ioStream(processID) } -func createAssets(sandboxConfig *SandboxConfig) error { +func createAssets(ctx context.Context, sandboxConfig *SandboxConfig) error { + span, _ := trace(ctx, "createAssets") + defer span.Finish() + kernel, err := newAsset(sandboxConfig, kernelAsset) if err != nil { return err @@ -701,12 +721,15 @@ func createAssets(sandboxConfig *SandboxConfig) error { // It will create and store the sandbox structure, and then ask the hypervisor // to physically create that sandbox i.e. starts a VM for that sandbox to eventually // be started. -func createSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { - if err := createAssets(&sandboxConfig); err != nil { +func createSandbox(ctx context.Context, sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { + span, ctx := trace(ctx, "createSandbox") + defer span.Finish() + + if err := createAssets(ctx, &sandboxConfig); err != nil { return nil, err } - s, err := newSandbox(sandboxConfig, factory) + s, err := newSandbox(ctx, sandboxConfig, factory) if err != nil { return nil, err } @@ -746,7 +769,10 @@ func createSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, erro return s, nil } -func newSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { +func newSandbox(ctx context.Context, sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) { + span, ctx := trace(ctx, "newSandbox") + defer span.Finish() + if sandboxConfig.valid() == false { return nil, fmt.Errorf("Invalid sandbox configuration") } @@ -778,6 +804,7 @@ func newSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) shmSize: sandboxConfig.ShmSize, sharePidNs: sandboxConfig.SharePidNs, stateful: sandboxConfig.Stateful, + ctx: ctx, } if err = globalSandboxList.addSandbox(s); err != nil { @@ -791,7 +818,7 @@ func newSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) } }() - if err = s.storage.createAllResources(s); err != nil { + if err = s.storage.createAllResources(ctx, s); err != nil { return nil, err } @@ -801,7 +828,7 @@ func newSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) } }() - if err = s.hypervisor.init(s.id, &sandboxConfig.HypervisorConfig, sandboxConfig.VMConfig, s.storage); err != nil { + if err = s.hypervisor.init(ctx, s.id, &sandboxConfig.HypervisorConfig, sandboxConfig.VMConfig, s.storage); err != nil { return nil, err } @@ -810,7 +837,7 @@ func newSandbox(sandboxConfig SandboxConfig, factory Factory) (*Sandbox, error) } agentConfig := newAgentConfig(sandboxConfig.AgentType, sandboxConfig.AgentConfig) - if err = s.agent.init(s, agentConfig); err != nil { + if err = s.agent.init(ctx, s, agentConfig); err != nil { return nil, err } @@ -823,6 +850,9 @@ func (s *Sandbox) storeSandboxDevices() error { // storeSandbox stores a sandbox config. func (s *Sandbox) storeSandbox() error { + span, _ := s.trace("storeSandbox") + defer span.Finish() + err := s.storage.storeSandboxResource(s.id, configFileType, *(s.config)) if err != nil { return err @@ -839,7 +869,7 @@ func (s *Sandbox) storeSandbox() error { } // fetchSandbox fetches a sandbox config from a sandbox ID and returns a sandbox. -func fetchSandbox(sandboxID string) (sandbox *Sandbox, err error) { +func fetchSandbox(ctx context.Context, sandboxID string) (sandbox *Sandbox, err error) { virtLog.Info("fetch sandbox") if sandboxID == "" { return nil, errNeedSandboxID @@ -857,7 +887,7 @@ func fetchSandbox(sandboxID string) (sandbox *Sandbox, err error) { } // fetchSandbox is not suppose to create new sandbox VM. - sandbox, err = createSandbox(config, nil) + sandbox, err = createSandbox(ctx, config, nil) if err != nil { return nil, fmt.Errorf("failed to create sandbox with config %+v: %v", config, err) } @@ -938,6 +968,9 @@ func (s *Sandbox) Delete() error { } func (s *Sandbox) createNetwork() error { + span, _ := s.trace("createNetwork") + defer span.Finish() + var netNsPath string var netNsCreated bool var networkNS NetworkNamespace @@ -951,7 +984,7 @@ func (s *Sandbox) createNetwork() error { }() // Initialize the network. - netNsPath, netNsCreated, err = s.network.init(s.config.NetworkConfig) + netNsPath, netNsCreated, err = s.network.init(s.ctx, s.config.NetworkConfig) if err != nil { return err } @@ -977,6 +1010,9 @@ func (s *Sandbox) createNetwork() error { } func (s *Sandbox) removeNetwork() error { + span, _ := s.trace("removeNetwork") + defer span.Finish() + return s.network.remove(s, s.networkNS, s.networkNS.NetNsCreated) } @@ -1069,13 +1105,16 @@ func (s *Sandbox) ListRoutes() ([]*grpc.Route, error) { // startVM starts the VM. func (s *Sandbox) startVM() error { + span, ctx := s.trace("startVM") + defer span.Finish() + s.Logger().Info("Starting VM") // FIXME: This would break cached VMs. We need network hotplug and move // oci hooks and netns handling to cli. See #273. if err := s.network.run(s.networkNS.NetNsPath, func() error { if s.factory != nil { - vm, err := s.factory.GetVM(VMConfig{ + vm, err := s.factory.GetVM(ctx, VMConfig{ HypervisorType: s.config.HypervisorType, HypervisorConfig: s.config.HypervisorConfig, AgentType: s.config.AgentType, @@ -1109,6 +1148,9 @@ func (s *Sandbox) startVM() error { // stopVM: stop the sandbox's VM func (s *Sandbox) stopVM() error { + span, _ := s.trace("stopVM") + defer span.Finish() + return s.hypervisor.stopSandbox() } @@ -1291,6 +1333,9 @@ func (s *Sandbox) StatsContainer(containerID string) (ContainerStats, error) { // createContainers registers all containers to the proxy, create the // containers in the guest and starts one shim per container. func (s *Sandbox) createContainers() error { + span, _ := s.trace("createContainers") + defer span.Finish() + for _, contConfig := range s.config.Containers { newContainer, err := createContainer(s, contConfig) if err != nil { @@ -1330,6 +1375,9 @@ func (s *Sandbox) start() error { // stop stops a sandbox. The containers that are making the sandbox // will be destroyed. func (s *Sandbox) stop() error { + span, _ := s.trace("stop") + defer span.Finish() + if err := s.state.validTransition(s.state.State, StateStopped); err != nil { return err } @@ -1510,7 +1558,10 @@ func (s *Sandbox) deleteContainersState() error { // togglePauseSandbox pauses a sandbox if pause is set to true, else it resumes // it. -func togglePauseSandbox(sandboxID string, pause bool) (*Sandbox, error) { +func togglePauseSandbox(ctx context.Context, sandboxID string, pause bool) (*Sandbox, error) { + span, ctx := trace(ctx, "togglePauseSandbox") + defer span.Finish() + if sandboxID == "" { return nil, errNeedSandbox } @@ -1522,7 +1573,7 @@ func togglePauseSandbox(sandboxID string, pause bool) (*Sandbox, error) { defer unlockSandbox(lockFile) // Fetch the sandbox from storage and create it. - s, err := fetchSandbox(sandboxID) + s, err := fetchSandbox(ctx, sandboxID) if err != nil { return nil, err } @@ -1544,6 +1595,9 @@ func togglePauseSandbox(sandboxID string, pause bool) (*Sandbox, error) { // HotplugAddDevice is used for add a device to sandbox // Sandbox implement DeviceReceiver interface from device/api/interface.go func (s *Sandbox) HotplugAddDevice(device api.Device, devType config.DeviceType) error { + span, _ := s.trace("HotplugAddDevice") + defer span.Finish() + switch devType { case config.DeviceVFIO: vfioDevices, ok := device.GetDeviceInfo().([]*config.VFIODev) diff --git a/virtcontainers/sandbox_test.go b/virtcontainers/sandbox_test.go index 24425c9f2..fc3eb2652 100644 --- a/virtcontainers/sandbox_test.go +++ b/virtcontainers/sandbox_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -51,7 +52,7 @@ func testCreateSandbox(t *testing.T, id string, Containers: containers, } - sandbox, err := createSandbox(sconfig, nil) + sandbox, err := createSandbox(context.Background(), sconfig, nil) if err != nil { return nil, fmt.Errorf("Could not create sandbox: %s", err) } @@ -585,7 +586,7 @@ func TestSandboxSetSandboxAndContainerState(t *testing.T) { } // force state to be read from disk - p2, err := fetchSandbox(p.ID()) + p2, err := fetchSandbox(context.Background(), p.ID()) if err != nil { t.Fatalf("Failed to fetch sandbox %v: %v", p.ID(), err) } @@ -1184,7 +1185,7 @@ func TestSandboxAttachDevicesVFIO(t *testing.T) { } containers[c.id].sandbox = &sandbox - err = sandbox.storage.createAllResources(&sandbox) + err = sandbox.storage.createAllResources(context.Background(), &sandbox) assert.Nil(t, err, "Error while create all resources for sandbox") err = sandbox.storeSandboxDevices() @@ -1226,7 +1227,7 @@ func TestSandboxCreateAssets(t *testing.T) { HypervisorConfig: hc, } - err = createAssets(p) + err = createAssets(context.Background(), p) assert.Nil(err) a, ok := p.HypervisorConfig.customAssets[kernelAsset] @@ -1242,7 +1243,7 @@ func TestSandboxCreateAssets(t *testing.T) { HypervisorConfig: hc, } - err = createAssets(p) + err = createAssets(context.Background(), p) assert.NotNil(err) } diff --git a/virtcontainers/syscall_test.go b/virtcontainers/syscall_test.go index 1eb8febdb..b13608843 100644 --- a/virtcontainers/syscall_test.go +++ b/virtcontainers/syscall_test.go @@ -7,6 +7,7 @@ package virtcontainers import ( + "context" "os" "path/filepath" "syscall" @@ -17,7 +18,7 @@ func TestBindMountInvalidSourceSymlink(t *testing.T) { source := filepath.Join(testDir, "fooFile") os.Remove(source) - err := bindMount(source, "", false) + err := bindMount(context.Background(), source, "", false) if err == nil { t.Fatal() } @@ -39,7 +40,7 @@ func TestBindMountFailingMount(t *testing.T) { t.Fatal(err) } - err = bindMount(source, "", false) + err = bindMount(context.Background(), source, "", false) if err == nil { t.Fatal() } @@ -66,7 +67,7 @@ func TestBindMountSuccessful(t *testing.T) { t.Fatal(err) } - err = bindMount(source, dest, false) + err = bindMount(context.Background(), source, dest, false) if err != nil { t.Fatal(err) } @@ -95,7 +96,7 @@ func TestBindMountReadonlySuccessful(t *testing.T) { t.Fatal(err) } - err = bindMount(source, dest, true) + err = bindMount(context.Background(), source, dest, true) if err != nil { t.Fatal(err) } diff --git a/virtcontainers/virtcontainers_test.go b/virtcontainers/virtcontainers_test.go index c85a42256..d752f92f7 100644 --- a/virtcontainers/virtcontainers_test.go +++ b/virtcontainers/virtcontainers_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "flag" "fmt" "io/ioutil" @@ -73,7 +74,7 @@ func TestMain(m *testing.M) { logger.Logger.Level = logrus.DebugLevel } } - SetLogger(logger) + SetLogger(context.Background(), logger) testDir, err = ioutil.TempDir("", "vc-tmp-") if err != nil { diff --git a/virtcontainers/vm.go b/virtcontainers/vm.go index aa42d8006..7ffa47c61 100644 --- a/virtcontainers/vm.go +++ b/virtcontainers/vm.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "os" "path/filepath" @@ -41,7 +42,7 @@ func (c *VMConfig) Valid() error { } // NewVM creates a new VM based on provided VMConfig. -func NewVM(config VMConfig) (*VM, error) { +func NewVM(ctx context.Context, config VMConfig) (*VM, error) { hypervisor, err := newHypervisor(config.HypervisorType) if err != nil { return nil, err @@ -61,7 +62,7 @@ func NewVM(config VMConfig) (*VM, error) { } }() - if err = hypervisor.init(id, &config.HypervisorConfig, Resources{}, &filesystem{}); err != nil { + if err = hypervisor.init(ctx, id, &config.HypervisorConfig, Resources{}, &filesystem{}); err != nil { return nil, err } diff --git a/virtcontainers/vm_test.go b/virtcontainers/vm_test.go index 15c16f8ba..8ecbd5c7d 100644 --- a/virtcontainers/vm_test.go +++ b/virtcontainers/vm_test.go @@ -6,6 +6,7 @@ package virtcontainers import ( + "context" "io/ioutil" "testing" @@ -25,12 +26,14 @@ func TestNewVM(t *testing.T) { ImagePath: testDir, } + ctx := context.Background() + var vm *VM - _, err := NewVM(config) + _, err := NewVM(ctx, config) assert.Error(err) config.HypervisorConfig = hyperConfig - vm, err = NewVM(config) + vm, err = NewVM(ctx, config) assert.Nil(err) // VM operations @@ -55,15 +58,15 @@ func TestNewVM(t *testing.T) { // template VM config.HypervisorConfig.BootFromTemplate = true - _, err = NewVM(config) + _, err = NewVM(ctx, config) assert.Error(err) config.HypervisorConfig.MemoryPath = testDir - _, err = NewVM(config) + _, err = NewVM(ctx, config) assert.Error(err) config.HypervisorConfig.DevicesStatePath = testDir - _, err = NewVM(config) + _, err = NewVM(ctx, config) assert.Nil(err) }