Skip to content

Commit bef978d

Browse files
authored
Merge pull request #44 from cbullinger/docsp-49329-push-artifact-repo
DOCSP-49329: Copy Go SDK project files to atlas-architecture-go-sdk
2 parents f098752 + 10dd53c commit bef978d

File tree

10 files changed

+430
-8
lines changed

10 files changed

+430
-8
lines changed

config.json

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,23 @@
11
[
22
{
3-
"notes": "This is a test config. It can be safely deleted.",
4-
"source_directory" : "generated-examples/go",
5-
"target_repo" : "docs-code-examples-test-target",
3+
"notes": "Copy atlas-sdk-go project files to user-facing Atlas Architecture Center artifact repo root",
4+
"source_directory" : "generated-usage-examples/go/atlas-sdk-go/project-copy",
5+
"target_repo" : "atlas-architecture-go-sdk",
6+
"target_branch" : "copy-test",
7+
"target_directory" : "."
8+
},
9+
{
10+
"notes": "Example config for copying files from a directory to another repo",
11+
"source_directory" : "generated-examples",
12+
"target_repo" : "my-target-repo-name",
613
"target_branch" : "main",
7-
"target_directory" : "go"
14+
"target_directory" : "examples"
815
},
916
{
10-
"notes":"This is a test config that copies fake v2 code examples to the v2.2 driver branch.",
11-
"source_directory" : "generated-examples/go/v2",
12-
"target_repo" : "docs-code-examples-test-target",
17+
"notes":"Example config for copying a subset of files to another repo and branch",
18+
"source_directory" : "generated-examples/v2",
19+
"target_repo" : "my-target-repo-name",
1320
"target_branch" : "v2.2",
14-
"target_directory" : "go"
21+
"target_directory" : "v2-examples"
1522
}
1623
]
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package main
2+
3+
import (
4+
"atlas-sdk-go/internal/auth"
5+
"compress/gzip"
6+
"context"
7+
"fmt"
8+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
9+
"io"
10+
"log"
11+
"os"
12+
"strings"
13+
)
14+
15+
// getHostLogs downloads a compressed .gz file that contains the MongoDB logs for
16+
// the specified host in your project.
17+
func getHostLogs(ctx context.Context, atlasClient admin.APIClient, params *admin.GetHostLogsApiParams) (string, error) {
18+
logFileName := fmt.Sprintf("logs_%s_%s.gz", params.GroupId, params.HostName)
19+
fmt.Printf("Fetching %s log for host %s in project %s\n", params.LogName, params.HostName, params.GroupId)
20+
21+
if err := downloadLogs(ctx, atlasClient, params, logFileName); err != nil {
22+
return "", err
23+
}
24+
25+
fmt.Printf("Logs saved to %s\n", logFileName)
26+
return logFileName, nil
27+
}
28+
29+
func SafeClose(c io.Closer) {
30+
if c != nil {
31+
if err := c.Close(); err != nil {
32+
log.Printf("Warning: failed to close resource: %v", err)
33+
}
34+
}
35+
}
36+
37+
func downloadLogs(ctx context.Context, atlasClient admin.APIClient, params *admin.GetHostLogsApiParams, filePath string) error {
38+
resp, _, err := atlasClient.MonitoringAndLogsApi.GetHostLogsWithParams(ctx, params).Execute()
39+
if err != nil {
40+
return fmt.Errorf("fetch logs: %w", err)
41+
}
42+
defer SafeClose(resp)
43+
44+
file, err := os.Create(filePath)
45+
if err != nil {
46+
return fmt.Errorf("create %q: %w", filePath, err)
47+
}
48+
defer SafeClose(file)
49+
50+
if _, err := io.Copy(file, resp); err != nil {
51+
return fmt.Errorf("write to %q: %w", filePath, err)
52+
}
53+
54+
return nil
55+
}
56+
57+
func unzipGzFile(srcPath, destPath string) error {
58+
srcFile, err := os.Open(srcPath)
59+
if err != nil {
60+
return fmt.Errorf("open gz file: %w", err)
61+
}
62+
defer SafeClose(srcFile)
63+
64+
gzReader, err := gzip.NewReader(srcFile)
65+
if err != nil {
66+
return fmt.Errorf("create gzip reader: %w", err)
67+
}
68+
defer SafeClose(gzReader)
69+
70+
destFile, err := os.Create(destPath)
71+
if err != nil {
72+
return fmt.Errorf("create destination file: %w", err)
73+
}
74+
defer SafeClose(destFile)
75+
76+
if _, err := io.Copy(destFile, gzReader); err != nil {
77+
return fmt.Errorf("unzip copy error: %w", err)
78+
}
79+
80+
fmt.Printf("Unzipped logs to %s\n", destPath)
81+
return nil
82+
}
83+
84+
func main() {
85+
ctx := context.Background()
86+
87+
// Create an Atlas client authenticated using OAuth2 with service account credentials
88+
client, _, config, err := auth.CreateAtlasClient()
89+
if err != nil {
90+
log.Fatalf("Failed to create Atlas client: %v", err)
91+
}
92+
93+
params := &admin.GetHostLogsApiParams{
94+
GroupId: config.ProjectID,
95+
HostName: config.HostName,
96+
LogName: "mongodb", // Type of log ("mongodb" or "mongos")
97+
}
98+
99+
logFileName, err := getHostLogs(ctx, *client, params)
100+
if err != nil {
101+
log.Fatalf("Failed to download logs: %v", err)
102+
}
103+
104+
plainTextLog := strings.TrimSuffix(logFileName, ".gz") + ".log"
105+
if err := unzipGzFile(logFileName, plainTextLog); err != nil {
106+
log.Fatalf("Failed to unzip log file: %v", err)
107+
}
108+
109+
}
110+
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package main
2+
3+
import (
4+
"atlas-sdk-go/internal/auth"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
9+
"log"
10+
)
11+
12+
// getDiskMetrics fetches metrics for a specified disk partition in a project and prints results to the console
13+
func getDiskMetrics(ctx context.Context, atlasClient admin.APIClient, params *admin.GetDiskMeasurementsApiParams) (*admin.ApiMeasurementsGeneralViewAtlas, error) {
14+
15+
resp, _, err := atlasClient.MonitoringAndLogsApi.GetDiskMeasurementsWithParams(ctx, params).Execute()
16+
if err != nil {
17+
if apiError, ok := admin.AsError(err); ok {
18+
return nil, fmt.Errorf("failed to get metrics for partition: %s (API error: %v)", err, apiError.GetDetail())
19+
}
20+
return nil, fmt.Errorf("failed to get metrics: %w", err)
21+
}
22+
if resp == nil || resp.HasMeasurements() == false {
23+
return nil, fmt.Errorf("no metrics found for partition %s in project %s", params.PartitionName, params.GroupId)
24+
}
25+
jsonData, err := json.MarshalIndent(resp, "", " ")
26+
if err != nil {
27+
return nil, fmt.Errorf("failed to marshal response: %w", err)
28+
}
29+
fmt.Println(string(jsonData))
30+
return resp, nil
31+
}
32+
33+
func main() {
34+
ctx := context.Background()
35+
36+
// Create an Atlas client authenticated using OAuth2 with service account credentials
37+
atlasClient, _, config, err := auth.CreateAtlasClient()
38+
if err != nil {
39+
log.Fatalf("Failed to create Atlas client: %v", err)
40+
}
41+
42+
// Fetch disk metrics using the following parameters:
43+
partitionName := "data"
44+
diskMetricsGranularity := admin.PtrString("P1D")
45+
diskMetricsPeriod := admin.PtrString("P1D")
46+
diskMetrics := []string{
47+
"DISK_PARTITION_SPACE_FREE", "DISK_PARTITION_SPACE_USED",
48+
}
49+
50+
diskMeasurementsParams := &admin.GetDiskMeasurementsApiParams{
51+
GroupId: config.ProjectID,
52+
ProcessId: config.ProcessID,
53+
PartitionName: partitionName,
54+
M: &diskMetrics,
55+
Granularity: diskMetricsGranularity,
56+
Period: diskMetricsPeriod,
57+
}
58+
_, err = getDiskMetrics(ctx, *atlasClient, diskMeasurementsParams)
59+
if err != nil {
60+
fmt.Printf("Error fetching disk metrics: %v", err)
61+
}
62+
}
63+
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package main
2+
3+
import (
4+
"atlas-sdk-go/internal/auth"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
9+
"log"
10+
)
11+
12+
// getProcessMetrics fetches metrics for a specified host process in a project and prints results to the console
13+
func getProcessMetrics(ctx context.Context, atlasClient admin.APIClient, params *admin.GetHostMeasurementsApiParams) (*admin.ApiMeasurementsGeneralViewAtlas, error) {
14+
fmt.Printf("Fetching metrics for host process %s in project %s", params.ProcessId, params.GroupId)
15+
16+
resp, _, err := atlasClient.MonitoringAndLogsApi.GetHostMeasurementsWithParams(ctx, params).Execute()
17+
if err != nil {
18+
if apiError, ok := admin.AsError(err); ok {
19+
return nil, fmt.Errorf("failed to get metrics for process in host: %s (API error: %v)", err, apiError.GetDetail())
20+
}
21+
return nil, fmt.Errorf("failed to get metrics: %w", err)
22+
}
23+
24+
if resp == nil || resp.HasMeasurements() == false {
25+
return nil, fmt.Errorf("no metrics found for host process %s in project %s", params.ProcessId, params.GroupId)
26+
}
27+
jsonData, err := json.MarshalIndent(resp, "", " ")
28+
if err != nil {
29+
return nil, fmt.Errorf("failed to marshal response: %w", err)
30+
}
31+
fmt.Println(string(jsonData))
32+
return resp, nil
33+
}
34+
35+
func main() {
36+
ctx := context.Background()
37+
38+
// Create an Atlas client authenticated using OAuth2 with service account credentials
39+
atlasClient, _, config, err := auth.CreateAtlasClient()
40+
if err != nil {
41+
log.Fatalf("Failed to create Atlas client: %v", err)
42+
}
43+
44+
// Fetch process metrics using the following parameters:
45+
processMetricGranularity := admin.PtrString("PT1H")
46+
processMetricPeriod := admin.PtrString("P7D")
47+
processMetrics := []string{
48+
"OPCOUNTER_INSERT", "OPCOUNTER_QUERY", "OPCOUNTER_UPDATE", "TICKETS_AVAILABLE_READS",
49+
"TICKETS_AVAILABLE_WRITE", "CONNECTIONS", "QUERY_TARGETING_SCANNED_OBJECTS_PER_RETURNED",
50+
"QUERY_TARGETING_SCANNED_PER_RETURNED", "SYSTEM_CPU_GUEST", "SYSTEM_CPU_IOWAIT",
51+
"SYSTEM_CPU_IRQ", "SYSTEM_CPU_KERNEL", "SYSTEM_CPU_NICE", "SYSTEM_CPU_SOFTIRQ",
52+
"SYSTEM_CPU_STEAL", "SYSTEM_CPU_USER",
53+
}
54+
hostMeasurementsParams := &admin.GetHostMeasurementsApiParams{
55+
GroupId: config.ProjectID,
56+
ProcessId: config.ProcessID,
57+
M: &processMetrics,
58+
Granularity: processMetricGranularity,
59+
Period: processMetricPeriod,
60+
}
61+
_, err = getProcessMetrics(ctx, *atlasClient, hostMeasurementsParams)
62+
if err != nil {
63+
fmt.Printf("Error fetching host process metrics: %v", err)
64+
}
65+
}
66+
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"MONGODB_ATLAS_BASE_URL": "https://cloud.mongodb.com",
3+
"ATLAS_ORG_ID": "<your-organization-id>",
4+
"ATLAS_PROJECT_ID": "<your-project-id>",
5+
"ATLAS_CLUSTER_NAME": "<clusterName>",
6+
"ATLAS_PROCESS_ID": "<clusterName-shard-00-00.hostSuffix.mongodb.net:port>"
7+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
module atlas-sdk-go
2+
3+
go 1.24
4+
5+
require (
6+
github.com/joho/godotenv v1.5.1
7+
github.com/stretchr/testify v1.10.0
8+
go.mongodb.org/atlas-sdk/v20250219001 v20250219001.1.0
9+
)
10+
11+
require (
12+
github.com/davecgh/go-spew v1.1.1 // indirect
13+
github.com/mongodb-forks/digest v1.1.0 // indirect
14+
github.com/pmezard/go-difflib v1.0.0 // indirect
15+
golang.org/x/oauth2 v0.28.0 // indirect
16+
gopkg.in/yaml.v3 v3.0.1 // indirect
17+
)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3+
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
4+
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
5+
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
6+
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
7+
github.com/mongodb-forks/digest v1.1.0 h1:7eUdsR1BtqLv0mdNm4OXs6ddWvR4X2/OsLwdKksrOoc=
8+
github.com/mongodb-forks/digest v1.1.0/go.mod h1:rb+EX8zotClD5Dj4NdgxnJXG9nwrlx3NWKJ8xttz1Dg=
9+
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
10+
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
11+
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
12+
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
13+
go.mongodb.org/atlas-sdk/v20250219001 v20250219001.1.0 h1:tm7d3xvbNFIpuvFcppXc1zdpM/dO7HwivpA+Y4np3uQ=
14+
go.mongodb.org/atlas-sdk/v20250219001 v20250219001.1.0/go.mod h1:huR1gWJhExa60NIRhsLDdc7RmmqKJJwnbdlA1UUh8V4=
15+
golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc=
16+
golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8=
17+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
18+
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
19+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
20+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package auth
2+
3+
import (
4+
"atlas-sdk-go/internal"
5+
"context"
6+
"fmt"
7+
"go.mongodb.org/atlas-sdk/v20250219001/admin"
8+
)
9+
10+
const filePath = "./configs/config.json"
11+
12+
// CreateAtlasClient initializes and returns an authenticated Atlas API client
13+
// using OAuth2 with service account credentials.
14+
func CreateAtlasClient() (*admin.APIClient, *internal.Secrets, *internal.Config, error) {
15+
16+
var secrets, err = internal.LoadSecrets()
17+
if err != nil {
18+
return nil, nil, nil, fmt.Errorf("failed to load secrets: %w", err)
19+
}
20+
if err := secrets.CheckRequiredEnv(); err != nil {
21+
return nil, nil, nil, fmt.Errorf("invalid .env: %w", err)
22+
}
23+
24+
config, err := internal.LoadConfig(filePath)
25+
if err != nil {
26+
return nil, nil, nil, fmt.Errorf("failed to load config file: %w", err)
27+
}
28+
config.SetDefaults()
29+
if err := config.CheckRequiredFields(); err != nil {
30+
return nil, nil, nil, fmt.Errorf("invalid config: %w", err)
31+
}
32+
33+
ctx := context.Background()
34+
atlasClient, err := admin.NewClient(
35+
admin.UseBaseURL(config.BaseURL),
36+
admin.UseOAuthAuth(ctx, secrets.ServiceAccountID, secrets.ServiceAccountSecret),
37+
)
38+
if err != nil {
39+
return nil, nil, nil, fmt.Errorf("error creating SDK client: %w", err)
40+
}
41+
42+
return atlasClient, secrets, config, nil
43+
}

0 commit comments

Comments
 (0)