//go:build linux

/*
Copyright 2023 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package stats

import (
	"fmt"
	"time"

	cadvisorapiv2 "github.com/google/cadvisor/info/v2"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	utilfeature "k8s.io/apiserver/pkg/util/feature"
	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
	"k8s.io/klog/v2"
	statsapi "k8s.io/kubelet/pkg/apis/stats/v1alpha1"
	"k8s.io/kubernetes/pkg/features"
)

func (p *criStatsProvider) addCRIPodContainerStats(
	logger klog.Logger,
	criSandboxStat *runtimeapi.PodSandboxStats,
	ps *statsapi.PodStats,
	fsIDtoInfo map[string]*cadvisorapiv2.FsInfo,
	containerMap map[string]*runtimeapi.Container,
	podSandbox *runtimeapi.PodSandbox,
	rootFsInfo *cadvisorapiv2.FsInfo, updateCPUNanoCoreUsage bool) error {
	for _, criContainerStat := range criSandboxStat.Linux.Containers {
		container, found := containerMap[criContainerStat.Attributes.Id]
		if !found {
			continue
		}
		// Fill available stats for full set of required pod stats
		cs, err := p.makeContainerStats(logger, criContainerStat, container, rootFsInfo, fsIDtoInfo, podSandbox.GetMetadata(),
			updateCPUNanoCoreUsage)
		if err != nil {
			return fmt.Errorf("make container stats: %w", err)
		}
		ps.Containers = append(ps.Containers, *cs)
	}
	return nil
}

// addCRIPodContainerCPUAndMemoryStats adds container CPU and memory stats from CRI to the PodStats.
// This is a lighter-weight version of addCRIPodContainerStats that only populates CPU and memory
// stats needed for the resource metrics endpoint.
func (p *criStatsProvider) addCRIPodContainerCPUAndMemoryStats(
	criSandboxStat *runtimeapi.PodSandboxStats,
	ps *statsapi.PodStats,
	containerMap map[string]*runtimeapi.Container) {
	if criSandboxStat == nil || criSandboxStat.Linux == nil {
		return
	}
	for _, criContainerStat := range criSandboxStat.Linux.Containers {
		container, found := containerMap[criContainerStat.Attributes.Id]
		if !found {
			continue
		}
		// Fill available CPU and memory stats for resource metrics
		cs := p.makeContainerCPUAndMemoryStats(criContainerStat, time.Unix(0, container.CreatedAt), true)
		ps.Containers = append(ps.Containers, *cs)
	}
}

func addCRIPodNetworkStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {
	if criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Network == nil {
		return
	}
	criNetwork := criPodStat.Linux.Network
	iStats := statsapi.NetworkStats{
		Time:           metav1.NewTime(time.Unix(0, criNetwork.Timestamp)),
		InterfaceStats: criInterfaceToSummary(criNetwork.DefaultInterface),
		Interfaces:     make([]statsapi.InterfaceStats, 0, len(criNetwork.Interfaces)),
	}
	for _, iface := range criNetwork.Interfaces {
		iStats.Interfaces = append(iStats.Interfaces, criInterfaceToSummary(iface))
	}
	ps.Network = &iStats
}

func addCRIPodMemoryStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {
	if criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Memory == nil {
		return
	}
	criMemory := criPodStat.Linux.Memory
	ps.Memory = &statsapi.MemoryStats{
		Time:            metav1.NewTime(time.Unix(0, criMemory.Timestamp)),
		AvailableBytes:  valueOfUInt64Value(criMemory.AvailableBytes),
		UsageBytes:      valueOfUInt64Value(criMemory.UsageBytes),
		WorkingSetBytes: valueOfUInt64Value(criMemory.WorkingSetBytes),
		RSSBytes:        valueOfUInt64Value(criMemory.RssBytes),
		PageFaults:      valueOfUInt64Value(criMemory.PageFaults),
		MajorPageFaults: valueOfUInt64Value(criMemory.MajorPageFaults),
		PSI:             makePSIStats(criMemory.Psi),
	}
}

func addCRIPodCPUStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {
	if criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Cpu == nil {
		return
	}
	criCPU := criPodStat.Linux.Cpu
	ps.CPU = &statsapi.CPUStats{
		Time:                 metav1.NewTime(time.Unix(0, criCPU.Timestamp)),
		UsageNanoCores:       valueOfUInt64Value(criCPU.UsageNanoCores),
		UsageCoreNanoSeconds: valueOfUInt64Value(criCPU.UsageCoreNanoSeconds),
		PSI:                  makePSIStats(criCPU.Psi),
	}
}

func addCRIPodIOStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {
	if !utilfeature.DefaultFeatureGate.Enabled(features.KubeletPSI) {
		return
	}
	if criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Io == nil {
		return
	}
	criIO := criPodStat.Linux.Io
	ps.IO = &statsapi.IOStats{
		Time: metav1.NewTime(time.Unix(0, criIO.Timestamp)),
		PSI:  makePSIStats(criIO.Psi),
	}
}

func addCRIPodProcessStats(ps *statsapi.PodStats, criPodStat *runtimeapi.PodSandboxStats) {
	if criPodStat == nil || criPodStat.Linux == nil || criPodStat.Linux.Process == nil {
		return
	}
	ps.ProcessStats = &statsapi.ProcessStats{
		ProcessCount: valueOfUInt64Value(criPodStat.Linux.Process.ProcessCount),
	}
}

// listContainerNetworkStats returns the network stats of all the running containers.
// It should return (nil, nil) for platforms other than Windows.
func (p *criStatsProvider) listContainerNetworkStats(klog.Logger) (map[string]*statsapi.NetworkStats, error) {
	return nil, nil
}
