/
deployment_opts.go
265 lines (230 loc) · 8.27 KB
/
deployment_opts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Copyright 2023 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 options
import (
"context"
"errors"
"fmt"
"io"
"regexp"
"sort"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/briandowns/spinner"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/cli/atlas/setup"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/config"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/log"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/podman"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/search"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/store"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/telemetry"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/terminal"
"github.com/mongodb/mongodb-atlas-cli/atlascli/internal/usage"
)
const (
MongodHostnamePrefix = "mongod"
MongotHostnamePrefix = "mongot"
CheckHostnamePrefix = "check"
spinnerSpeed = 100 * time.Millisecond
// based on https://www.mongodb.com/docs/atlas/reference/api-resources-spec/v2/#tag/Clusters/operation/createCluster
clusterNamePattern = "^[a-zA-Z0-9][a-zA-Z0-9-]*$"
MongotDockerImageName = "docker.io/mongodb/mongodb-atlas-search:preview"
PausedState = "PAUSED"
StoppedState = "STOPPED"
IdleState = "IDLE"
DeletingState = "DELETING"
RestartingState = "RESTARTING"
LocalCluster = "local"
AtlasCluster = "atlas"
CompassConnect = "compass"
MongoshConnect = "mongosh"
PromptTypeMessage = "What type of deployment would you like to work with?"
MaxItemsPerPage = 500
)
var (
errInvalidDeploymentName = errors.New("invalid cluster name")
errDeploymentTypeNotImplemented = errors.New("deployment type not implemented")
ErrNotAuthenticated = errors.New("you are not authenticated. Please, run atlas auth login")
ErrCompassNotInstalled = errors.New("did not find MongoDB Compass, install: https://dochub.mongodb.org/core/install-compass")
ErrMongoshNotInstalled = errors.New("did not find mongosh, install: https://dochub.mongodb.org/core/install-mongosh")
DeploymentTypeOptions = []string{LocalCluster, AtlasCluster}
deploymentTypeDescription = map[string]string{
LocalCluster: "Local Database",
AtlasCluster: "Atlas Database",
}
)
var localStateMap = map[string]string{
"running": IdleState,
"removing": DeletingState,
// a "created" container is ready to be started but is currently stopped
"created": StoppedState,
"paused": PausedState,
"restarting": RestartingState,
"exited": StoppedState,
"dead": StoppedState,
}
type DeploymentOpts struct {
DeploymentName string
DeploymentType string
MdbVersion string
Port int
DBUsername string
DBUserPassword string
PodmanClient podman.Client
CredStore store.CredentialsGetter
s *spinner.Spinner
DefaultSetter cli.DefaultSetterOpts
AtlasClusterListStore store.ClusterLister
Config setup.ProfileReader
DeploymentTelemetry DeploymentTelemetry
}
type Deployment struct {
Type string
Name string
MongoDBVersion string
StateName string
}
func (opts *DeploymentOpts) InitStore(ctx context.Context, writer io.Writer) func() error {
return func() error {
var err error
opts.PodmanClient = podman.NewClient()
opts.Config = config.Default()
opts.CredStore = config.Default()
if opts.AtlasClusterListStore, err = store.New(store.AuthenticatedPreset(config.Default()), store.WithContext(ctx)); err != nil {
return err
}
opts.DefaultSetter.OutWriter = writer
opts.DeploymentTelemetry = NewDeploymentTypeTelemetry(opts)
opts.UpdateDeploymentTelemetry()
return opts.DefaultSetter.InitStore(ctx)
}
}
func (opts *DeploymentOpts) LocalMongodHostname() string {
return fmt.Sprintf("%s-%s", MongodHostnamePrefix, opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalMongotHostname() string {
return fmt.Sprintf("%s-%s", MongotHostnamePrefix, opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalCheckHostname() string {
return fmt.Sprintf("%s-%s", CheckHostnamePrefix, opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalNetworkName() string {
return fmt.Sprintf("mdb-local-%s", opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalMongotDataVolume() string {
return fmt.Sprintf("mongot-local-data-%s", opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalMongodDataVolume() string {
return fmt.Sprintf("mongod-local-data-%s", opts.DeploymentName)
}
func (opts *DeploymentOpts) LocalMongoMetricsVolume() string {
return fmt.Sprintf("mongot-local-metrics-%s", opts.DeploymentName)
}
func (opts *DeploymentOpts) MongodDockerImageName() string {
return fmt.Sprintf("docker.io/mongodb/mongodb-enterprise-server:%s-ubi8", opts.MdbVersion)
}
func LocalDeploymentName(hostname string) string {
return strings.TrimPrefix(hostname, fmt.Sprintf("%s-", MongodHostnamePrefix))
}
func (opts *DeploymentOpts) StartSpinner() {
if terminal.IsTerminal(log.Writer()) {
opts.s = spinner.New(spinner.CharSets[9], spinnerSpeed)
opts.s.Start()
}
}
func (opts *DeploymentOpts) StopSpinner() {
if terminal.IsTerminal(log.Writer()) {
opts.s.Stop()
}
}
func ValidateDeploymentName(n string) error {
if matched, _ := regexp.MatchString(clusterNamePattern, n); !matched {
return fmt.Errorf("%w: %s", errInvalidDeploymentName, n)
}
return nil
}
func (opts *DeploymentOpts) IsCliAuthenticated() bool {
if opts.CredStore == nil {
opts.CredStore = config.Default()
}
return opts.CredStore.AuthType() != config.NotLoggedIn
}
func (opts *DeploymentOpts) GetLocalDeployments(ctx context.Context) ([]Deployment, error) {
mdbContainers, err := opts.PodmanClient.ListContainers(ctx, MongodHostnamePrefix)
if err != nil {
return nil, err
}
sort.Slice(mdbContainers, func(i, j int) bool {
return mdbContainers[i].Names[0] < mdbContainers[j].Names[0]
})
deployments := make([]Deployment, len(mdbContainers))
for i, c := range mdbContainers {
stateName, found := localStateMap[c.State]
if !found {
stateName = strings.ToUpper(c.State)
}
name := strings.TrimPrefix(c.Names[0], MongodHostnamePrefix+"-")
deployments[i] = Deployment{
Type: "LOCAL",
Name: name,
MongoDBVersion: c.Labels["version"],
StateName: stateName,
}
}
return deployments, nil
}
func (opts *DeploymentOpts) promptDeploymentType() error {
p := &survey.Select{
Message: PromptTypeMessage,
Options: DeploymentTypeOptions,
Help: usage.DeploymentType,
Description: func(value string, _ int) string {
return deploymentTypeDescription[value]
},
}
return telemetry.TrackAskOne(p, &opts.DeploymentType, nil)
}
func validateDeploymentType(s string) error {
if !search.StringInSliceFold(DeploymentTypeOptions, s) {
return fmt.Errorf("%w: %s", errDeploymentTypeNotImplemented, s)
}
return nil
}
func (opts *DeploymentOpts) ValidateAndPromptDeploymentType() error {
if opts.DeploymentType == "" {
if err := opts.promptDeploymentType(); err != nil {
return err
}
} else if err := validateDeploymentType(opts.DeploymentType); err != nil {
return err
}
return nil
}
func (opts *DeploymentOpts) IsAtlasDeploymentType() bool {
return strings.EqualFold(opts.DeploymentType, AtlasCluster)
}
func (opts *DeploymentOpts) IsLocalDeploymentType() bool {
return strings.EqualFold(opts.DeploymentType, LocalCluster)
}
func (opts *DeploymentOpts) NoDeploymentTypeSet() bool {
return strings.EqualFold(opts.DeploymentType, "")
}
func (opts *DeploymentOpts) IsAuthEnabled() bool {
return opts.DBUsername != ""
}
func (opts *DeploymentOpts) UpdateDeploymentTelemetry() {
opts.DeploymentTelemetry.AppendDeploymentType()
}