Repository: containerd/containerd
File: internal/cri/server/sandbox_stats_windows.go (Go)

Code before:
		ProcessCount: &runtime.UInt64Value{Value: pidCount},
	}

	c.saveSandBoxMetrics(podSandboxStats.Attributes.Id, podSandboxStats)

	return podSandboxStats, nil
}

func convertMetricsToWindowsStats(metrics []*types.Metric, sandbox sandboxstore.Sandbox) (map[string]*wstats.Statistics, error) {
	isHostProcess := sandbox.Config.GetWindows().GetSecurityContext().GetHostProcess()

	statsMap := make(map[string]*wstats.Statistics)
	for _, stat := range metrics {
		containerStatsData, err := typeurl.UnmarshalAny(stat.Data)
		if err != nil {
			return nil, fmt.Errorf("failed to extract metrics for container with id %s: %w", stat.ID, err)
		}

		// extract the metrics if available for this container
		// containerStatsData can be nil for pods that don't have an actual podsandbox container such as HPC
		// In the case of HostProcess sandbox container we will use the nil value for the statsmap which is used later
		// otherwise return an error since we should have gotten stats
		containerStats, ok := containerStatsData.(*wstats.Statistics)
		if !ok && (!isHostProcess || sandbox.ID != stat.ID) {
			return nil, fmt.Errorf("failed to extract metrics for container with id %s: %w", stat.ID, err)
		}

		statsMap[stat.ID] = containerStats
	}
	return statsMap, nil
}

func (c *criService) toPodSandboxStats(sandbox sandboxstore.Sandbox, statsMap map[string]*wstats.Statistics, containers []containerstore.Container, timestamp time.Time) (*runtime.WindowsContainerStats, []*runtime.WindowsContainerStats, error) {
	podMetric, ok := statsMap[sandbox.ID]
	if !ok {
		return nil, nil, fmt.Errorf("failed to find container metric for pod with id %s", sandbox.ID)
	}

	ociRuntime, err := c.config.GetSandboxRuntime(sandbox.Config, sandbox.RuntimeHandler)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get runtimeHandler %q: %w", sandbox.RuntimeHandler, err)
	}
	snapshotter := c.RuntimeSnapshotter(ctrdutil.NamespacedContext(), ociRuntime)

	podRuntimeStats, err := c.convertToCRIStats(podMetric)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to covert container metrics for sandbox with id %s: %w", sandbox.ID, err)
	}

	windowsContainerStats := make([]*runtime.WindowsContainerStats, 0, len(statsMap))
	for _, cntr := range containers {

Review comment (suggestion):
Probably not for this PR, but this logic seems complicated, and somewhat err-prone (at least, I can't get my head around the correctness at a glance). Could probably use a rewrite to flip some of the conditionals.

Because looking at the logic; if it's `!ok`, but any of the other conditions are true, then we set `statsMap[stat.ID] = containerStats` below (setting it to .. `nil` - is that intentional / correct ?)

Code after:
		ProcessCount: &runtime.UInt64Value{Value: pidCount},
	}

	c.saveSandBoxMetrics(podSandboxStats.Attributes.Id, podSandboxStats)

	return podSandboxStats, nil
}

func convertMetricsToWindowsStats(metrics []*types.Metric, sandbox sandboxstore.Sandbox) (map[string]*wstats.Statistics, error) {
	isHostProcess := sandbox.Config.GetWindows().GetSecurityContext().GetHostProcess()

	statsMap := make(map[string]*wstats.Statistics)
	for _, stat := range metrics {
		containerStatsData, err := typeurl.UnmarshalAny(stat.Data)
		if err != nil {
			return nil, fmt.Errorf("failed to extract metrics for container with id %s: %w", stat.ID, err)
		}

		// extract the metrics if available for this container
		// containerStatsData can be nil for pods that don't have an actual podsandbox container such as HPC
		// In the case of HostProcess sandbox container we will use the nil value for the statsmap which is used later
		// otherwise return an error since we should have gotten stats
		containerStats, ok := containerStatsData.(*wstats.Statistics)
		//nolint:staticcheck // QF1001: could apply De Morgan's law (staticcheck)
		if !ok && !(isHostProcess && sandbox.ID == stat.ID) {
			return nil, fmt.Errorf("failed to extract metrics for container with id %s: %w", stat.ID, err)
		}

		statsMap[stat.ID] = containerStats
	}
	return statsMap, nil
}

func (c *criService) toPodSandboxStats(sandbox sandboxstore.Sandbox, statsMap map[string]*wstats.Statistics, containers []containerstore.Container, timestamp time.Time) (*runtime.WindowsContainerStats, []*runtime.WindowsContainerStats, error) {
	podMetric, ok := statsMap[sandbox.ID]
	if !ok {
		return nil, nil, fmt.Errorf("failed to find container metric for pod with id %s", sandbox.ID)
	}

	ociRuntime, err := c.config.GetSandboxRuntime(sandbox.Config, sandbox.RuntimeHandler)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get runtimeHandler %q: %w", sandbox.RuntimeHandler, err)
	}
	snapshotter := c.RuntimeSnapshotter(ctrdutil.NamespacedContext(), ociRuntime)

	podRuntimeStats, err := c.convertToCRIStats(podMetric)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to covert container metrics for sandbox with id %s: %w", sandbox.ID, err)
	}

	windowsContainerStats := make([]*runtime.WindowsContainerStats, 0, len(statsMap))