github.com/google/cadvisor@v0.49.1/utils/cpuload/netlink/reader.go (about)

     1  // Copyright 2015 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package netlink
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  
    21  	info "github.com/google/cadvisor/info/v1"
    22  
    23  	"k8s.io/klog/v2"
    24  )
    25  
    26  type NetlinkReader struct {
    27  	familyID uint16
    28  	conn     *Connection
    29  }
    30  
    31  func New() (*NetlinkReader, error) {
    32  	conn, err := newConnection()
    33  	if err != nil {
    34  		return nil, fmt.Errorf("failed to create a new connection: %s", err)
    35  	}
    36  
    37  	id, err := getFamilyID(conn)
    38  	if err != nil {
    39  		return nil, fmt.Errorf("failed to get netlink family id for task stats: %s", err)
    40  	}
    41  	klog.V(4).Infof("Family id for taskstats: %d", id)
    42  	return &NetlinkReader{
    43  		familyID: id,
    44  		conn:     conn,
    45  	}, nil
    46  }
    47  
    48  func (r *NetlinkReader) Stop() {
    49  	if r.conn != nil {
    50  		r.conn.Close()
    51  	}
    52  }
    53  
    54  func (r *NetlinkReader) Start() error {
    55  	// We do the start setup for netlink in New(). Nothing to do here.
    56  	return nil
    57  }
    58  
    59  // Returns instantaneous number of running tasks in a group.
    60  // Caller can use historical data to calculate cpu load.
    61  // path is an absolute filesystem path for a container under the CPU cgroup hierarchy.
    62  // NOTE: non-hierarchical load is returned. It does not include load for subcontainers.
    63  func (r *NetlinkReader) GetCpuLoad(name string, path string) (info.LoadStats, error) {
    64  	if len(path) == 0 {
    65  		return info.LoadStats{}, fmt.Errorf("cgroup path can not be empty")
    66  	}
    67  
    68  	cfd, err := os.Open(path)
    69  	if err != nil {
    70  		return info.LoadStats{}, fmt.Errorf("failed to open cgroup path %s: %q", path, err)
    71  	}
    72  	defer cfd.Close()
    73  
    74  	stats, err := getLoadStats(r.familyID, cfd, r.conn)
    75  	if err != nil {
    76  		return info.LoadStats{}, err
    77  	}
    78  	klog.V(4).Infof("Task stats for %q: %+v", path, stats)
    79  	return stats, nil
    80  }