-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcreate.go
More file actions
301 lines (242 loc) · 8.27 KB
/
create.go
File metadata and controls
301 lines (242 loc) · 8.27 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// Copyright 2021 - 2024 Crunchy Data Solutions, Inc.
//
// SPDX-License-Identifier: Apache-2.0
package cmd
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/crunchydata/postgres-operator-client/internal"
"github.com/crunchydata/postgres-operator-client/internal/apis/postgres-operator.crunchydata.com/v1beta1"
"github.com/crunchydata/postgres-operator-client/internal/util"
)
// newCreateCommand returns the create subcommand of the PGO plugin.
// Subcommands of create will be use to create objects, backups, etc.
func newCreateCommand(config *internal.Config) *cobra.Command {
cmd := &cobra.Command{
Use: "create",
Short: "Create a resource",
Long: "Create a resource",
}
cmd.AddCommand(newCreateClusterCommand(config))
cmd.AddCommand(newCreateOperatorCommand(config))
return cmd
}
// newCreateClusterCommand returns the create cluster subcommand.
// create cluster will take a cluster name as an argument and create a basic
// cluster using a kube client
func newCreateClusterCommand(config *internal.Config) *cobra.Command {
cmd := &cobra.Command{
Use: "postgrescluster CLUSTER_NAME",
Aliases: []string{"postgresclusters"},
Short: "Create PostgresCluster with a given name",
Long: `Create basic PostgresCluster with a given name.
### RBAC Requirements
Resources Verbs
--------- -----
postgresclusters.postgres-operator.crunchydata.com [create]
### Usage`,
}
cmd.Args = cobra.ExactArgs(1)
var pgMajorVersion int
cmd.Flags().IntVar(&pgMajorVersion, "pg-major-version", 0, "Set the Postgres major version")
cobra.CheckErr(cmd.MarkFlagRequired("pg-major-version"))
var backupsDisabled bool
cmd.Flags().BoolVar(&backupsDisabled, "disable-backups", false, "Disable backups")
cmd.Example = internal.FormatExample(`# Create a postgrescluster with Postgres 15
pgo create postgrescluster hippo --pg-major-version 15
# Create a postgrescluster with backups disabled (only available in CPK v5.7+)
# Requires confirmation
pgo create postgrescluster hippo --disable-backups
### Example output
postgresclusters/hippo created`)
cmd.RunE = func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
clusterName := args[0]
namespace, err := config.Namespace()
if err != nil {
return err
}
mapping, client, err := v1beta1.NewPostgresClusterClient(config)
if err != nil {
return err
}
cluster, err := generateUnstructuredClusterYaml(clusterName, strconv.Itoa(pgMajorVersion))
if err != nil {
return err
}
if backupsDisabled {
fmt.Print("WARNING: Running a production postgrescluster without backups " +
"is not recommended. \nAre you sure you want " +
"to continue without backups? (yes/no): ")
var confirmed *bool
for i := 0; confirmed == nil && i < 10; i++ {
// retry 10 times or until a confirmation is given or denied,
// whichever comes first
confirmed = util.Confirm(os.Stdin, os.Stdout)
}
if confirmed == nil || !*confirmed {
return nil
}
unstructured.RemoveNestedField(cluster.Object, "spec", "backups")
}
u, err := client.
Namespace(namespace).
Create(ctx, cluster, config.Patch.CreateOptions(metav1.CreateOptions{}))
if err != nil {
return err
}
cmd.Printf("%s/%s created\n", mapping.Resource.Resource, u.GetName())
return nil
}
return cmd
}
// generateUnstructuredClusterYaml takes a name and returns a PostgresCluster
// in the unstructured format.
func generateUnstructuredClusterYaml(name, pgMajorVersion string) (*unstructured.Unstructured, error) {
var cluster unstructured.Unstructured
err := yaml.Unmarshal([]byte(fmt.Sprintf(`
apiVersion: postgres-operator.crunchydata.com/v1beta1
kind: PostgresCluster
metadata:
name: %s
spec:
postgresVersion: %s
instances:
- dataVolumeClaimSpec:
accessModes:
- "ReadWriteOnce"
resources:
requests:
storage: 1Gi
backups:
pgbackrest:
repos:
- name: repo1
volume:
volumeClaimSpec:
accessModes:
- "ReadWriteOnce"
resources:
requests:
storage: 1Gi
`, name, pgMajorVersion)), &cluster)
if err != nil {
return nil, err
}
return &cluster, nil
}
// Creating a custom value type that satisfies the Value interface
// https://pkg.go.dev/github.com/spf13/pflag#Value
// This allows us to set a custom enum-type var
type installToolString string
const (
installToolStringKustomize installToolString = "kustomize"
installToolStringHelm installToolString = "helm"
)
func (its *installToolString) String() string {
return string(*its)
}
func (its *installToolString) Set(v string) error {
switch v {
case "kustomize", "helm":
*its = installToolString(v)
return nil
default:
return errors.New(`must be one of "kustomize" or "helm"`)
}
}
// Type is only used in help text
func (its *installToolString) Type() string {
return "installToolString"
}
// newCreateOperatorCommand returns the create operator subcommand.
// create operator will take a cluster name as an argument and create a basic
// operator using a kube client.
func newCreateOperatorCommand(config *internal.Config) *cobra.Command {
cmd := &cobra.Command{
Use: "operator",
Aliases: []string{"operators"},
Short: "Create Postgres-Operator",
Long: `Create Postgres-Operator.
An operator is deployed:
- from any remote or local source (defaults to github.com/CrunchyData/postgres-operator-examples for kustomize installations and oci://registry.developers.crunchydata.com/crunchydata/pgo for Helm installations);
- using either kustomize or Helm (defaults to kustomize).
Note: The tool used to install must already be present.
If Helm is used as the deployment tool, you may optionally supply a name (defaults to "crunchy") and values file (defaults to "values.yaml" file).
### RBAC Requirements
Resources Verbs
--------- -----
pods [create]
TODO...
### Usage`,
}
cmd.Args = cobra.ExactArgs(0)
var source string
cmd.Flags().StringVar(&source,
"source",
"https://github.com/CrunchyData/postgres-operator-examples.git/kustomize/install/default?timeout=120&ref=main",
"Source to deploy the operator from; defaults to github.com/CrunchyData/postgres-operator-examples for kustomize installations and oci://registry.developers.crunchydata.com/crunchydata/pgo for Helm installations")
// Default to using kustomize
var installTool = installToolStringKustomize
cmd.Flags().VarP(&installTool,
"install-tool",
"t",
"Tool to deploy the operator (either kustomize or helm); defaults to kustomize")
var installName string
cmd.Flags().StringVar(&installName,
"name",
"crunchy",
"Name for the Helm installation (defaults to 'crunchy')")
var valueFile string
cmd.Flags().StringVar(&valueFile,
"values",
"",
"Location of a values file")
cmd.Example = internal.FormatExample(`# Create an operator with defaults:
pgo create operator
# Create an operator with Helm in a particular namespace.
# The namespace has to exist prior to the command being run:
pgo create operator --install-tool helm --namespace postgres-operator
# Create an operator...
`)
cmd.RunE = func(cmd *cobra.Command, args []string) error {
// Note: Kustomize has a namespace in the overlay; for now,
// use that namespace.
installNamespace, err := config.Namespace()
if err != nil {
return err
}
var ex *exec.Cmd
// Need to install with --server-side flag due to size
// of CRD
if installTool == installToolStringKustomize {
ex = exec.Command("kubectl", "apply", "--kustomize", source, "--server-side")
}
if installTool == installToolStringHelm {
// If the source wasn't changed from default, set it for our Helm default
if !cmd.Flags().Changed("source") {
source = "oci://registry.developers.crunchydata.com/crunchydata/pgo"
}
args := []string{"install", installName, source, "--namespace", installNamespace}
if valueFile != "" {
args = append(args, "--values", valueFile)
}
ex = exec.Command("helm", args...)
}
msg, err := ex.Output()
if err != nil {
return err
}
cmd.Printf("%s", msg)
return nil
}
return cmd
}