Best Syzkaller code snippet using gce.Error
mig_info_provider_test.go
Source:mig_info_provider_test.go
...118 cache: &GceCache{119 instancesToMig: map[GceRef]GceRef{instanceRef: mig.GceRef()},120 },121 expectedMig: nil,122 expectedErr: fmt.Errorf("instance %v belongs to unregistered mig %v", instanceRef, mig.GceRef()),123 expectedCachedMigRef: mig.GceRef(),124 expectedCached: true,125 },126 {127 name: "instance mig unknown in cache",128 cache: &GceCache{129 instancesFromUnknownMig: map[GceRef]bool{instanceRef: true},130 },131 expectedCachedMigUnknown: true,132 },133 {134 name: "mig from cache fill",135 cache: &GceCache{136 migs: map[GceRef]Mig{mig.GceRef(): mig},...
gce_cloud_provider_test.go
Source:gce_cloud_provider_test.go
...37 return args.Bool(0)38}39func (m *gceManagerMock) GetMigSize(mig *Mig) (int64, error) {40 args := m.Called(mig)41 return args.Get(0).(int64), args.Error(1)42}43func (m *gceManagerMock) SetMigSize(mig *Mig, size int64) error {44 args := m.Called(mig, size)45 return args.Error(0)46}47func (m *gceManagerMock) DeleteInstances(instances []*GceRef) error {48 args := m.Called(instances)49 return args.Error(0)50}51func (m *gceManagerMock) GetMigForInstance(instance *GceRef) (*Mig, error) {52 args := m.Called(instance)53 return args.Get(0).(*Mig), args.Error(1)54}55func (m *gceManagerMock) GetMigNodes(mig *Mig) ([]string, error) {56 args := m.Called(mig)57 return args.Get(0).([]string), args.Error(1)58}59func (m *gceManagerMock) Refresh() error {60 args := m.Called()61 return args.Error(0)62}63func (m *gceManagerMock) Cleanup() error {64 args := m.Called()65 return args.Error(0)66}67func (m *gceManagerMock) getMigs() []*migInformation {68 args := m.Called()69 return args.Get(0).([]*migInformation)70}71func (m *gceManagerMock) createNodePool(mig *Mig) error {72 args := m.Called(mig)73 return args.Error(0)74}75func (m *gceManagerMock) deleteNodePool(toBeRemoved *Mig) error {76 args := m.Called(toBeRemoved)77 return args.Error(0)78}79func (m *gceManagerMock) getLocation() string {80 args := m.Called()81 return args.String(0)82}83func (m *gceManagerMock) getProjectId() string {84 args := m.Called()85 return args.String(0)86}87func (m *gceManagerMock) getMode() GcpCloudProviderMode {88 args := m.Called()89 return args.Get(0).(GcpCloudProviderMode)90}91func (m *gceManagerMock) getTemplates() *templateBuilder {92 args := m.Called()93 return args.Get(0).(*templateBuilder)94}95func (m *gceManagerMock) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {96 args := m.Called()97 return args.Get(0).(*cloudprovider.ResourceLimiter), args.Error(1)98}99func (m *gceManagerMock) findMigsNamed(name *regexp.Regexp) ([]string, error) {100 args := m.Called()101 return args.Get(0).([]string), args.Error(1)102}103func TestBuildGceCloudProvider(t *testing.T) {104 gceManagerMock := &gceManagerMock{}105 resourceLimiter := cloudprovider.NewResourceLimiter(106 map[string]int64{cloudprovider.ResourceNameCores: 1, cloudprovider.ResourceNameMemory: 10000000},107 map[string]int64{cloudprovider.ResourceNameCores: 10, cloudprovider.ResourceNameMemory: 100000000})108 provider, err := BuildGceCloudProvider(gceManagerMock, resourceLimiter)109 assert.NoError(t, err)110 assert.NotNil(t, provider)111}112func TestNodeGroups(t *testing.T) {113 gceManagerMock := &gceManagerMock{}114 gce := &GceCloudProvider{115 gceManager: gceManagerMock,116 }117 mig := &migInformation{config: &Mig{GceRef: GceRef{Name: "ng1"}}}118 gceManagerMock.On("getMigs").Return([]*migInformation{mig}).Once()119 result := gce.NodeGroups()120 assert.Equal(t, []cloudprovider.NodeGroup{mig.config}, result)121 mock.AssertExpectationsForObjects(t, gceManagerMock)122}123func TestNodeGroupForNode(t *testing.T) {124 gceManagerMock := &gceManagerMock{}125 gce := &GceCloudProvider{126 gceManager: gceManagerMock,127 }128 n := BuildTestNode("n1", 1000, 1000)129 n.Spec.ProviderID = "gce://project1/us-central1-b/n1"130 mig := Mig{GceRef: GceRef{Name: "ng1"}}131 gceManagerMock.On("GetMigForInstance", mock.AnythingOfType("*gce.GceRef")).Return(&mig, nil).Once()132 nodeGroup, err := gce.NodeGroupForNode(n)133 assert.NoError(t, err)134 assert.Equal(t, mig, *reflect.ValueOf(nodeGroup).Interface().(*Mig))135 mock.AssertExpectationsForObjects(t, gceManagerMock)136}137func TestGetResourceLimiter(t *testing.T) {138 gceManagerMock := &gceManagerMock{}139 resourceLimiter := cloudprovider.NewResourceLimiter(140 map[string]int64{cloudprovider.ResourceNameCores: 1, cloudprovider.ResourceNameMemory: 10000000},141 map[string]int64{cloudprovider.ResourceNameCores: 10, cloudprovider.ResourceNameMemory: 100000000})142 gce := &GceCloudProvider{143 gceManager: gceManagerMock,144 resourceLimiterFromFlags: resourceLimiter,145 }146 // Return default.147 gceManagerMock.On("GetResourceLimiter").Return((*cloudprovider.ResourceLimiter)(nil), nil).Once()148 returnedResourceLimiter, err := gce.GetResourceLimiter()149 assert.NoError(t, err)150 assert.Equal(t, resourceLimiter, returnedResourceLimiter)151 // Return for GKE.152 resourceLimiterGKE := cloudprovider.NewResourceLimiter(153 map[string]int64{cloudprovider.ResourceNameCores: 2, cloudprovider.ResourceNameMemory: 20000000},154 map[string]int64{cloudprovider.ResourceNameCores: 5, cloudprovider.ResourceNameMemory: 200000000})155 gceManagerMock.On("GetResourceLimiter").Return(resourceLimiterGKE, nil).Once()156 returnedResourceLimiterGKE, err := gce.GetResourceLimiter()157 assert.NoError(t, err)158 assert.Equal(t, returnedResourceLimiterGKE, resourceLimiterGKE)159 // Error in GceManager.160 gceManagerMock.On("GetResourceLimiter").Return((*cloudprovider.ResourceLimiter)(nil), fmt.Errorf("Some error")).Once()161 returnedResourceLimiter, err = gce.GetResourceLimiter()162 assert.Error(t, err)163}164const getMachineTypeResponse = `{165 "kind": "compute#machineType",166 "id": "3001",167 "creationTimestamp": "2015-01-16T09:25:43.314-08:00",168 "name": "n1-standard-1",169 "description": "1 vCPU, 3.75 GB RAM",170 "guestCpus": 1,171 "memoryMb": 3840,172 "maximumPersistentDisks": 32,173 "maximumPersistentDisksSizeGb": "65536",174 "zone": "us-central1-a",175 "selfLink": "https://www.googleapis.com/compute/v1/projects/krzysztof-jastrzebski-dev/zones/us-central1-a/machineTypes/n1-standard-1",176 "isSharedCpu": false177}`178const getInstanceGroupManagerResponse = `{179 "kind": "compute#instanceGroupManager",180 "id": "3213213219",181 "creationTimestamp": "2017-09-15T04:47:24.687-07:00",182 "name": "gke-cluster-1-default-pool",183 "zone": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-b",184 "instanceTemplate": "https://www.googleapis.com/compute/v1/projects/project1/global/instanceTemplates/gke-cluster-1-default-pool",185 "instanceGroup": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-b/instanceGroups/gke-cluster-1-default-pool",186 "baseInstanceName": "gke-cluster-1-default-pool-f23aac-grp",187 "fingerprint": "kfdsuH",188 "currentActions": {189 "none": 3,190 "creating": 0,191 "creatingWithoutRetries": 0,192 "recreating": 0,193 "deleting": 0,194 "abandoning": 0,195 "restarting": 0,196 "refreshing": 0197 },198 "targetSize": 3,199 "selfLink": "https://www.googleapis.com/compute/v1/projects/project1/zones/us-central1-b/instanceGroupManagers/gke-cluster-1-default-pool"200}`201const getInstanceTemplateResponse = `{202 "kind": "compute#instanceTemplate",203 "id": "28701103232323232",204 "creationTimestamp": "2017-09-15T04:47:21.577-07:00",205 "name": "gke-cluster-1-default-pool",206 "description": "",207 "properties": {208 "tags": {209 "items": [210 "gke-cluster-1-fc0afeeb-node"211 ]212 },213 "machineType": "n1-standard-1",214 "canIpForward": true,215 "networkInterfaces": [216 {217 "kind": "compute#networkInterface",218 "network": "https://www.googleapis.com/compute/v1/projects/project1/global/networks/default",219 "subnetwork": "https://www.googleapis.com/compute/v1/projects/project1/regions/us-central1/subnetworks/default",220 "accessConfigs": [221 {222 "kind": "compute#accessConfig",223 "type": "ONE_TO_ONE_NAT",224 "name": "external-nat"225 }226 ]227 }228 ],229 "disks": [230 {231 "kind": "compute#attachedDisk",232 "type": "PERSISTENT",233 "mode": "READ_WRITE",234 "boot": true,235 "initializeParams": {236 "sourceImage": "https://www.googleapis.com/compute/v1/projects/gke-node-images/global/images/cos-stable-60-9592-84-0",237 "diskSizeGb": "100",238 "diskType": "pd-standard"239 },240 "autoDelete": true241 }242 ],243 "metadata": {244 "kind": "compute#metadata",245 "fingerprint": "F7n_RsHD3ng=",246 "items": [247 {248 "key": "kube-env",249 "value": "ALLOCATE_NODE_CIDRS: \"true\"\n"250 },251 {252 "key": "user-data",253 "value": "#cloud-config\n\nwrite_files:\n - path: /etc/systemd/system/kube-node-installation.service\n "254 },255 {256 "key": "gci-update-strategy",257 "value": "update_disabled"258 },259 {260 "key": "gci-ensure-gke-docker",261 "value": "true"262 },263 {264 "key": "configure-sh",265 "value": "#!/bin/bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, "266 },267 {268 "key": "cluster-name",269 "value": "cluster-1"270 }271 ]272 },273 "serviceAccounts": [274 {275 "email": "default",276 "scopes": [277 "https://www.googleapis.com/auth/compute",278 "https://www.googleapis.com/auth/devstorage.read_only",279 "https://www.googleapis.com/auth/logging.write",280 "https://www.googleapis.com/auth/monitoring.write",281 "https://www.googleapis.com/auth/servicecontrol",282 "https://www.googleapis.com/auth/service.management.readonly",283 "https://www.googleapis.com/auth/trace.append"284 ]285 }286 ],287 "scheduling": {288 "onHostMaintenance": "MIGRATE",289 "automaticRestart": true,290 "preemptible": false291 }292 },293 "selfLink": "https://www.googleapis.com/compute/v1/projects/project1/global/instanceTemplates/gke-cluster-1-default-pool-f7607aac"294}`295func TestMig(t *testing.T) {296 server := NewHttpServerMock()297 defer server.Close()298 gceManagerMock := &gceManagerMock{}299 client := &http.Client{}300 gceService, err := gcev1.New(client)301 assert.NoError(t, err)302 gceService.BasePath = server.URL303 templateBuilder := &templateBuilder{gceService, "project1"}304 gce := &GceCloudProvider{305 gceManager: gceManagerMock,306 }307 // Test NewNodeGroup.308 gceManagerMock.On("getProjectId").Return("project1").Once()309 gceManagerMock.On("getLocation").Return("us-central1-b").Once()310 gceManagerMock.On("getTemplates").Return(templateBuilder).Once()311 server.On("handle", "/project1/zones/us-central1-b/machineTypes/n1-standard-1").Return(getMachineTypeResponse).Once()312 nodeGroup, err := gce.NewNodeGroup("n1-standard-1", nil, nil, nil)313 assert.NoError(t, err)314 assert.NotNil(t, nodeGroup)315 mig1 := reflect.ValueOf(nodeGroup).Interface().(*Mig)316 mig1.exist = true317 assert.True(t, strings.HasPrefix(mig1.Id(), "https://content.googleapis.com/compute/v1/projects/project1/zones/us-central1-b/instanceGroups/"+nodeAutoprovisioningPrefix+"-n1-standard-1"))318 assert.Equal(t, true, mig1.Autoprovisioned())319 assert.Equal(t, 0, mig1.MinSize())320 assert.Equal(t, 1000, mig1.MaxSize())321 mock.AssertExpectationsForObjects(t, gceManagerMock)322 // Test TargetSize.323 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(2), nil).Once()324 targetSize, err := mig1.TargetSize()325 assert.NoError(t, err)326 assert.Equal(t, 2, targetSize)327 mock.AssertExpectationsForObjects(t, gceManagerMock)328 // Test IncreaseSize.329 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(2), nil).Once()330 gceManagerMock.On("SetMigSize", mock.AnythingOfType("*gce.Mig"), int64(3)).Return(nil).Once()331 err = mig1.IncreaseSize(1)332 assert.NoError(t, err)333 mock.AssertExpectationsForObjects(t, gceManagerMock)334 // Test IncreaseSize - fail on wrong size.335 err = mig1.IncreaseSize(0)336 assert.Error(t, err)337 assert.Equal(t, "size increase must be positive", err.Error())338 // Test IncreaseSize - fail on too big delta.339 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(2), nil).Once()340 err = mig1.IncreaseSize(1000)341 assert.Error(t, err)342 assert.Equal(t, "size increase too large - desired:1002 max:1000", err.Error())343 mock.AssertExpectationsForObjects(t, gceManagerMock)344 // Test DecreaseTargetSize.345 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(3), nil).Once()346 gceManagerMock.On("GetMigNodes", mock.AnythingOfType("*gce.Mig")).Return(347 []string{"gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-9j4g",348 "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1"}, nil).Once()349 gceManagerMock.On("SetMigSize", mock.AnythingOfType("*gce.Mig"), int64(2)).Return(nil).Once()350 err = mig1.DecreaseTargetSize(-1)351 assert.NoError(t, err)352 mock.AssertExpectationsForObjects(t, gceManagerMock)353 // Test DecreaseTargetSize - fail on positive delta.354 err = mig1.DecreaseTargetSize(1)355 assert.Error(t, err)356 assert.Equal(t, "size decrease must be negative", err.Error())357 // Test DecreaseTargetSize - fail on deleting existing nodes.358 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(3), nil).Once()359 gceManagerMock.On("GetMigNodes", mock.AnythingOfType("*gce.Mig")).Return(360 []string{"gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-9j4g",361 "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1"}, nil).Once()362 err = mig1.DecreaseTargetSize(-2)363 assert.Error(t, err)364 assert.Equal(t, "attempt to delete existing nodes targetSize:3 delta:-2 existingNodes: 2", err.Error())365 mock.AssertExpectationsForObjects(t, gceManagerMock)366 // Test Belongs - true.367 gceManagerMock.On("GetMigForInstance", mock.AnythingOfType("*gce.GceRef")).Return(mig1, nil).Once()368 node := BuildTestNode("gke-cluster-1-default-pool-f7607aac-dck1", 1000, 1000)369 node.Spec.ProviderID = "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1"370 belongs, err := mig1.Belongs(node)371 assert.NoError(t, err)372 assert.True(t, belongs)373 mock.AssertExpectationsForObjects(t, gceManagerMock)374 // Test Belongs - false.375 mig2 := &Mig{376 GceRef: GceRef{377 Project: "project1",378 Zone: "us-central1-b",379 Name: "default-pool",380 },381 gceManager: gceManagerMock,382 minSize: 0,383 maxSize: 1000,384 autoprovisioned: true,385 exist: true,386 nodePoolName: "default-pool",387 spec: nil}388 gceManagerMock.On("GetMigForInstance", mock.AnythingOfType("*gce.GceRef")).Return(mig2, nil).Once()389 belongs, err = mig1.Belongs(node)390 assert.NoError(t, err)391 assert.False(t, belongs)392 mock.AssertExpectationsForObjects(t, gceManagerMock)393 // Test DeleteNodes.394 n1 := BuildTestNode("gke-cluster-1-default-pool-f7607aac-9j4g", 1000, 1000)395 n1.Spec.ProviderID = "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-9j4g"396 n1ref := &GceRef{"project1", "us-central1-b", "gke-cluster-1-default-pool-f7607aac-9j4g"}397 n2 := BuildTestNode("gke-cluster-1-default-pool-f7607aac-dck1", 1000, 1000)398 n2.Spec.ProviderID = "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1"399 n2ref := &GceRef{"project1", "us-central1-b", "gke-cluster-1-default-pool-f7607aac-dck1"}400 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(2), nil).Once()401 gceManagerMock.On("GetMigForInstance", n1ref).Return(mig1, nil).Once()402 gceManagerMock.On("GetMigForInstance", n2ref).Return(mig1, nil).Once()403 gceManagerMock.On("DeleteInstances", []*GceRef{n1ref, n2ref}).Return(nil).Once()404 err = mig1.DeleteNodes([]*apiv1.Node{n1, n2})405 assert.NoError(t, err)406 mock.AssertExpectationsForObjects(t, gceManagerMock)407 // Test DeleteNodes - fail on reaching min size.408 gceManagerMock.On("GetMigSize", mock.AnythingOfType("*gce.Mig")).Return(int64(0), nil).Once()409 err = mig1.DeleteNodes([]*apiv1.Node{n1, n2})410 assert.Error(t, err)411 assert.Equal(t, "min size reached, nodes will not be deleted", err.Error())412 mock.AssertExpectationsForObjects(t, gceManagerMock)413 // Test Nodes.414 gceManagerMock.On("GetMigNodes", mock.AnythingOfType("*gce.Mig")).Return(415 []string{"gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-9j4g",416 "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1"}, nil).Once()417 nodes, err := mig1.Nodes()418 assert.NoError(t, err)419 assert.Equal(t, "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-9j4g", nodes[0])420 assert.Equal(t, "gce://project1/us-central1-b/gke-cluster-1-default-pool-f7607aac-dck1", nodes[1])421 mock.AssertExpectationsForObjects(t, gceManagerMock)422 // Test Create.423 mig1.exist = false424 gceManagerMock.On("createNodePool", mock.AnythingOfType("*gce.Mig")).Return(nil).Once()425 err = mig1.Create()426 assert.NoError(t, err)427 mock.AssertExpectationsForObjects(t, gceManagerMock)428 // Test Delete.429 mig1.exist = true430 gceManagerMock.On("deleteNodePool", mock.AnythingOfType("*gce.Mig")).Return(nil).Once()431 err = mig1.Delete()432 assert.NoError(t, err)433 mock.AssertExpectationsForObjects(t, gceManagerMock)434 // Test TemplateNodeInfo.435 gceManagerMock.On("getTemplates").Return(templateBuilder).Times(2)436 server.On("handle", "/project1/zones/us-central1-b/instanceGroupManagers/default-pool").Return(getInstanceGroupManagerResponse).Once()437 server.On("handle", "/project1/global/instanceTemplates/gke-cluster-1-default-pool").Return(getInstanceTemplateResponse).Once()438 server.On("handle", "/project1/zones/us-central1-b/machineTypes/n1-standard-1").Return(getMachineTypeResponse).Once()439 templateNodeInfo, err := mig2.TemplateNodeInfo()440 assert.NoError(t, err)441 assert.NotNil(t, templateNodeInfo)442 assert.NotNil(t, templateNodeInfo.Node())443 mock.AssertExpectationsForObjects(t, gceManagerMock)444 // Test TemplateNodeInfo for non-existing autoprovisioned Mig.445 gceManagerMock.On("getTemplates").Return(templateBuilder).Once()446 server.On("handle", "/project1/zones/us-central1-b/machineTypes/n1-standard-1").Return(getMachineTypeResponse).Once()447 mig1.exist = false448 templateNodeInfo, err = mig1.TemplateNodeInfo()449 assert.NoError(t, err)450 assert.NotNil(t, templateNodeInfo)451 assert.NotNil(t, templateNodeInfo.Node())452 mock.AssertExpectationsForObjects(t, gceManagerMock)453}454func TestGceRefFromProviderId(t *testing.T) {455 ref, err := GceRefFromProviderId("gce://project1/us-central1-b/name1")456 assert.NoError(t, err)457 assert.Equal(t, GceRef{"project1", "us-central1-b", "name1"}, *ref)458}...
gce.go
Source:gce.go
1// Copyright 2015 The Prometheus Authors2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.13package gce14import (15 "context"16 "fmt"17 "net/http"18 "strconv"19 "strings"20 "time"21 "github.com/go-kit/kit/log"22 "github.com/pkg/errors"23 "github.com/prometheus/common/model"24 "golang.org/x/oauth2/google"25 compute "google.golang.org/api/compute/v1"26 "google.golang.org/api/option"27 "github.com/prometheus/prometheus/discovery"28 "github.com/prometheus/prometheus/discovery/refresh"29 "github.com/prometheus/prometheus/discovery/targetgroup"30 "github.com/prometheus/prometheus/util/strutil"31)32const (33 gceLabel = model.MetaLabelPrefix + "gce_"34 gceLabelProject = gceLabel + "project"35 gceLabelZone = gceLabel + "zone"36 gceLabelNetwork = gceLabel + "network"37 gceLabelSubnetwork = gceLabel + "subnetwork"38 gceLabelPublicIP = gceLabel + "public_ip"39 gceLabelPrivateIP = gceLabel + "private_ip"40 gceLabelInstanceID = gceLabel + "instance_id"41 gceLabelInstanceName = gceLabel + "instance_name"42 gceLabelInstanceStatus = gceLabel + "instance_status"43 gceLabelTags = gceLabel + "tags"44 gceLabelMetadata = gceLabel + "metadata_"45 gceLabelLabel = gceLabel + "label_"46 gceLabelMachineType = gceLabel + "machine_type"47)48// DefaultSDConfig is the default GCE SD configuration.49var DefaultSDConfig = SDConfig{50 Port: 80,51 TagSeparator: ",",52 RefreshInterval: model.Duration(60 * time.Second),53}54func init() {55 discovery.RegisterConfig(&SDConfig{})56}57// SDConfig is the configuration for GCE based service discovery.58type SDConfig struct {59 // Project: The Google Cloud Project ID60 Project string `yaml:"project"`61 // Zone: The zone of the scrape targets.62 // If you need to configure multiple zones use multiple gce_sd_configs63 Zone string `yaml:"zone"`64 // Filter: Can be used optionally to filter the instance list by other criteria.65 // Syntax of this filter string is described here in the filter query parameter section:66 // https://cloud.google.com/compute/docs/reference/latest/instances/list67 Filter string `yaml:"filter,omitempty"`68 RefreshInterval model.Duration `yaml:"refresh_interval,omitempty"`69 Port int `yaml:"port"`70 TagSeparator string `yaml:"tag_separator,omitempty"`71}72// Name returns the name of the Config.73func (*SDConfig) Name() string { return "gce" }74// NewDiscoverer returns a Discoverer for the Config.75func (c *SDConfig) NewDiscoverer(opts discovery.DiscovererOptions) (discovery.Discoverer, error) {76 return NewDiscovery(*c, opts.Logger)77}78// UnmarshalYAML implements the yaml.Unmarshaler interface.79func (c *SDConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {80 *c = DefaultSDConfig81 type plain SDConfig82 err := unmarshal((*plain)(c))83 if err != nil {84 return err85 }86 if c.Project == "" {87 return errors.New("GCE SD configuration requires a project")88 }89 if c.Zone == "" {90 return errors.New("GCE SD configuration requires a zone")91 }92 return nil93}94// Discovery periodically performs GCE-SD requests. It implements95// the Discoverer interface.96type Discovery struct {97 *refresh.Discovery98 project string99 zone string100 filter string101 client *http.Client102 svc *compute.Service103 isvc *compute.InstancesService104 port int105 tagSeparator string106}107// NewDiscovery returns a new Discovery which periodically refreshes its targets.108func NewDiscovery(conf SDConfig, logger log.Logger) (*Discovery, error) {109 d := &Discovery{110 project: conf.Project,111 zone: conf.Zone,112 filter: conf.Filter,113 port: conf.Port,114 tagSeparator: conf.TagSeparator,115 }116 var err error117 d.client, err = google.DefaultClient(context.Background(), compute.ComputeReadonlyScope)118 if err != nil {119 return nil, errors.Wrap(err, "error setting up communication with GCE service")120 }121 d.svc, err = compute.NewService(context.Background(), option.WithHTTPClient(d.client))122 if err != nil {123 return nil, errors.Wrap(err, "error setting up communication with GCE service")124 }125 d.isvc = compute.NewInstancesService(d.svc)126 d.Discovery = refresh.NewDiscovery(127 logger,128 "gce",129 time.Duration(conf.RefreshInterval),130 d.refresh,131 )132 return d, nil133}134func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) {135 tg := &targetgroup.Group{136 Source: fmt.Sprintf("GCE_%s_%s", d.project, d.zone),137 }138 ilc := d.isvc.List(d.project, d.zone)139 if len(d.filter) > 0 {140 ilc = ilc.Filter(d.filter)141 }142 err := ilc.Pages(ctx, func(l *compute.InstanceList) error {143 for _, inst := range l.Items {144 if len(inst.NetworkInterfaces) == 0 {145 continue146 }147 labels := model.LabelSet{148 gceLabelProject: model.LabelValue(d.project),149 gceLabelZone: model.LabelValue(inst.Zone),150 gceLabelInstanceID: model.LabelValue(strconv.FormatUint(inst.Id, 10)),151 gceLabelInstanceName: model.LabelValue(inst.Name),152 gceLabelInstanceStatus: model.LabelValue(inst.Status),153 gceLabelMachineType: model.LabelValue(inst.MachineType),154 }155 priIface := inst.NetworkInterfaces[0]156 labels[gceLabelNetwork] = model.LabelValue(priIface.Network)157 labels[gceLabelSubnetwork] = model.LabelValue(priIface.Subnetwork)158 labels[gceLabelPrivateIP] = model.LabelValue(priIface.NetworkIP)159 addr := fmt.Sprintf("%s:%d", priIface.NetworkIP, d.port)160 labels[model.AddressLabel] = model.LabelValue(addr)161 // Tags in GCE are usually only used for networking rules.162 if inst.Tags != nil && len(inst.Tags.Items) > 0 {163 // We surround the separated list with the separator as well. This way regular expressions164 // in relabeling rules don't have to consider tag positions.165 tags := d.tagSeparator + strings.Join(inst.Tags.Items, d.tagSeparator) + d.tagSeparator166 labels[gceLabelTags] = model.LabelValue(tags)167 }168 // GCE metadata are key-value pairs for user supplied attributes.169 if inst.Metadata != nil {170 for _, i := range inst.Metadata.Items {171 // Protect against occasional nil pointers.172 if i.Value == nil {173 continue174 }175 name := strutil.SanitizeLabelName(i.Key)176 labels[gceLabelMetadata+model.LabelName(name)] = model.LabelValue(*i.Value)177 }178 }179 // GCE labels are key-value pairs that group associated resources180 for key, value := range inst.Labels {181 name := strutil.SanitizeLabelName(key)182 labels[gceLabelLabel+model.LabelName(name)] = model.LabelValue(value)183 }184 if len(priIface.AccessConfigs) > 0 {185 ac := priIface.AccessConfigs[0]186 if ac.Type == "ONE_TO_ONE_NAT" {187 labels[gceLabelPublicIP] = model.LabelValue(ac.NatIP)188 }189 }190 tg.Targets = append(tg.Targets, labels)191 }192 return nil193 })194 if err != nil {195 return nil, errors.Wrap(err, "error retrieving refresh targets from gce")196 }197 return []*targetgroup.Group{tg}, nil198}...
Error
Using AI Code Generation
1import (2func main() {3 g := gce{}4 fmt.Println(g.Error())5}6import (7func main() {8 g := gce{}9 fmt.Println(g.Error())10}11import (12func main() {13 g := gce{}14 fmt.Println(g.Error())15}16import (17func main() {18 g := gce{}19 fmt.Println(g.Error())20}21import (22func main() {23 g := gce{}24 fmt.Println(g.Error())25}26import (27func main() {28 g := gce{}29 fmt.Println(g.Error())30}31import (32func main() {33 g := gce{}34 fmt.Println(g.Error())35}36import (37func main() {38 g := gce{}39 fmt.Println(g.Error())40}41import (42func main() {43 g := gce{}44 fmt.Println(g.Error())45}46import (47func main() {48 g := gce{}49 fmt.Println(g.Error())50}51import (52func main() {53 g := gce{}54 fmt.Println(g.Error())55}56import (57func main() {58 g := gce{}59 fmt.Println(g.Error())60}
Error
Using AI Code Generation
1import (2func main() {3 gce, err := metadata.OnGCE()4 if err != nil {5 log.Fatal(err)6 }7 fmt.Println(gce)8}9import (10func main() {11 projectID, err := metadata.Get("project/project-id")12 if err != nil {13 log.Fatal(err)14 }15 fmt.Println(projectID)16}17import (18func main() {19 instances, err := metadata.Instances()20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(instances)24}
Error
Using AI Code Generation
1import (2func main() {3 g := gce{}4 fmt.Println(g.Error())5}6import (7func main() {8 g := gce{}9 fmt.Println(g.Error())10}11import (12func main() {13 g := gce{}14 fmt.Println(g.Error())15}16import (17func main() {18 g := gce{}19 fmt.Println(g.Error())20}21import (22func main() {23 g := gce{}24 fmt.Println(g.Error())25}26import (27func main() {28 g := gce{}29 fmt.Println(g.Error())30}31import (32func main() {33 g := gce{}34 fmt.Println(g.Error())35}36import (37func main() {38 g := gce{}39 fmt.Println(g.Error())40}41import (42func main() {43 g := gce{}44 fmt.Println(g.Error())45}46import (47func main() {48 g := gce{}49 fmt.Println(g.Error())50}51import (52func main() {53 g := gce{}54 fmt.Println(g.Error())55}
Error
Using AI Code Generation
1import (2func main() {3 gce := compute.NewService(nil)4 err := gce.Instances.Get("project", "zone", "instance").Do()5 if err != nil {6 fmt.Println("Error:", err.Error())7 }8}9func (e Error) Error() string
Error
Using AI Code Generation
1import (2func main() {3 g := gce.New()4 g.Add("a", "1")5 g.Add("b", "2")6 g.Add("c", "3")7 g.Add("d", "4")8 g.Add("e", "5")9 g.Add("f", "6")10 g.Add("g", "7")11 g.Add("h", "8")12 g.Add("i", "9")13 g.Add("j", "10")14 g.Add("k", "11")15 g.Add("l", "12")16 g.Add("m", "13")17 g.Add("n", "14")18 g.Add("o", "15")19 g.Add("p", "16")20 g.Add("q", "17")21 g.Add("r", "18")22 g.Add("s", "19")23 g.Add("t", "20")24 g.Add("u", "21")25 g.Add("v", "22")26 g.Add("w", "23")27 g.Add("x", "24")28 g.Add("y", "25")29 g.Add("z", "26")30 if g.Error() != nil {31 fmt.Println(g.Error())32 }33 fmt.Println("gce size:", g.Size())34 fmt.Println("gce keys:", g.Keys())35 fmt.Println("gce values:", g.Values())36 fmt.Println("gce pairs:", g.Pairs())37 fmt.Println("gce contains a:", g.Contains("a"))38 fmt.Println("gce contains b:", g.Contains("b"))39 fmt.Println("gce contains z:", g.Contains("z"))40 fmt.Println("gce contains 1:", g.ContainsValue("1"))41 fmt.Println("gce contains 2:", g.ContainsValue("2"))42 fmt.Println("gce contains 26:", g.ContainsValue("26"))43 fmt.Println("gce get a:", g.Get("a"))44 fmt.Println("gce get b:", g.Get("b"))45 fmt.Println("gce get z:", g.Get("z"))46 fmt.Println("gce remove a:", g.Remove("a"))47 fmt.Println("gce remove b:", g.Remove("b"))48 fmt.Println("gce remove z:", g.Remove("z"))49 fmt.Println("gce size:", g.Size())50 fmt.Println("
Error
Using AI Code Generation
1import (2func main() {3 fmt.Println(stringutil.Reverse("Hello, world"))4}5import (6func main() {7 fmt.Println(icomefromalaska.Reverse("Hello, world"))8}9import (10func main() {11 fmt.Println(stringutil.MyName)12}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!