Skip to content

Commit

Permalink
feat: adds gcp metadata provider support to cloudmeta package
Browse files Browse the repository at this point in the history
This adds gcp metadata provider support to cloudmeta package.

Fixes: #4128
  • Loading branch information
VAveryanov8 committed Dec 11, 2024
1 parent 8878021 commit 7d6bb37
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
50 changes: 50 additions & 0 deletions pkg/cloudmeta/gcp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (C) 2024 ScyllaDB

package cloudmeta

import (
"context"
"strings"

"cloud.google.com/go/compute/metadata"
"github.com/pkg/errors"
)

// GCPMetadata is a wrapper around gcp metadata client.
type GCPMetadata struct {
meta *metadata.Client
}

// NewGCPMetadata returns gcp metadata provider.
func NewGCPMetadata() *GCPMetadata {
return &GCPMetadata{
meta: metadata.NewClient(nil),
}
}

// Metadata returns InstanceMetadata from gcp if available.
func (gcp *GCPMetadata) Metadata(ctx context.Context) (InstanceMetadata, error) {
machineType, err := gcp.getMachineType(ctx)
if err != nil {
return InstanceMetadata{}, errors.Wrap(err, "gcp.meta.GetWithContext")
}
return InstanceMetadata{
CloudProvider: CloudProviderGCP,
InstanceType: machineType,
}, nil
}

func (gcp *GCPMetadata) getMachineType(ctx context.Context) (string, error) {
// The machine type for this VM. This value has the following format: projects/PROJECT_NUM/machineTypes/MACHINE_TYPE.
machineType, err := gcp.meta.GetWithContext(ctx, "instance/machine-type")
if err != nil {
return "", errors.Wrap(err, "gcp.meta.GetWithContext")
}

parts := strings.Split(machineType, "/")
if len(parts) < 2 {
return "", errors.Errorf("unexpected machine-type format: %s", machineType)
}

return parts[len(parts)-1], nil
}
11 changes: 9 additions & 2 deletions pkg/cloudmeta/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ type InstanceMetadata struct {
// CloudProvider is enum of supported cloud providers.
type CloudProvider string

// CloudProviderAWS represents aws provider.
var CloudProviderAWS CloudProvider = "aws"
var (
// CloudProviderAWS represents aws provider.
CloudProviderAWS CloudProvider = "aws"
// CloudProviderGCP represents gcp provider.
CloudProviderGCP CloudProvider = "gcp"
)

// CloudMetadataProvider interface that each metadata provider should implement.
type CloudMetadataProvider interface {
Expand All @@ -41,9 +45,12 @@ func NewCloudMeta() (*CloudMeta, error) {
return nil, err
}

gcpMeta := NewGCPMetadata()

return &CloudMeta{
providers: []CloudMetadataProvider{
awsMeta,
gcpMeta,
},
providerTimeout: defaultTimeout,
}, nil
Expand Down

0 comments on commit 7d6bb37

Please sign in to comment.