Repository navigation
Expand file tree
/
Copy pathtags.go
More file actions
278 lines (242 loc) · 8.46 KB
/
Copy pathtags.go
File metadata and controls
278 lines (242 loc) · 8.46 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
package main
import (
"encoding/json"
"os"
"strings"
"github.com/jmespath/go-jmespath"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
trie "github.com/v-pap/trie"
"gitlab.ops.mist.io/mistio/openapi-cli-generator/cli"
"gopkg.in/h2non/gentleman.v2"
)
var taggableResources []string = []string{
"cloud",
"cluster",
"key",
"machine",
"network",
"rule",
"schedule",
"script",
"secret",
"volume",
"zone",
}
var resourceListControllersMap map[string]func(params *viper.Viper) (*gentleman.Response, map[string]interface{}, cli.CLIOutputOptions, error) = map[string]func(params *viper.Viper) (*gentleman.Response, map[string]interface{}, cli.CLIOutputOptions, error){
"cloud": MistApiV2ListClouds,
"cluster": MistApiV2ListClusters,
"key": MistApiV2ListKeys,
"machine": MistApiV2ListMachines,
"network": MistApiV2ListNetworks,
"rule": MistApiV2ListRules,
"schedule": MistApiV2ListSchedules,
"script": MistApiV2ListScripts,
"secret": MistApiV2ListSecrets,
"volume": MistApiV2ListVolumes,
"zone": MistApiV2ListZones,
}
var resourceGetControllersMap map[string]func(param string, params *viper.Viper) (*gentleman.Response, map[string]interface{}, cli.CLIOutputOptions, error) = map[string]func(param string, params *viper.Viper) (*gentleman.Response, map[string]interface{}, cli.CLIOutputOptions, error){
"cloud": MistApiV2GetCloud,
"cluster": MistApiV2GetCluster,
"key": MistApiV2GetKey,
"machine": MistApiV2GetMachine,
"network": MistApiV2GetNetwork,
"rule": MistApiV2GetRule,
"schedule": MistApiV2GetSchedule,
"script": MistApiV2GetScript,
"secret": MistApiV2GetSecret,
"volume": MistApiV2GetVolume,
"zone": MistApiV2GetZone,
}
var tagSubCommandTpl = `Usage:{{if .Runnable}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}
RESOURCE... are resource names seperated by white space.
TAGS are key-value comma seperated values. (e.g. key1=value1,key2){{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
type KeyValuePair struct {
Key string `json:"key"`
Value string `json:"value"`
}
type Resource struct {
ResourceType string `json:"resource_type"`
ResourceID string `json:"resource_id"`
}
type Operation struct {
Operation string `json:"operation"`
Tags []KeyValuePair `json:"tags"`
Resources []Resource `json:"resources"`
}
type tagResourceBody struct {
Operations []Operation `json:"operations"`
}
func tagValidArgsFunction(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
resourceType := strings.Fields(cmd.Use)[0]
params := viper.New()
params.Set("only", "name")
var decoded interface{}
_, decoded, _, err := resourceListControllersMap[resourceType](params)
if err != nil {
logger.Fatalf("Error calling operation: %s", err.Error())
}
data, _ := jmespath.Search("data[].name", decoded)
j, _ := json.Marshal(data)
str := strings.Replace(strings.Replace(strings.Replace(string(j[:]), "[", "", -1), "]", "", -1), " ", "\\ ", -1)
return strings.Split(str, ","), cobra.ShellCompDirectiveNoFileComp
}
func tagRun(cmd *cobra.Command, args []string, params *viper.Viper, tagOperation string) {
resourceType := strings.Fields(cmd.Use)[0]
resourceNames := args[:len(args)-1]
stringTags := args[len(args)-1]
resources := []Resource{}
for _, resourceName := range resourceNames {
_, decodedResource, _, err := resourceGetControllersMap[resourceType](resourceName, params)
rawResourceID, _ := jmespath.Search("data.id", decodedResource)
resourceID, ok := rawResourceID.(string)
if !ok {
logger.Fatalf("Error parsing resource: %s", err.Error())
}
resources = append(resources, Resource{ResourceType: resourceType + "s", ResourceID: resourceID})
}
tags := []KeyValuePair{}
for _, stringTag := range strings.Split(stringTags, ",") {
splittedTag := strings.Split(stringTag, "=")
kv := KeyValuePair{}
kv.Key = splittedTag[0]
if len(splittedTag) > 1 {
kv.Value = splittedTag[1]
}
tags = append(tags, kv)
}
operations := []Operation{{Operation: tagOperation, Tags: tags, Resources: resources}}
body := tagResourceBody{Operations: operations}
rawBody, err := json.Marshal(body)
if err != nil {
logger.Fatalf("Error marshalling tags: %s", err.Error())
}
_, decodedTag, outputOptions, err := MistApiV2TagResources(params, string(rawBody))
if err != nil {
logger.Fatalf("Error calling operation: %s", err.Error())
}
if err := cli.Formatter.Format(decodedTag, params, outputOptions); err != nil {
logger.Fatalf("Formatting failed: %s", err.Error())
}
}
func calculateAliasesMap(terms []string) map[string][]string {
termsTrie := trie.New()
aliasesMap := make(map[string][]string)
for _, term := range terms {
termsTrie.Insert(term)
}
for _, term := range terms {
suffix, ok := termsTrie.FindLongestUniqueSuffix(term)
if !ok {
continue
}
aliasesMap[term] = calculateAliases(term, suffix)
}
return aliasesMap
}
func tagCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "tag",
Short: "Tag resource",
}
cmd.SetErr(os.Stderr)
aliasesMap := calculateAliasesMap(taggableResources)
for _, resource := range taggableResources {
params := viper.New()
cmdResource := &cobra.Command{
Use: resource + " RESOURCE... TAGS",
Short: "Tag " + resource,
Aliases: aliasesMap[resource],
Args: cobra.MinimumNArgs(2),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return tagValidArgsFunction(cmd, args, toComplete)
},
Run: func(cmd *cobra.Command, args []string) {
tagRun(cmd, args, params, "add")
},
}
cmdResource.SetUsageTemplate(tagSubCommandTpl)
cmd.AddCommand(cmdResource)
}
return cmd
}
func untagCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "untag",
Short: "Untag resource",
}
cmd.SetErr(os.Stderr)
aliasesMap := calculateAliasesMap(taggableResources)
for _, resource := range taggableResources {
params := viper.New()
cmdResource := &cobra.Command{
Use: resource + " RESOURCE... TAGS",
Short: "Untag " + resource,
Aliases: aliasesMap[resource],
Args: cobra.MinimumNArgs(2),
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return tagValidArgsFunction(cmd, args, toComplete)
},
Run: func(cmd *cobra.Command, args []string) {
tagRun(cmd, args, params, "remove")
},
}
cmdResource.SetUsageTemplate(tagSubCommandTpl)
cmd.AddCommand(cmdResource)
}
return cmd
}
// MistApiV2TagResources Tag Resources
func MistApiV2TagResources(params *viper.Viper, body string) (*gentleman.Response, interface{}, cli.CLIOutputOptions, error) {
handlerPath := "tag-resources"
if mistApiV2Subcommand {
handlerPath = "Mist CLI " + handlerPath
}
err := setContext()
if err != nil {
return nil, nil, cli.CLIOutputOptions{}, err
}
server, err := getServer()
if err != nil {
return nil, nil, cli.CLIOutputOptions{}, err
}
url := server + "/api/v2/tags"
req := cli.Client.Post().URL(url)
if body != "" {
req = req.AddHeader("Content-Type", "application/json").BodyString(body)
}
cli.HandleBefore(handlerPath, params, req)
resp, err := req.Do()
if err != nil {
return resp, nil, cli.CLIOutputOptions{}, errors.Wrap(err, "Request failed")
}
var decoded interface{}
if resp.StatusCode < 400 {
if err := cli.UnmarshalResponse(resp, &decoded); err != nil {
return resp, nil, cli.CLIOutputOptions{}, errors.Wrap(err, "Unmarshalling response failed")
}
} else {
return resp, nil, cli.CLIOutputOptions{}, errors.Errorf("HTTP %d: %s", resp.StatusCode, resp.String())
}
after := cli.HandleAfter(handlerPath, params, resp, decoded)
if after != nil {
decoded = after
}
return resp, decoded, cli.CLIOutputOptions{[]string{}, []string{}, []string{}, []string{}, map[string]string{}}, nil
}