package agent import ( "context" "os" "time" "github.com/containerd/containerd/containers" "edge-infra.dev/pkg/lib/uuid" cc "edge-infra.dev/pkg/sds/devices/agent/common" "edge-infra.dev/pkg/sds/devices/agent/metrics" dsv1 "edge-infra.dev/pkg/sds/devices/k8s/apis/v1" "edge-infra.dev/pkg/sds/devices/logger" ) type deviceConfigJob interface { Run(ctx context.Context) } type job struct { allDeviceClasses map[string]*dsv1.DeviceClass containers map[string]*containers.Container postHookFns []func(context.Context) } func newJob(containers map[string]*containers.Container, postHookFns []func(context.Context), allDeviceClasses map[string]*dsv1.DeviceClass) deviceConfigJob { return &job{ allDeviceClasses: allDeviceClasses, containers: containers, postHookFns: postHookFns, } } func (j job) Run(ctx context.Context) { j.applyDeviceConfigurationUpdate(ctx) } // applyDeviceConfigurationUpdate will apply cgroups to the containers and runs posthook events func (j job) applyDeviceConfigurationUpdate(ctx context.Context) { requestID := uuid.New().UUID log := logger.FromContext(ctx).With("requestId", requestID) ctx = logger.IntoContext(ctx, log) changedContainerNames := []string{} configUpdate := func(ctx context.Context) { log.Debug("device request started") for _, ctr := range j.containers { ctrName := ctr.Labels[cc.AnnContainerName] changedContainerNames = append(changedContainerNames, ctrName) ApplyCgroupsToContainer(ctx, requestID, ctr, j.allDeviceClasses) } for _, postHookFn := range j.postHookFns { postHookFn(ctx) } log.Debug("device request finished", "containers", changedContainerNames) } duration := timeConfigUpdate(ctx, configUpdate) if len(changedContainerNames) != 0 { log.Info("applied device update to containers", "updated containers", changedContainerNames, "time", duration) } } // timeConfigUpdate will time how long it takes to process the container configuration update func timeConfigUpdate(ctx context.Context, fn func(ctx context.Context)) string { startTime := time.Now() fn(ctx) endTime := time.Now() diff := endTime.Sub(startTime) metrics.RecordDuration(nodeName(), diff.Seconds()) return diff.String() } func nodeName() string { return os.Getenv("HOSTNAME") }