github.com/google/cadvisor@v0.49.1/utils/cloudinfo/aws/aws.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 cloudinfo 16 17 import ( 18 "os" 19 "strings" 20 21 "github.com/aws/aws-sdk-go/aws" 22 "github.com/aws/aws-sdk-go/aws/ec2metadata" 23 "github.com/aws/aws-sdk-go/aws/session" 24 25 info "github.com/google/cadvisor/info/v1" 26 "github.com/google/cadvisor/utils/cloudinfo" 27 ) 28 29 const ( 30 productVerFileName = "/sys/class/dmi/id/product_version" 31 biosVerFileName = "/sys/class/dmi/id/bios_vendor" 32 systemdOSReleaseFileName = "/etc/os-release" 33 amazon = "amazon" 34 ) 35 36 func init() { 37 cloudinfo.RegisterCloudProvider(info.AWS, &provider{}) 38 } 39 40 type provider struct{} 41 42 var _ cloudinfo.CloudProvider = provider{} 43 44 func (provider) IsActiveProvider() bool { 45 return fileContainsAmazonIdentifier(productVerFileName) || 46 fileContainsAmazonIdentifier(biosVerFileName) || 47 fileContainsAmazonIdentifier(systemdOSReleaseFileName) 48 } 49 50 func fileContainsAmazonIdentifier(filename string) bool { 51 fileContent, err := os.ReadFile(filename) 52 if err != nil { 53 return false 54 } 55 56 return strings.Contains(string(fileContent), amazon) 57 } 58 59 func getAwsMetadata(name string) string { 60 sess, err := session.NewSession(&aws.Config{}) 61 if err != nil { 62 return info.UnknownInstance 63 } 64 client := ec2metadata.New(sess) 65 data, err := client.GetMetadata(name) 66 if err != nil { 67 return info.UnknownInstance 68 } 69 return data 70 } 71 72 func (provider) GetInstanceType() info.InstanceType { 73 return info.InstanceType(getAwsMetadata("instance-type")) 74 } 75 76 func (provider) GetInstanceID() info.InstanceID { 77 return info.InstanceID(getAwsMetadata("instance-id")) 78 }