forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
256 lines (205 loc) · 6.27 KB
/
utils.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
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
package main
import (
"fmt"
"io/ioutil"
"os"
"reflect"
"sort"
"strings"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/termios"
)
// Batch operations.
type batchResult struct {
err error
name string
}
func runBatch(names []string, action func(name string) error) []batchResult {
chResult := make(chan batchResult, len(names))
for _, name := range names {
go func(name string) {
chResult <- batchResult{action(name), name}
}(name)
}
results := []batchResult{}
for range names {
results = append(results, <-chResult)
}
return results
}
// Add a device to an instance.
func instanceDeviceAdd(client lxd.InstanceServer, name string, devName string, dev map[string]string) error {
// Get the instance entry
inst, etag, err := client.GetInstance(name)
if err != nil {
return err
}
// Check if the device already exists
_, ok := inst.Devices[devName]
if ok {
return fmt.Errorf(i18n.G("Device already exists: %s"), devName)
}
inst.Devices[devName] = dev
op, err := client.UpdateInstance(name, inst.Writable(), etag)
if err != nil {
return err
}
return op.Wait()
}
// Add a device to a profile.
func profileDeviceAdd(client lxd.InstanceServer, name string, devName string, dev map[string]string) error {
// Get the profile entry
profile, profileEtag, err := client.GetProfile(name)
if err != nil {
return err
}
// Check if the device already exists
_, ok := profile.Devices[devName]
if ok {
return fmt.Errorf(i18n.G("Device already exists: %s"), devName)
}
// Add the device to the instance
profile.Devices[devName] = dev
err = client.UpdateProfile(name, profile.Writable(), profileEtag)
if err != nil {
return err
}
return nil
}
// Create the specified image aliases, updating those that already exist.
func ensureImageAliases(client lxd.InstanceServer, aliases []api.ImageAlias, fingerprint string) error {
if len(aliases) == 0 {
return nil
}
names := make([]string, len(aliases))
for i, alias := range aliases {
names[i] = alias.Name
}
sort.Strings(names)
resp, err := client.GetImageAliases()
if err != nil {
return err
}
// Delete existing aliases that match provided ones
for _, alias := range GetExistingAliases(names, resp) {
err := client.DeleteImageAlias(alias.Name)
if err != nil {
return fmt.Errorf(i18n.G("Failed to remove alias %s: %w"), alias.Name, err)
}
}
// Create new aliases.
for _, alias := range aliases {
aliasPost := api.ImageAliasesPost{}
aliasPost.Name = alias.Name
aliasPost.Target = fingerprint
err := client.CreateImageAlias(aliasPost)
if err != nil {
return fmt.Errorf(i18n.G("Failed to create alias %s: %w"), alias.Name, err)
}
}
return nil
}
// GetExistingAliases returns the intersection between a list of aliases and all the existing ones.
func GetExistingAliases(aliases []string, allAliases []api.ImageAliasesEntry) []api.ImageAliasesEntry {
existing := []api.ImageAliasesEntry{}
for _, alias := range allAliases {
name := alias.Name
pos := sort.SearchStrings(aliases, name)
if pos < len(aliases) && aliases[pos] == name {
existing = append(existing, alias)
}
}
return existing
}
func getConfig(args ...string) (map[string]string, error) {
if len(args) == 2 && !strings.Contains(args[0], "=") {
if args[1] == "-" && !termios.IsTerminal(getStdinFd()) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf(i18n.G("Can't read from stdin: %w"), err)
}
args[1] = string(buf[:])
}
return map[string]string{args[0]: args[1]}, nil
}
values := map[string]string{}
for _, arg := range args {
fields := strings.SplitN(arg, "=", 2)
if len(fields) != 2 {
return nil, fmt.Errorf(i18n.G("Invalid key=value configuration: %s"), arg)
}
if fields[1] == "-" && !termios.IsTerminal(getStdinFd()) {
buf, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, fmt.Errorf(i18n.G("Can't read from stdin: %w"), err)
}
fields[1] = string(buf[:])
}
values[fields[0]] = fields[1]
}
return values, nil
}
func usage(name string, args ...string) string {
if len(args) == 0 {
return name
}
return name + " " + args[0]
}
// instancesExist iterates over a list of instances (or snapshots) and checks that they exist.
func instancesExist(resources []remoteResource) error {
for _, resource := range resources {
// Handle snapshots.
if shared.IsSnapshot(resource.name) {
parent, snap, _ := shared.InstanceGetParentAndSnapshotName(resource.name)
_, _, err := resource.server.GetInstanceSnapshot(parent, snap)
if err != nil {
return fmt.Errorf(i18n.G("Failed checking instance snapshot exists \"%s:%s\": %w"), resource.remote, resource.name, err)
}
continue
}
_, _, err := resource.server.GetInstance(resource.name)
if err != nil {
return fmt.Errorf(i18n.G("Failed checking instance exists \"%s:%s\": %w"), resource.remote, resource.name, err)
}
}
return nil
}
// structHasField checks if specified struct includes field with given name.
func structHasField(typ reflect.Type, field string) bool {
var parent reflect.Type
for i := 0; i < typ.NumField(); i++ {
fieldType := typ.Field(i)
yaml := fieldType.Tag.Get("yaml")
if yaml == ",inline" {
parent = fieldType.Type
}
if yaml == field {
return true
}
}
if parent != nil {
return structHasField(parent, field)
}
return false
}
// getServerSupportedFilters returns two lists: one with filters supported by server and second one with not supported.
func getServerSupportedFilters(filters []string, i interface{}) ([]string, []string) {
supportedFilters := []string{}
unsupportedFilters := []string{}
for _, filter := range filters {
membs := strings.SplitN(filter, "=", 2)
// Only key/value pairs are supported by server side API
// Only keys which are part of struct are supported by server side API
// Multiple values (separated by ',') are not supported by server side API
// Keys with '.' in name are not supported
if len(membs) < 2 || !structHasField(reflect.TypeOf(i), membs[0]) || strings.Contains(membs[1], ",") || strings.Contains(membs[0], ".") {
unsupportedFilters = append(unsupportedFilters, filter)
continue
}
supportedFilters = append(supportedFilters, filter)
}
return supportedFilters, unsupportedFilters
}