github.com/google/cloudprober@v0.11.3/targets/gce/gce_utils.go (about) 1 // Copyright 2017-2019 The Cloudprober Authors. 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 "context" 19 "errors" 20 "fmt" 21 "strings" 22 23 "github.com/golang/protobuf/proto" 24 rdspb "github.com/google/cloudprober/rds/proto" 25 configpb "github.com/google/cloudprober/targets/gce/proto" 26 dnsRes "github.com/google/cloudprober/targets/resolver" 27 "golang.org/x/oauth2/google" 28 compute "google.golang.org/api/compute/v1" 29 ) 30 31 // defaultComputeService returns the compute service to use for the GCE API 32 // calls. 33 func defaultComputeService(apiVersion string) (*compute.Service, error) { 34 client, err := google.DefaultClient(context.TODO(), compute.ComputeScope) 35 if err != nil { 36 return nil, err 37 } 38 cs, err := compute.New(client) 39 if err != nil { 40 return nil, err 41 } 42 cs.BasePath = "https://www.googleapis.com/compute/" + apiVersion + "/projects/" 43 return cs, nil 44 } 45 46 // Utility function to parse "<key>:<value>" style strings into RDS style 47 // label filters. 48 func parseLabels(sl []string) ([]*rdspb.Filter, error) { 49 var result []*rdspb.Filter 50 for _, s := range sl { 51 tokens := strings.Split(s, ":") 52 if len(tokens) != 2 { 53 return nil, fmt.Errorf("invalid label definition: %s", s) 54 } 55 result = append(result, &rdspb.Filter{ 56 Key: proto.String("labels." + tokens[0]), 57 Value: proto.String(tokens[1]), 58 }) 59 } 60 return result, nil 61 } 62 63 // Instances resource type related utilities. 64 // ======================================== 65 66 func instancesIPConfig(ipb *configpb.Instances) *rdspb.IPConfig { 67 ipTypeMap := map[string]rdspb.IPConfig_IPType{ 68 "PRIVATE": rdspb.IPConfig_DEFAULT, 69 "PUBLIC": rdspb.IPConfig_PUBLIC, 70 "ALIAS": rdspb.IPConfig_ALIAS, 71 } 72 73 return &rdspb.IPConfig{ 74 NicIndex: proto.Int32(ipb.GetNetworkInterface().GetIndex()), 75 IpType: ipTypeMap[ipb.GetNetworkInterface().GetIpType().String()].Enum(), 76 } 77 } 78 79 func verifyInstancesConfig(ipb *configpb.Instances, globalResolver *dnsRes.Resolver) error { 80 if ipb.GetUseDnsToResolve() { 81 if ipb.GetNetworkInterface() != nil { 82 return errors.New("network_intf and use_dns_to_resolve are mutually exclusive") 83 } 84 if globalResolver == nil { 85 return errors.New("use_dns_to_resolve configured, but globalResolver is nil") 86 } 87 } 88 return nil 89 }