-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adds gcp metadata provider support to cloudmeta package
This adds gcp metadata provider support to cloudmeta package. Fixes: #4128
- Loading branch information
1 parent
8878021
commit 7d6bb37
Showing
2 changed files
with
59 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters