Skip to content

CLOUDP-57864: Backup: Start a restore job #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 13, 2020
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
1 change: 1 addition & 0 deletions internal/cli/atlas_backups_restores.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func AtlasBackupsRestoresBuilder() *cobra.Command {
}

cmd.AddCommand(AtlasBackupsRestoresListBuilder())
cmd.AddCommand(AtlasBackupsRestoresStartBuilder())

return cmd
}
244 changes: 244 additions & 0 deletions internal/cli/atlas_backups_restores_start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
// Copyright 2020 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 cli

import (
"errors"
"fmt"

atlas "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"
"github.com/mongodb/mongocli/internal/config"
"github.com/mongodb/mongocli/internal/flags"
"github.com/mongodb/mongocli/internal/json"
"github.com/mongodb/mongocli/internal/store"
"github.com/mongodb/mongocli/internal/usage"
"github.com/spf13/cobra"
)

const (
automatedRestore = "AUTOMATED_RESTORE"
httpRestore = "HTTP"
onlyFor = "'%s' can only be used with %s"
)

type atlasBackupsRestoresStartOpts struct {
*globalOpts
method string
clusterName string
clusterID string
targetProjectID string
targetClusterID string
targetClusterName string
checkpointID string
oplogTs string
oplogInc int64
snapshotID string
expirationHours int64
expires string
maxDownloads int64
pointInTimeUTCMillis float64
store store.ContinuousJobCreator
}

func (opts *atlasBackupsRestoresStartOpts) init() error {
if opts.ProjectID() == "" {
return errMissingProjectID
}

var err error
opts.store, err = store.New()
return err
}

func (opts *atlasBackupsRestoresStartOpts) Run() error {
request := opts.newContinuousJobRequest()

result, err := opts.store.CreateContinuousRestoreJob(opts.ProjectID(), opts.fromCluster(), request)

if err != nil {
return err
}

return json.PrettyPrint(result)
}

func (opts *atlasBackupsRestoresStartOpts) newContinuousJobRequest() *atlas.ContinuousJobRequest {
request := new(atlas.ContinuousJobRequest)
request.Delivery.MethodName = opts.method
request.SnapshotID = opts.snapshotID

if opts.isAutomatedRestore() {
request.Delivery.TargetGroupID = opts.targetProjectID
opts.setTargetCluster(request)

if opts.oplogTs != "" && opts.oplogInc != 0 {
request.OplogTs = opts.oplogTs
request.OplogInc = opts.oplogInc
}
if opts.pointInTimeUTCMillis != 0 {
request.PointInTimeUTCMillis = opts.pointInTimeUTCMillis
}
}

if opts.isHTTP() {
if opts.expires != "" {
request.Delivery.Expires = opts.expires
}
if opts.maxDownloads > 0 {
request.Delivery.MaxDownloads = opts.maxDownloads
}
if opts.expirationHours > 0 {
request.Delivery.ExpirationHours = opts.expirationHours
}
}
return request
}

func (opts *atlasBackupsRestoresStartOpts) fromCluster() string {
if opts.clusterName != "" {
return opts.clusterName
}
return opts.clusterID
}

func (opts *atlasBackupsRestoresStartOpts) setTargetCluster(out *atlas.ContinuousJobRequest) {
if opts.targetClusterID != "" {
out.Delivery.TargetClusterID = opts.targetClusterID
} else if opts.targetClusterName != "" {
out.Delivery.TargetClusterName = opts.targetClusterName
}
}

func (opts *atlasBackupsRestoresStartOpts) isAutomatedRestore() bool {
return opts.method == automatedRestore
}

func (opts *atlasBackupsRestoresStartOpts) isHTTP() bool {
return opts.method == httpRestore
}

func (opts *atlasBackupsRestoresStartOpts) validateParams() error {
if (opts.clusterName == "" && opts.clusterID == "") || (opts.clusterName != "" && opts.clusterID != "") {
return errors.New("needs clusterName or clusterId")
}

if !opts.isAutomatedRestore() {
if e := opts.automatedRestoreOnlyFlags(); e != nil {
return e
}
}

if !opts.isHTTP() {
if e := opts.httpRestoreOnlyFlags(); e != nil {
return e
}
}

return nil
}

func (opts *atlasBackupsRestoresStartOpts) httpRestoreOnlyFlags() error {
if opts.expires != "" {
return fmt.Errorf(onlyFor, flags.Expires, httpRestore)
}
if opts.maxDownloads > 0 {
return fmt.Errorf(onlyFor, flags.MaxDownloads, httpRestore)
}
if opts.expirationHours > 0 {
return fmt.Errorf(onlyFor, flags.ExpirationHours, httpRestore)
}
return nil
}

func (opts *atlasBackupsRestoresStartOpts) automatedRestoreOnlyFlags() error {
if opts.checkpointID != "" {
return fmt.Errorf(onlyFor, flags.CheckpointID, automatedRestore)
}
if opts.oplogTs != "" {
return fmt.Errorf(onlyFor, flags.OplogTs, automatedRestore)
}
if opts.oplogInc > 0 {
return fmt.Errorf(onlyFor, flags.OplogInc, automatedRestore)
}
if opts.pointInTimeUTCMillis > 0 {
return fmt.Errorf(onlyFor, flags.PointInTimeUTCMillis, automatedRestore)
}
return nil
}

