Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions docs/command/atlas-backups-snapshots-download.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
.. _atlas-backups-snapshots-download:

================================
atlas backups snapshots download
================================

.. default-domain:: mongodb

.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol

Download one snapshot for the specified flex cluster.

You can download a snapshot for an Atlas Flex cluster.
To use this command, you must authenticate with a user account or an API key with the Project Owner role.
Atlas supports this command only for Flex clusters.

Syntax
------

.. code-block::
:caption: Command Syntax

atlas backups snapshots download <snapshotId> [options]

.. Code end marker, please don't delete this comment

Arguments
---------

.. list-table::
:header-rows: 1
:widths: 20 10 10 60

* - Name
- Type
- Required
- Description
* - snapshotId
- string
- true
- Unique 24-hexadecimal digit string that identifies the snapshot to download.

Options
-------

.. list-table::
:header-rows: 1
:widths: 20 10 10 60

* - Name
- Type
- Required
- Description
* - --clusterName
- string
- true
- Name of the cluster. To learn more, see https://dochub.mongodb.org/core/create-cluster-api.
* - -h, --help
-
- false
- help for download
* - --out
- string
- false
- Output file name. This value defaults to the Snapshot id.
* - --projectId
- string
- false
- Hexadecimal string that identifies the project to use. This option overrides the settings in the configuration file or environment variable.

Inherited Options
-----------------

.. list-table::
:header-rows: 1
:widths: 20 10 10 60

* - Name
- Type
- Required
- Description
* - -P, --profile
- string
- false
- Name of the profile to use from your configuration file. To learn about profiles for the Atlas CLI, see https://dochub.mongodb.org/core/atlas-cli-save-connection-settings.

Output
------

If the command succeeds, the CLI returns output similar to the following sample. Values in brackets represent your values.

.. code-block::

Snapshot '<Name>' downloaded.


2 changes: 2 additions & 0 deletions docs/command/atlas-backups-snapshots.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Related Commands
* :ref:`atlas-backups-snapshots-create` - Create a backup snapshot for your project and cluster.
* :ref:`atlas-backups-snapshots-delete` - Remove the specified backup snapshot.
* :ref:`atlas-backups-snapshots-describe` - Return the details for the specified snapshot for your project.
* :ref:`atlas-backups-snapshots-download` - Download one snapshot for the specified flex cluster.
* :ref:`atlas-backups-snapshots-list` - Return all cloud backup snapshots for your project and cluster.
* :ref:`atlas-backups-snapshots-watch` - Watch the specified snapshot in your project until it becomes available.

Expand All @@ -62,6 +63,7 @@ Related Commands
create </command/atlas-backups-snapshots-create>
delete </command/atlas-backups-snapshots-delete>
describe </command/atlas-backups-snapshots-describe>
download </command/atlas-backups-snapshots-download>
list </command/atlas-backups-snapshots-list>
watch </command/atlas-backups-snapshots-watch>

156 changes: 156 additions & 0 deletions internal/cli/backup/snapshots/download.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Copyright 2024 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package snapshots

import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"

"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/require"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/flag"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/store"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/usage"
"github.com/spf13/afero"
"github.com/spf13/cobra"
atlasv2 "go.mongodb.org/atlas-sdk/v20241113004/admin"
)

type DownloadOpts struct {
cli.ProjectOpts
cli.DownloaderOpts
cli.OutputOpts
store store.SnapshotsDownloader
clusterName string
id string
}

func (opts *DownloadOpts) initStore(ctx context.Context) func() error {
return func() error {
var err error
opts.store, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx))
return err
}
}

var downloadTemplate = "Snapshot '%s' downloaded.\n"
var errEmptyURL = errors.New("'snapshotUrl' is empty")
var errExtNotSupported = errors.New("only the '.tgz' extension is supported")

func (opts *DownloadOpts) Run() error {
r, err := opts.store.DownloadFlexClusterSnapshot(opts.ConfigProjectID(), opts.clusterName, opts.newFlexBackupSnapshotDownloadCreate())
if err != nil {
return err
}

return opts.Download(r.SnapshotUrl)
}

func (opts *DownloadOpts) newFlexBackupSnapshotDownloadCreate() *atlasv2.FlexBackupSnapshotDownloadCreate20241113 {
return &atlasv2.FlexBackupSnapshotDownloadCreate20241113{
SnapshotId: opts.id,
}
}

func (opts *DownloadOpts) Download(url *string) error {
if url == nil {
return errEmptyURL
}

w, err := opts.NewWriteCloser()
if err != nil {
return err
}
defer w.Close()

req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, *url, nil)
if err != nil {
return err
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}

defer resp.Body.Close()
if err != nil {
_ = opts.OnError(w)
return err
}

if _, err := io.Copy(w, resp.Body); err != nil {
_ = opts.OnError(w)
return err
}

fmt.Printf(downloadTemplate, opts.Out)
return nil
}

