-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
319 lines (262 loc) · 7.45 KB
/
helpers.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/*
* Copyright (C) 2016 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Benjamin Zeller <[email protected]>
*
* Based on the LXD lxc client. Copyright Holders:
* Author: Gustavo Niemeyer
* Author: Stéphane Graber
* Author: Tycho Andersen
* Author: Joshua Griffiths
*/
package ubuntu_sdk_tools
import (
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared"
"path"
"os"
"fmt"
"log"
"os/exec"
"strings"
)
const LxdBridgeFile = "/etc/default/lxd-bridge"
const LxdContainerPerm = 0755
var globConfig *lxd.Config = nil
type ClickContainer struct {
Name string `json:"name"`
Architecture string `json:"architecture"`
Framework string `json:"framework"`
UpdatesEnabled bool `json:"updatesEnabled"`
Container shared.ContainerInfo `json:"-"`
}
func EnsureLXDInitializedOrDie() {
config := GetConfigOrDie()
//let's register a new remote
defaultImageRemote := "https://sdk-images.canonical.com"
if (len(os.Getenv("USDK_TEST_REMOTE")) != 0) {
defaultImageRemote = os.Getenv("USDK_TEST_REMOTE")
}
defaultRemoteName := "ubuntu-sdk-images"
remotes := config.Remotes
sdkRem, ok := remotes[defaultRemoteName]
if ok {
if sdkRem.Addr == defaultImageRemote {
return
} else {
cmd := exec.Command("lxc", "remote", "remove", defaultRemoteName)
err := cmd.Run()
if (err != nil) {
fmt.Fprintf(os.Stderr, "Could not remove the remote "+defaultRemoteName+". error: %v\n", err)
fmt.Fprintf(os.Stderr, "Please remove it manually.\n", err)
os.Exit(1)
}
}
}
cmd := exec.Command("lxc", "remote", "add", "ubuntu-sdk-images", defaultImageRemote, "--accept-certificate", "--protocol=simplestreams")
err := cmd.Run()
if (err != nil) {
fmt.Fprintf(os.Stderr, "Could not register remote. error: %v\n", err)
os.Exit(1)
}
//make sure config is loaded again
globConfig = nil
}
func GetConfigOrDie () (*lxd.Config) {
if globConfig != nil {
return globConfig
}
configDir := "$HOME/.config/lxc"
if os.Getenv("LXD_CONF") != "" {
configDir = os.Getenv("LXD_CONF")
}
configPath := os.ExpandEnv(path.Join(configDir, "config.yml"))
globConfig, err := lxd.LoadConfig(configPath)
if err != nil {
log.Fatal("Could not load LXC config")
}
certf := globConfig.ConfigPath("client.crt")
keyf := globConfig.ConfigPath("client.key")
if !shared.PathExists(certf) || !shared.PathExists(keyf) {
fmt.Fprintf(os.Stderr, "Generating a client certificate. This may take a minute...\n")
err = shared.FindOrGenCert(certf, keyf)
if err != nil {
log.Fatal("Could not generate client certificates.\n")
os.Exit(1)
}
if shared.PathExists("/var/lib/lxd/") {
fmt.Fprintf(os.Stderr, "If this is your first time using LXD, you should also run: sudo lxd init\n\n")
}
}
return globConfig
}
func BootContainerSync (client *lxd.Client, name string) error {
current, err := client.ContainerInfo(name)
if err != nil {
return err
}
action := shared.Start
if current.StatusCode == shared.Running {
return nil
}
// "start" for a frozen container means "unfreeze"
if current.StatusCode == shared.Frozen {
action = shared.Unfreeze
}
resp, err := client.Action(name, action, 10, false, false)
if err != nil {
return err
}
if resp.Type != lxd.Async {
return fmt.Errorf("bad result type from action")
}
if err := client.WaitForSuccess(resp.Operation); err != nil {
return fmt.Errorf("%s\nTry `lxc info --show-log %s` for more info", err, name)
}
return nil
}
func StopContainerSync (client *lxd.Client, container string) error {
ct, err := client.ContainerInfo(container)
if err != nil {
return err
}
if ct.StatusCode != 0 && ct.StatusCode != shared.Stopped {
resp, err := client.Action(container, shared.Stop, -1, true, false)
if err != nil {
return err
}
if resp.Type != lxd.Async {
return fmt.Errorf("bad result type from action")
}
if err := client.WaitForSuccess(resp.Operation); err != nil {
return fmt.Errorf("%s\nTry `lxc info --show-log %s` for more info", err, container)
}
if ct.Ephemeral == true {
return nil
}
}
return nil
}
func UpdateConfigSync (client *lxd.Client, container string) error {
fmt.Printf("Applying changes to container: %s\n", container)
err := StopContainerSync(client, container)
if err != nil {
return err
}
err = BootContainerSync(client, container)
if ( err != nil ) {
return err
}
command := []string {
"exec", container, "--",
"bash", "-c", "rm /etc/ld.so.cache; ldconfig",
}
cmd := exec.Command("lxc", command...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func AddDeviceSync (client *lxd.Client, container, devname, devtype string, props []string) error{
fmt.Printf("Adding device %s to %s: %s %v\n",devname, container, devtype, props)
resp, err := client.ContainerDeviceAdd(container, devname, devtype, props)
if err != nil {
return err
}
err = client.WaitForSuccess(resp.Operation)
if err == nil {
fmt.Printf("Device %s added to %s\n", devname, container)
}
return err
}
func RemoveDeviceSync (client *lxd.Client, container, devname string) error{
fmt.Printf("Removing device %s\n",devname)
resp, err := client.ContainerDeviceDelete(container, devname)
if err != nil {
return err
}
err = client.WaitForSuccess(resp.Operation)
if err == nil {
fmt.Printf("Device %s removed from %s\n", devname, container)
}
return err
}
func RemoveContainerSync(client *lxd.Client, container string) (error){
err := StopContainerSync(client, container)
if err != nil {
return err
}
resp, err := client.Delete(container)
if err != nil {
return err
}
return client.WaitForSuccess(resp.Operation)
}
func GetUserConfirmation(question string) (bool) {
var response string
responses := map[string]bool{
"y": true, "yes": true,
"n": false, "no": false,
}
ok := false
answer := false
for !ok {
fmt.Print(question+" (yes/no): ")
_, err := fmt.Scanln(&response)
if err != nil {
log.Fatal(err)
}
response = strings.ToLower(response)
answer, ok = responses[response]
}
return answer
}
func ContainerRootfs (container string) (string) {
return shared.VarPath("containers", container, "rootfs")
}
var ClickArchConfig string = "user.click-architecture"
var ClickFrameworkConfig string = "user.click-framework"
var TargetUpgradesConfig string = "user.click-updates-enabled"
func FindClickTargets (client *lxd.Client) ([]ClickContainer, error) {
ctslist, err := client.ListContainers()
if err != nil {
return nil, err
}
clickTargets := []ClickContainer{}
for _, cInfo := range ctslist {
cConf := cInfo.Config
clickArch, ok := cConf[ClickArchConfig]
if !ok {
continue
}
clickFW, ok := cConf[ClickFrameworkConfig]
if !ok {
continue
}
updatesEnabled, ok := cConf[TargetUpgradesConfig]
if !ok {
updatesEnabled = "false"
}
clickTargets = append(clickTargets,
ClickContainer{
Name:cInfo.Name,
Architecture: clickArch,
Framework: clickFW,
Container: cInfo,
UpdatesEnabled: updatesEnabled == "true",
},
)
}
return clickTargets, nil
}