func markRequiredAutomatedRestoreFlags(cmd *cobra.Command) error {
if err := cmd.MarkFlagRequired(flags.TargetProjectID); err != nil {
return err
}

if config.Service() == config.CloudService {
return cmd.MarkFlagRequired(flags.ClusterName)
}
return cmd.MarkFlagRequired(flags.ClusterID)
}

// mongocli atlas backup(s) restore(s) job(s) start
func AtlasBackupsRestoresStartBuilder() *cobra.Command {
opts := &atlasBackupsRestoresStartOpts{
globalOpts: newGlobalOpts(),
}
cmd := &cobra.Command{
Use: "start",
Short: "Start a restore job.",
Args: cobra.ExactValidArgs(1),
ValidArgs: []string{automatedRestore, httpRestore},
PreRunE: func(cmd *cobra.Command, args []string) error {
if opts.isAutomatedRestore() {
if err := markRequiredAutomatedRestoreFlags(cmd); err != nil {
return err
}
}
return opts.init()
},
RunE: func(cmd *cobra.Command, args []string) error {
opts.method = args[0]

if e := opts.validateParams(); e != nil {
return e
}

return opts.Run()
},
}

cmd.Flags().StringVar(&opts.snapshotID, flags.SnapshotID, "", usage.SnapshotID)
// Atlas uses cluster name
cmd.Flags().StringVar(&opts.clusterName, flags.ClusterName, "", usage.ClusterName)
// C/OM uses cluster ID
cmd.Flags().StringVar(&opts.clusterID, flags.ClusterID, "", usage.ClusterID)

// For Automatic restore
cmd.Flags().StringVar(&opts.targetProjectID, flags.TargetProjectID, "", usage.TargetProjectID)
cmd.Flags().StringVar(&opts.targetClusterID, flags.TargetClusterID, "", usage.TargetClusterID)
cmd.Flags().StringVar(&opts.targetClusterName, flags.TargetClusterName, "", usage.TargetClusterName)
cmd.Flags().StringVar(&opts.checkpointID, flags.CheckpointID, "", usage.CheckpointID)
cmd.Flags().StringVar(&opts.oplogTs, flags.OplogTs, "", usage.OplogTs)
cmd.Flags().Int64Var(&opts.oplogInc, flags.OplogInc, 0, usage.OplogInc)
cmd.Flags().Float64Var(&opts.pointInTimeUTCMillis, flags.PointInTimeUTCMillis, 0, usage.PointInTimeUTCMillis)

// For http restore
cmd.Flags().StringVar(&opts.expires, flags.Expires, "", usage.Expires)
cmd.Flags().Int64Var(&opts.maxDownloads, flags.MaxDownloads, 0, usage.MaxDownloads)
cmd.Flags().Int64Var(&opts.expirationHours, flags.ExpirationHours, 0, usage.ExpirationHours)

cmd.Flags().StringVar(&opts.projectID, flags.ProjectID, "", usage.ProjectID)

return cmd
}
72 changes: 72 additions & 0 deletions internal/cli/atlas_backups_restores_start_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2020 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 cli

import (
"testing"

"github.com/golang/mock/gomock"
"github.com/mongodb/mongocli/internal/fixtures"
"github.com/mongodb/mongocli/internal/mocks"
)

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

defer ctrl.Finish()

expected := fixtures.ContinuousJob()

t.Run(automatedRestore, func(t *testing.T) {
listOpts := &atlasBackupsRestoresStartOpts{
globalOpts: newGlobalOpts(),
store: mockStore,
method: automatedRestore,
clusterName: "Cluster0",
}

mockStore.
EXPECT().
CreateContinuousRestoreJob(listOpts.projectID, "Cluster0", listOpts.newContinuousJobRequest()).
Return(expected, nil).
Times(1)

err := listOpts.Run()
if err != nil {
t.Fatalf("Run() unexpected error: %v", err)
}
})

t.Run(httpRestore, func(t *testing.T) {
listOpts := &atlasBackupsRestoresStartOpts{
globalOpts: newGlobalOpts(),
store: mockStore,
method: httpRestore,
clusterName: "Cluster0",
}

mockStore.
EXPECT().
CreateContinuousRestoreJob(listOpts.projectID, "Cluster0", listOpts.newContinuousJobRequest()).
Return(expected, nil).
Times(1)

err := listOpts.Run()
if err != nil {
t.Fatalf("Run() unexpected error: %v", err)
}
})
}
35 changes: 17 additions & 18 deletions internal/fixtures/continuous_jobs.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
// Copyright 2020 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 fixtures

import atlas "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"

func AutomatedContinuousJob() *atlas.ContinuousJob {
return &atlas.ContinuousJob{
BatchID: "",
ClusterID: "",
Created: "",
ClusterName: "",
Delivery: nil,
EncryptionEnabled: false,
GroupID: "",
Hashes: nil,
ID: "",
Links: nil,
MasterKeyUUID: "",
SnapshotID: "",
StatusName: "",
PointInTime: nil,
Timestamp: atlas.SnapshotTimestamp{},
}
// TODO: https://github.com/mongodb/go-client-mongodb-atlas/pull/64
func ContinuousJob() *atlas.ContinuousJob {
return &atlas.ContinuousJob{}
}

func ContinuousJobs() *atlas.ContinuousJobs {
Expand Down
14 changes: 14 additions & 0 deletions internal/fixtures/continuous_snapshots.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
// Copyright 2020 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 fixtures

import atlas "github.com/mongodb/go-client-mongodb-atlas/mongodbatlas"
Expand Down
Loading