/
approve_migration.go
97 lines (82 loc) · 2.57 KB
/
approve_migration.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
package schemaherokubectlcli
import (
"context"
"fmt"
"time"
"github.com/pkg/errors"
"github.com/schemahero/schemahero/pkg/apis/schemas/v1alpha4"
schemasclientv1alpha4 "github.com/schemahero/schemahero/pkg/client/schemaheroclientset/typed/schemas/v1alpha4"
"github.com/schemahero/schemahero/pkg/config"
"github.com/spf13/cobra"
"github.com/spf13/viper"
kuberneteserrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
func ApproveMigrationCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "migration",
Short: "",
Long: `...`,
Args: cobra.MinimumNArgs(1),
SilenceErrors: true,
SilenceUsage: true,
PreRun: func(cmd *cobra.Command, args []string) {
viper.BindPFlags(cmd.Flags())
},
RunE: func(cmd *cobra.Command, args []string) error {
v := viper.GetViper()
ctx := context.Background()
migrationName := args[0]
cfg, err := config.GetRESTConfig()
if err != nil {
return err
}
client, err := kubernetes.NewForConfig(cfg)
if err != nil {
return err
}
schemasClient, err := schemasclientv1alpha4.NewForConfig(cfg)
if err != nil {
return err
}
namespaceNames := []string{}
if viper.GetBool("all-namespaces") {
namespaces, err := client.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
for _, namespace := range namespaces.Items {
namespaceNames = append(namespaceNames, namespace.Name)
}
} else {
if v.GetString("namespace") != "" {
namespaceNames = []string{v.GetString("namespace")}
} else {
namespaceNames = []string{"default"}
}
}
for _, namespaceName := range namespaceNames {
migration, err := schemasClient.Migrations(namespaceName).Get(ctx, migrationName, metav1.GetOptions{})
if kuberneteserrors.IsNotFound(err) {
// continue to the next namespace
continue
}
if err != nil {
return err
}
migration.Status.ApprovedAt = time.Now().Unix()
migration.Status.Phase = v1alpha4.Approved
if _, err := schemasClient.Migrations(namespaceName).Update(ctx, migration, metav1.UpdateOptions{}); err != nil {
return err
}
fmt.Printf("Migration %s approved\n", migrationName)
return nil
}
err = errors.Errorf("migration %q not found", migrationName)
return err
},
}
cmd.Flags().Bool("all-namespaces", false, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.")
return cmd
}