github.com/google/cadvisor@v0.49.1/utils/cloudinfo/gce/gce.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 gce
    16  
    17  import (
    18  	"os"
    19  	"strings"
    20  
    21  	info "github.com/google/cadvisor/info/v1"
    22  	"github.com/google/cadvisor/utils/cloudinfo"
    23  
    24  	"cloud.google.com/go/compute/metadata"
    25  	"k8s.io/klog/v2"
    26  )
    27  
    28  const (
    29  	gceProductName = "/sys/class/dmi/id/product_name"
    30  	google         = "Google"
    31  )
    32  
    33  func init() {
    34  	cloudinfo.RegisterCloudProvider(info.GCE, &provider{})
    35  }
    36  
    37  type provider struct{}
    38  
    39  var _ cloudinfo.CloudProvider = provider{}
    40  
    41  func (provider) IsActiveProvider() bool {
    42  	data, err := os.ReadFile(gceProductName)
    43  	if err != nil {
    44  		klog.V(2).Infof("Error while reading product_name: %v", err)
    45  		return false
    46  	}
    47  	return strings.Contains(string(data), google)
    48  }
    49  
    50  func (provider) GetInstanceType() info.InstanceType {
    51  	machineType, err := metadata.Get("instance/machine-type")
    52  	if err != nil {
    53  		return info.UnknownInstance
    54  	}
    55  
    56  	responseParts := strings.Split(machineType, "/") // Extract the instance name from the machine type.
    57  	return info.InstanceType(responseParts[len(responseParts)-1])
    58  }
    59  
    60  func (provider) GetInstanceID() info.InstanceID {
    61  	instanceID, err := metadata.Get("instance/id")
    62  	if err != nil {
    63  		return info.UnknownInstance
    64  	}
    65  	return info.InstanceID(info.InstanceType(instanceID))
    66  }