This repository has been archived by the owner on Jul 16, 2018. It is now read-only.
/
environ.go
225 lines (188 loc) · 6.35 KB
/
environ.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
/*
*
* 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 cmds
import (
"fmt"
"strings"
"strconv"
"github.com/fabric8io/gofabric8/client"
"github.com/fabric8io/gofabric8/util"
"github.com/spf13/cobra"
yaml "gopkg.in/yaml.v2"
"k8s.io/kubernetes/pkg/api"
k8api "k8s.io/kubernetes/pkg/api/unversioned"
restclient "k8s.io/kubernetes/pkg/client/restclient"
k8client "k8s.io/kubernetes/pkg/client/unversioned"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
type EnvironmentData struct {
Name string `yaml:"name"`
Namespace string `yaml:"namespace"`
Order int `yaml:"order"`
}
func NewCmdGetEnviron(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "environ",
Short: "Get environment from fabric8-environments configmap",
Run: func(cmd *cobra.Command, args []string) {
detectedNS, c, _ := getOpenShiftClient(f)
selector, err := k8api.LabelSelectorAsSelector(
&k8api.LabelSelector{MatchLabels: map[string]string{"kind": "environments"}})
cmdutil.CheckErr(err)
cfgmap, err := c.ConfigMaps(detectedNS).List(api.ListOptions{LabelSelector: selector})
cmdutil.CheckErr(err)
fmt.Printf("%-10s DATA\n", "ENV")
for _, item := range cfgmap.Items {
for key, data := range item.Data {
var ed EnvironmentData
err := yaml.Unmarshal([]byte(data), &ed)
cmdutil.CheckErr(err)
fmt.Printf("%-10s name=%s namespace=%s order=%d\n",
key, ed.Name, ed.Namespace, ed.Order)
}
}
},
}
// NB(chmou): we may try to do the whole shenanigans like kubectl/oc does for
// outputting stuff but currently this is like swatting flies with a
// sledgehammer.
// cmdutil.AddPrinterFlags(cmd)
return cmd
}
func NewCmdCreateEnviron(f *cmdutil.Factory) (cmd *cobra.Command) {
cmd = &cobra.Command{
Use: "environ",
Short: "Create environment from fabric8-environments configmap",
Long: "gofabric8 create environ environKey namespace=string order=int ...",
Run: func(cmd *cobra.Command, args []string) {
var ev EnvironmentData
var yamlData []byte
ev.Order = -1
for _, kv := range args {
split := strings.Split(kv, "=")
k := split[0]
v := split[1]
if strings.ToLower(k) == "name" {
ev.Name = strings.ToLower(v)
} else if strings.ToLower(k) == "namespace" {
ev.Namespace = v
} else if strings.ToLower(k) == "order" {
conv, err := strconv.Atoi(v)
if err != nil {
util.Errorf("Cannot use %s from %s as number\n", v, k)
return
}
ev.Order = conv
} else {
util.Errorf("Unkown key: %s\n", k)
return
}
}
if ev.Name == "" || ev.Namespace == "" || ev.Order == -1 {
util.Error("missing some key=value\n")
cmd.Help()
return
}
detectedNS, c, _ := getOpenShiftClient(f)
yamlData, err := yaml.Marshal(&ev)
if err != nil {
util.Fatalf("Failed to marshal configmap fabric8-environments error: %v\ntemplate: %s", err, string(yamlData))
}
selector, err := k8api.LabelSelectorAsSelector(
&k8api.LabelSelector{MatchLabels: map[string]string{"kind": "environments"}})
cmdutil.CheckErr(err)
cfgmaps, err := c.ConfigMaps(detectedNS).List(api.ListOptions{LabelSelector: selector})
cmdutil.CheckErr(err)
cfgmap := &cfgmaps.Items[0] // TODO(chmou): can we have more than one cfgmap with kind=environments label?
cfgmap.Data[ev.Name] = string(yamlData)
_, err = c.ConfigMaps(detectedNS).Update(cfgmap)
cmdutil.CheckErr(err)
//cfgmap, err := c.ConfigMaps(detectedNS).Create()
},
}
return
}
// NewCmdDeleteEnviron is a command to delete an environ using: gofabric8 delete environ abcd
func NewCmdDeleteEnviron(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "environ",
Short: "Delete environment from fabric8-environments configmap",
Run: func(cmd *cobra.Command, args []string) {
detectedNS, c, _ := getOpenShiftClient(f)
selector, err := k8api.LabelSelectorAsSelector(
&k8api.LabelSelector{MatchLabels: map[string]string{"kind": "environments"}})
cmdutil.CheckErr(err)
if len(args) == 0 {
util.Errorf("Delete command requires the name of the environment as a parameter\n")
return
}
if len(args) != 1 {
util.Errorf("Delete command can have only one environment name parameter\n")
return
}
toDeleteEnv := args[0]
cfgmap, err := c.ConfigMaps(detectedNS).List(api.ListOptions{LabelSelector: selector})
cmdutil.CheckErr(err)
// remove the entry from the config map
var updatedCfgMap *api.ConfigMap
for _, item := range cfgmap.Items {
for k, data := range item.Data {
var ed EnvironmentData
err := yaml.Unmarshal([]byte(data), &ed)
cmdutil.CheckErr(err)
if strings.ToLower(ed.Name) == strings.ToLower(toDeleteEnv) {
delete(item.Data, k)
updatedCfgMap = &item
goto DeletedConfig
}
}
}
DeletedConfig:
if updatedCfgMap == nil {
util.Warnf("Could not find environment named %s\n", toDeleteEnv)
return
}
_, err = c.ConfigMaps(detectedNS).Update(updatedCfgMap)
if err != nil {
util.Errorf("Failed to update config map after deleting: %v\n", err)
return
}
util.Infof("environment %s has been deleted\n", toDeleteEnv)
},
}
return cmd
}
// getOpenShiftClient Get an openshift client and detect the project we want to
// be in
func getOpenShiftClient(f *cmdutil.Factory) (detectedNS string, c *k8client.Client, cfg *restclient.Config) {
c, cfg = client.NewClient(f)
initSchema()
typeOfMaster := util.TypeOfMaster(c)
isOpenshift := typeOfMaster == util.OpenShift
if isOpenshift {
oc, _ := client.NewOpenShiftClient(cfg)
projects, err := oc.Projects().List(api.ListOptions{})
if err != nil {
util.Warnf("Could not list projects: %v", err)
} else {
currentNS, _, _ := f.DefaultNamespace()
detectedNS = detectCurrentUserProject(currentNS, projects.Items)
}
}
if detectedNS == "" {
detectedNS, _, _ = f.DefaultNamespace()
}
return
}