Coder Social home page Coder Social logo

mongodb / go-client-mongodb-atlas Goto Github PK

View Code? Open in Web Editor NEW
77.0 24.0 35.0 9.4 MB

Go Client for MongoDB Atlas

Home Page: https://www.mongodb.com/docs/atlas/reference/api-resources-spec/

License: Apache License 2.0

Go 99.61% Makefile 0.08% Shell 0.31%
go hacktoberfest mongodb

go-client-mongodb-atlas's Introduction

go-client-mongodb-atlas

PkgGoDev CI

A Go HTTP client for the MongoDB Atlas API.

Note that go-client-mongodb-atlas only supports the two most recent major versions of Go.

This package is deprecated

The go-client-mongodb-atlas is deprecated and doesn't receive feature updates. We recommend migrating to the Atlas Go SDK for the latest changes.

To learn how to migrate from go-client-mongodb-atlas to the Atlas Go SDK, see the migration guide.

Usage

import "go.mongodb.org/atlas/mongodbatlas"

Construct a new Atlas client, then use the various services on the client to access different parts of the Atlas API. For example:

client := mongodbatlas.NewClient(nil)

The services of a client divide the API into logical chunks and correspond to the structure of the Atlas API documentation at https://docs.atlas.mongodb.com/api/.

NOTE: Using the context package, one can easily pass cancellation signals and deadlines to various services of the client for handling a request. In case there is no context available, then context.Background() can be used as a starting point.

Authentication

