This repository has been archived by the owner on May 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
namespace.go
231 lines (205 loc) · 6.17 KB
/
namespace.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
package namespace
import (
"fmt"
"github.com/jenkins-x/jx-helpers/pkg/cobras/helper"
"github.com/jenkins-x/jx-helpers/pkg/cobras/templates"
"github.com/jenkins-x/jx-helpers/pkg/input"
"github.com/jenkins-x/jx-helpers/pkg/input/survey"
"github.com/jenkins-x/jx-kube-client/pkg/kubeclient"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/spf13/cobra"
"github.com/pkg/errors"
"github.com/jenkins-x/jx-helpers/pkg/kube"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/clientcmd"
"sort"
"github.com/jenkins-x/jx-helpers/pkg/termcolor"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd/api"
)
type Options struct {
KubeClient kubernetes.Interface
Input input.Interface
Args []string
Create bool
BatchMode bool
}
var (
cmdLong = templates.LongDesc(`
Displays or changes the current namespace.`)
cmdExample = templates.Examples(`
# view the current namespace
jx --batch-mode ns
# interactively select the namespace to switch to
jx ns
# change the current namespace to 'cheese'
jx ns cheese
# change the current namespace to 'brie' creating it if necessary
jx ns --create brie`)
)
func NewCmdNamespace() (*cobra.Command, *Options) {
options := &Options{}
cmd := &cobra.Command{
Use: "namespace",
Aliases: []string{"ns"},
Short: "View or change the current namespace context in the current Kubernetes cluster",
Long: cmdLong,
Example: cmdExample,
Run: func(cmd *cobra.Command, args []string) {
options.Args = args
err := options.Run()
helper.CheckErr(err)
},
}
cmd.Flags().BoolVarP(&options.Create, "create", "c", false, "Creates the specified namespace if it does not exist")
cmd.Flags().BoolVarP(&options.BatchMode, "batch-mode", "b", false, "Enables batch mode")
return cmd, options
}
func (o *Options) Run() error {
var err error
currentNS := ""
o.KubeClient, currentNS, err = kube.LazyCreateKubeClientAndNamespace(o.KubeClient, "")
if err != nil {
return errors.Wrap(err, "creating kubernetes client")
}
client := o.KubeClient
f := kubeclient.NewFactory()
config, err := f.CreateKubeConfig()
if err != nil {
return errors.Wrap(err, "creating kubernetes configuration")
}
cfg, pathOptions, err := kubeclient.LoadConfig()
if err != nil {
return errors.Wrap(err, "loading Kubernetes configuration")
}
ns := namespace(o)
if ns == "" && !o.BatchMode {
ns, err = pickNamespace(o, client, currentNS)
if err != nil {
return err
}
}
info := termcolor.ColorInfo
if ns != "" && ns != currentNS {
ctx, err := changeNamespace(client, cfg, pathOptions, ns, o.Create)
if err != nil {
return err
}
if ctx == nil {
log.Logger().Infof("No kube context - probably in a unit test or pod?\n")
} else {
log.Logger().Infof("Now using namespace '%s' on server '%s'.\n", info(ctx.Namespace), info(kube.Server(cfg, ctx)))
}
} else {
if currentNS != "" {
ns = currentNS
}
server := kube.CurrentServer(cfg)
if config == nil {
log.Logger().Infof("Using namespace '%s' on server '%s'. No context - probably a unit test or pod?\n", info(ns), info(server))
} else {
log.Logger().Infof("Using namespace '%s' from context named '%s' on server '%s'.\n", info(ns), info(cfg.CurrentContext), info(server))
}
}
return nil
}
func namespace(o *Options) string {
ns := ""
args := o.Args
if len(args) > 0 {
ns = args[0]
}
return ns
}
func changeNamespace(client kubernetes.Interface, config *api.Config, pathOptions clientcmd.ConfigAccess, ns string, create bool) (*api.Context, error) {
_, err := client.CoreV1().Namespaces().Get(ns, metav1.GetOptions{})
if err != nil {
switch err.(type) {
case *apierrors.StatusError:
err = handleStatusError(err, client, ns, create)
if err != nil {
return nil, err
}
default:
return nil, errors.Wrapf(err, "getting namespace %q", ns)
}
}
newConfig := *config
ctx := kube.CurrentContext(config)
if ctx == nil {
log.Logger().Warnf("there is no context defined in your Kubernetes configuration - we may be inside a test case or pod?\n")
return ctx, nil
}
if ctx.Namespace == ns {
return ctx, nil
}
ctx.Namespace = ns
err = clientcmd.ModifyConfig(pathOptions, newConfig, false)
if err != nil {
return nil, fmt.Errorf("failed to update the kube config %s", err)
}
return ctx, nil
}
func handleStatusError(err error, client kubernetes.Interface, ns string, create bool) error {
statusErr, _ := err.(*apierrors.StatusError)
if statusErr.Status().Reason == metav1.StatusReasonNotFound && create {
err = createNamespace(client, ns)
if err != nil {
return err
}
} else {
return err
}
return nil
}
func createNamespace(client kubernetes.Interface, ns string) error {
namespace := corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: ns,
},
}
_, err := client.CoreV1().Namespaces().Create(&namespace)
if err != nil {
return errors.Wrapf(err, "unable to create namespace %s", ns)
}
return nil
}
func pickNamespace(o *Options, client kubernetes.Interface, defaultNamespace string) (string, error) {
names, err := getNamespaceNames(client)
if err != nil {
return "", errors.Wrap(err, "retrieving namespace the names of the namespaces")
}
selectedNamespace, err := pick(o, names, defaultNamespace)
if err != nil {
return "", errors.Wrap(err, "picking the namespace")
}
return selectedNamespace, nil
}
// getNamespaceNames returns the sorted list of environment names
func getNamespaceNames(client kubernetes.Interface) ([]string, error) {
var names []string
list, err := client.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
return names, fmt.Errorf("loading namespaces %s", err)
}
for k := range list.Items {
names = append(names, list.Items[k].Name)
}
sort.Strings(names)
return names, nil
}
func pick(o *Options, names []string, defaultNamespace string) (string, error) {
if len(names) == 0 {
return "", nil
}
if len(names) == 1 {
return names[0], nil
}
if o.Input == nil {
o.Input = survey.NewInput()
}
name, err := o.Input.PickNameWithDefault(names, "Change namespace:", defaultNamespace, "pick the kubernetes namespace for the current kubernetes cluster")
return name, err
}