func (opts *DownloadOpts) initDefaultOut() error {
if opts.Out == "" {
opts.Out = opts.id + ".tgz"
} else if !strings.Contains(opts.Out, ".tgz") {
return errExtNotSupported
}

return nil
}

// DownloadBuilder builds a cobra.Command that can run as:
// atlas backup snapshots download snapshotId --clusterName string [--projectId string] [--out string].
func DownloadBuilder() *cobra.Command {
opts := &DownloadOpts{}
opts.Fs = afero.NewOsFs()
cmd := &cobra.Command{
Use: "download <snapshotId>",
Short: "Download one snapshot for the specified flex cluster.",
Long: `You can download a snapshot for an Atlas Flex cluster.
` + fmt.Sprintf("%s\n%s", fmt.Sprintf(usage.RequiredRole, "Project Owner"), "Atlas supports this command only for Flex clusters."),
Args: require.ExactArgs(1),
Annotations: map[string]string{
"snapshotIdDesc": "Unique 24-hexadecimal digit string that identifies the snapshot to download.",
"output": downloadTemplate,
},
PreRunE: func(cmd *cobra.Command, _ []string) error {
return opts.PreRunE(
opts.ValidateProjectID,
opts.initStore(cmd.Context()),
opts.InitOutput(cmd.OutOrStdout(), createTemplate),
)
},
RunE: func(_ *cobra.Command, args []string) error {
opts.id = args[0]
if err := opts.initDefaultOut(); err != nil {
return err
}
return opts.Run()
},
}
cmd.Flags().StringVar(&opts.clusterName, flag.ClusterName, "", usage.ClusterName)
cmd.Flags().StringVar(&opts.Out, flag.Out, "", usage.SnapshotOut)

opts.AddProjectOptsFlags(cmd)

_ = cmd.MarkFlagRequired(flag.ClusterName)

return cmd
}
51 changes: 51 additions & 0 deletions internal/cli/backup/snapshots/download_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Copyright 2024 MongoDB Inc
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package snapshots

import (
"testing"

"github.com/golang/mock/gomock"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/mocks"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/pointer"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
atlasv2 "go.mongodb.org/atlas-sdk/v20241113004/admin"
)

func TestSnapshotDownloadOpts_Run(t *testing.T) {
ctrl := gomock.NewController(t)
mockStore := mocks.NewMockSnapshotsDownloader(ctrl)

opts := &DownloadOpts{
id: "test.tgz",
store: mockStore,
clusterName: "test",
}
opts.Out = opts.id
opts.Fs = afero.NewMemMapFs()

expected := &atlasv2.FlexBackupRestoreJob20241113{
SnapshotUrl: pointer.Get("test.tgz"),
}

mockStore.
EXPECT().
DownloadFlexClusterSnapshot(opts.ConfigProjectID(), opts.clusterName, opts.newFlexBackupSnapshotDownloadCreate()).
Return(expected, nil).
Times(1)

require.Error(t, opts.Run(), errEmptyURL.Error())
}
1 change: 1 addition & 0 deletions internal/cli/backup/snapshots/snapshots.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func Builder() *cobra.Command {
DescribeBuilder(),
WatchBuilder(),
DeleteBuilder(),
DownloadBuilder(),
)

return cmd
Expand Down
3 changes: 1 addition & 2 deletions internal/store/cloud_provider_backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,7 @@ func (s *Store) FlexClusterSnapshots(opts *atlasv2.ListFlexBackupsApiParams) (*a
return result, err
}

// DownloadFlexClusterSnapshots encapsulates the logic to manage different cloud providers.
func (s *Store) DownloadFlexClusterSnapshots(groupID, name string, flexBackupSnapshotDownloadCreate20241113 *atlasv2.FlexBackupSnapshotDownloadCreate20241113) (*atlasv2.FlexBackupRestoreJob20241113, error) {
func (s *Store) DownloadFlexClusterSnapshot(groupID, name string, flexBackupSnapshotDownloadCreate20241113 *atlasv2.FlexBackupSnapshotDownloadCreate20241113) (*atlasv2.FlexBackupRestoreJob20241113, error) {
if s.service == config.CloudGovService {
return nil, fmt.Errorf("%w: %s", errUnsupportedService, s.service)
}
Expand Down
1 change: 1 addition & 0 deletions internal/usage/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ dbName and collection are required only for built-in roles.`
ForceFile = "Flag that indicates whether to overwrite the destination file."
Email = "Email address for the user."
LogOut = "Output file name. This value defaults to the log name."
SnapshotOut = "Output file name. This value defaults to the Snapshot id."
LogStart = "UNIX Epoch-formatted starting date and time for the range of log messages to retrieve. This value defaults to 24 hours prior to the current timestamp."
LogEnd = "Ending date and time for the range of log messages to retrieve, given in UNIX time. Defaults to the start date plus 24 hours, if the start date is set. If start date is not provided, ending time defaults to the current time."
MeasurementStart = "ISO 8601-formatted date and time that specifies when to start retrieving measurements. You can't set this parameter and period in the same request."
Expand Down
Loading