The go-client-mongodb-atlas library does not directly handle authentication. Instead, when creating a new client, pass an http.Client that can handle Digest Access authentication for you. The easiest way to do this is using the digest library, but you can always use any other library that provides an http.Client. If you have a private and public API token pair (https://docs.atlas.mongodb.com/configure-api-access), you can use it with the digest library like:

import (
    "context"
    "log"

    "github.com/mongodb-forks/digest"
    "go.mongodb.org/atlas/mongodbatlas"
)

func main() {
    t := digest.NewTransport("your public key", "your private key")
    tc, err := t.Client()
    if err != nil {
        log.Fatalf(err.Error())
    }

    client := mongodbatlas.NewClient(tc)
    projects, _, err := client.Projects.GetAllProjects(context.Background(), nil)
}

Note that when using an authenticated Client, all calls made by the client will include the specified tokens. Therefore, authenticated clients should almost never be shared between different users.

Versioning

Each version of the client is tagged and the version is updated accordingly.

To see the list of past versions, run git tag.

To release a new version, first ensure that Version is updated (i.e., before running git push origin vx.y.z, verify that Version=x.y.z should match the tag being pushed to GitHub)

Roadmap

This library is being initially developed for mongocli, Atlas Terraform Provider, Atlas Vault Plugin, and Atlas Cloudformation Provider so API methods will likely be implemented in the order that they are needed by those projects.

Contributing

See our CONTRIBUTING.md Guide.

License

go-client-mongodb-atlas is released under the Apache 2.0 license. See LICENSE

go-client-mongodb-atlas's People

Contributors

10genola avatar abner-dou avatar agustinbettati avatar andreaangiolillo avatar atilsensalduz avatar codergo93 avatar dependabot[bot] avatar fmenezes avatar gmlp avatar gssbzn avatar howdoicomputer avatar lantoli avatar leofigy avatar maastha avatar marcosuma avatar marinsalinas avatar martinstibbe avatar matt-condon avatar mihaibojin avatar pacodw avatar robcarlan-mlab avatar stovoy avatar sugar-pack avatar sunny-b avatar suzuki-shunsuke avatar themantissa avatar thetonymaster avatar tibulca avatar trunet avatar wtrocki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-client-mongodb-atlas's Issues

Issue calling CloudProviderSnapshotBackupPolicies Service

Hi Team!

I'm trying to call Atlas API to GET the backup policy (CloudProviderSnapshotBackupPoliciesService) and I'm getting an error from the client:

{"responseError": "json: unsupported type: func() (io.ReadCloser, error)"}

My cluster is running in Atlas, I have enabled continuous backups. I'm passing valid parameters and it seems that issue is not on my service side.
Could someone look at this?

Cheers,
Magda

ClusterID attribute to Processes.List returns 400 error response

Describe the bug

client.Processes.List() takes an argument of ClusterID specified in processes.go. The corresponding endpoint seems to not take that argument, however. The call then returns an error complaining about the unknown query argument.

Expected behavior
The call should return a list of processes scoped to the specified cluster id.

Logs
N/A

Desktop (please complete the following information):

  • OS: all, replicated on OSX
  • Lib Version: 0.12.0

Additional context
"GET https://cloud.mongodb.com/api/atlas/v1.0/groups/613b7e5ac7577b1ee2e5c5dd/processes?clusterId=Cluster0&includeCount=true: 400 (request \"INVALID_QUERY_PARAMETER\") Invalid query parameter clusterId specified."

"CloudProviderSnapshots.GetOneCloudProviderSnapshot()" method returns already deleted snapshot

Describe the bug
I created a snapshot and deleted it using Atlas UI.
But "CloudProviderSnapshots.GetOneCloudProviderSnapshot()" method in atlas client returns already deleted snapshot

snapshot, res, err := client.CloudProviderSnapshots.GetOneCloudProviderSnapshot(context.TODO(), snapshotRequest)
if err != nil {
	log.Infof("Read - errorss reading project with id(%s): %s", snapshotId, err)
	return handler.ProgressEvent{
		OperationStatus:  handler.Failed,
		Message:          "Resource Not Found",
		HandlerErrorCode: cloudformation.HandlerErrorCodeNotFound}, nil
}

Expected behavior
it should return error( "Resource Not Found")

Logs
If applicable, add logs to help explain your problem.

Desktop (please complete the following information):

  • Windows
    -go.mongodb.org/atlas v0.17.0

Additional context
Add any other context about the problem here.

ClustersService does not list the available clusters

Describe the bug
I am trying to list the clusters for my organization using ClustersService.

The following code snippet does not retrieve any clusters despite I know I have deployed a couple

(the *client instance is valid since I am able to list my projects' names)

	projects, _, err := client.Projects.GetAllProjects(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	for _, project := range projects.Results {
		client.Clusters.List(ctx, project.ID, nil)
	}

Expected behavior
Clusters should be listed.

Logs
If applicable, add logs to help explain your problem.

Desktop (please complete the following information):

  • OS: MacOS Ventura
  • Lib Version v0.36.0

Additional context
Add any other context about the problem here.

Add "Name" ListOption for filtering list results

The Mongo Atlas API supports filtering list results based on a name parameter.

Link: https://docs.atlas.mongodb.com/reference/api/organization-get-all/#resource

It would be really useful to have this supported in the Go Client as well. At the moment, it looks like the only ListOptions that are supported are PageNum, and ItemsPerPage

// ListOptions specifies the optional parameters to List methods that
// support pagination.
type ListOptions struct {
// For paginated result sets, page of results to retrieve.
PageNum int `url:"pageNum,omitempty"`
// For paginated result sets, the number of results to include per page.
ItemsPerPage int `url:"itemsPerPage,omitempty"`
}

We use Ops Manager at work and we depend on this feature in the API. We want to use this Go client but we would need this feature to be supported.

It is a pretty small change and I could easily make a PR for it. I've already made the change in my own fork:
sunny-b@c581130

CloudProviderSnapshotBackupPolicy: Zero Values are ignored

Unmarshal/Marshal JSON with int set to 0 does not seem to work

type CloudProviderSnapshotBackupPolicy struct {
	ClusterID             string   `json:"clusterId,omitempty"`             //	Unique identifier of the Atlas cluster.
	ClusterName           string   `json:"clusterName,omitempty"`           //	Name of the Atlas cluster.
	ReferenceHourOfDay    int      `json:"referenceHourOfDay,omitempty"`    // UTC Hour of day between 0 and 23, inclusive, representing which hour of the day that Atlas takes snapshots for backup policy items.
	ReferenceMinuteOfHour int      `json:"referenceMinuteOfHour,omitempty"` // UTC Minutes after referenceHourOfDay that Atlas takes snapshots for backup policy items. Must be between 0 and 59, inclusive. Number of days back in time you can restore to with point-in-time accuracy.
	RestoreWindowDays     int      `json:"restoreWindowDays,omitempty"`     // Number of days back in time you can restore to with point-in-time accuracy. Must be a positive, non-zero integer.
	UpdateSnapshots       bool     `json:"updateSnapshots,omitempty"`       // Specify true to apply the retention changes in the updated backup policy to snapshots that Atlas took previously.
	NextSnapshot          string   `json:"nextSnapshot,omitempty"`          // UTC ISO 8601 formatted point in time when Atlas will take the next snapshot.
	Policies              []Policy `json:"policies,omitempty"`              // A list of policy definitions for the cluster.
}

ReferenceHourOfDay, ReferenceMinuteOfHour, and RestoreWindowDays should Unmarshal/Marshal the zero value

Wrong import path?

When I add the import to my go file (XXX/YYYY/ZZZZ file)

import "go.mongodb.org/atlas/mongodbatlas"

all I get is this message:

go: finding module for package go.mongodb.org/atlas/mongodbatlas
go: found go.mongodb.org/atlas/mongodbatlas in go.mongodb.org/atlas v0.3.0
go: github.com/XXX/YYYY/ZZZZ imports
	go.mongodb.org/atlas/mongodbatlas: go.mongodb.org/[email protected]: parsing go.mod:
	module declares its path as: github.com/mongodb/go-client-mongodb-atlas
	        but was required as: go.mongodb.org/atlas

am I doing anything wrong?

undefined: io.Discard and io.ReadAll in latest code push

Describe the bug
Currently, the Go Client is broken due to io.Discard and io.ReadAll being undefined in latest version of the code.

Expected behavior
Should be able to run the Go Client without getting undefined errors unrelated to my code.

Logs

# go.mongodb.org/atlas/mongodbatlas
/root/go/src/go.mongodb.org/atlas/mongodbatlas/mongodbatlas.go:450:20: undefined: io.Discard
/root/go/src/go.mongodb.org/atlas/mongodbatlas/mongodbatlas.go:521:15: undefined: io.ReadAll
Error: Process completed with exit code 2.

Support pagination

The following methods don't support the pagination.

There are some ways to support the pagination.

What do you think?

Can't provide customRole.actions[*].resources[*].collection as empty string

Describe the bug
Because the SDK uses value types instead of pointer types for type Resource.(Db|Collection) users of the SDK will not be able to send empty strings for fields such as collection or db as they will be fully omitted when serialized to JSON.

I've put together an example in "The Go Playground" to demonstrate the issue: https://play.golang.org/p/OHNEv_7HIcc

{"actions":[{"action":"DROP_INDEX","resources":

[{"db":"admin"}]}], //<--- should have "collection": ""

"inheritedRoles":null,"roleName":"500Error"}

Expected behavior
If I set Resource.Collection = "" I should have "collection": "" in the JSON output.

{"actions":[{"action":"DROP_INDEX","resources":

[{"db":"admin", "collection": "" }]}], // "collection": "" exists

"inheritedRoles":null,"roleName":"500Error"}

Logs
https://play.golang.org/p/OHNEv_7HIcc

Desktop (please complete the following information):

  • OS: [e.g. macOS]
  • Lib Version [e.g. 0.6.0]

Additional context
This should be an issue everywhere the SDK is being used. For example, I think it will be an issue here in the terraform provider:

https://github.com/mongodb/terraform-provider-mongodbatlas/blob/master/mongodbatlas/resource_mongodbatlas_custom_db_role.go#L118

Delete user does not work for IAM based users

Describe the bug
Delete user method does not work due to missing url escaping.
Following code does not work because the delete method does not escapes the username, when sending delete request to Atlas mongo api.

groupID := xxxxxxxxxxxx
username := "arn:aws:iam::977946299200:role/complicated-stack-heyhou-eu-we-9e2e2c92c26e1fd5d571582267c271fe"
dbName := $external

resp, err := client.DatabaseUsers.Delete(context.Background(), dbName, groupID, username)

If i escape all the dangerous characters in the url, delete method completes succesfully.

groupID := xxxxxxxxxxxx
username := url.QueryEscape("arn:aws:iam::977946299200:role/complicated-stack-heyhou-eu-we-9e2e2c92c26e1fd5d571582267c271fe")
dbName := $external

resp, err := client.DatabaseUsers.Delete(context.Background(), dbName, groupID, username)

Expected behavior
Username should be escaped automatically.

Logs
If applicable, add logs to help explain your problem.

Desktop (please complete the following information):

  • OS: linux
  • Lib Version: 0.7.2

Additional context
Add any other context about the problem here.

`setListOptions` does not include options from embedded `ListOptions`

Describe the bug
setListOptions only captures struct fields from 1 level deep. It will not capture options from embedded structs like ListOptions.

So when I do the following:

mongodbatlas.EventListOptions{
		ListOptions: mongodbatlas.ListOptions{
			IncludeCount: false,
		},
		EventType: []string{
			"API_KEY_CREATED",
		},
	}

setListOptions drops:

ListOptions: mongodbatlas.ListOptions{
  IncludeCount: false,
},

Expected behavior
A clear and concise description of what you expected to happen.

When I use a struct that embeds ListOptions, the parameters from the embedded ListOptions will be added to my request.

Logs
If applicable, add logs to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. macOS]
  • Lib Version [e.g. 0.6.0]

Additional context
Add any other context about the problem here.

CloudQuery Source Plugin?

Hi Team, hopefully this is right place to ask, if not, I'd appreciate if you can direct me.

I'm the founder of cloudquery.io, a high performance open source ELT framework.

Our users are interested in a MongoDB Atlas plugin, but as we cannot maintain all the plugins ourselves, I was curious if this would be an interesting collaboration, where we would help implement an initial source plugin, and you will help maintain it.

This will give your users the ability to sync MongoDB Atlas APIs to any of their datalakes/data-warehouses/databases easily using any of the growing list of CQ destination plugins (We already support MongoDB destination, which is quite popular destination for ELT workloads and hence the request for the Atlas connector).

Best,
Yevgeny

Unable to set the "authenticationEnabled" = false using the client.LDAPConfigurations.Save()

Describe the bug
Im not being able to set the property, "authenticationEnabled" to FALSE using the client.LDAPConfigurations.Save(), every time this property is provided as FALSE, is discarted, and keeps being TRUE.

in the next example, im executing the save functionality with only the AuthenticationEnabled in False, then getting the ldap configurations with a curl call, and validating that the property is in true.

image

is possible to set that property in false using an api call
image

ive also tried to set it on TURE (original was set on false) and it works ok

image

# Summary: the property AuthenticationEnabled can be set on TRUE, but cannot be set on FALSE

Expected behavior
When providing the property authenticationEnabled in false using the client, should be set in false in the atlas api.

Desktop (please complete the following information):

  • OS: macOS Monterey 12.3
  • Lib Version go.mongodb.org/atlas v0.20.0
  • Go 1.19

Missing `components` in `CloudProviderSnapshotRestoreJob`

Describe the bug
According to the docs here, https://docs.atlas.mongodb.com/reference/api/cloud-backup/restore/get-one-restore-job, there should be a list of components in the response for sharded clusters. This is missing in the response struct.

Expected behavior
To be able to look at components in a CloudProviderSnapshotRestoreJob

Additional context
I think this is the only way to differentiate what each download url for sharded clusters corresponds to, so this is a pretty important feature.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.