-
Notifications
You must be signed in to change notification settings - Fork 20
/
coi.go
249 lines (209 loc) · 6.15 KB
/
coi.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
package cmd
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
const coiTemplateName = "Container-Optimized Instance"
var coiCmd = &cobra.Command{
Use: "coi <name>",
Short: "Deploy a Container-Optimized Instance",
Long: fmt.Sprintf(`This command creates a Compute instance running one or several Docker
containers based on the Docker image specified or a Docker Compose
configuration provided. It can be invoked in 2 ways:
* Specifying a Docker image and optionally ports to publish:
$ exo lab coi nginx \
--zone ch-gva-2 \
--image nginxdemos/hello \
--port 80:80 \
...
* Specifying a Docker Compose file:
$ exo lab coi my-app \
--zone ch-gva-2 \
--docker-compose /path/to/docker-compose.yml \
# or --docker-compose https://my.app/docker-compose.yml
...
Once created, the Compute instance can be managed like any other standard
instance using the "exo vm" commands.
The Docker Compose configuration reference can be found at this address:
https://docs.docker.com/compose/compose-file/
Supported output template annotations: %s`,
strings.Join(outputterTemplateAnnotations(&vmShowOutput{}), ", ")),
PreRunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
cmdExitOnUsageError(cmd, "invalid arguments")
}
cmdSetZoneFlagFromDefault(cmd)
return cmdCheckRequiredFlags(cmd, []string{"zone"})
},
RunE: func(cmd *cobra.Command, args []string) error {
var cloudInitUserdata string
z, err := cmd.Flags().GetString("zone")
if err != nil {
return err
}
zone, err := getZoneByNameOrID(z)
if err != nil {
return err
}
diskSize, err := cmd.Flags().GetInt64("disk-size")
if err != nil {
return err
}
sshKey, err := cmd.Flags().GetString("ssh-key")
if err != nil {
return err
}
if sshKey == "" {
sshKey = gCurrentAccount.DefaultSSHKey
}
sg, err := cmd.Flags().GetStringSlice("security-group")
if err != nil {
return err
}
securityGroups, err := getSecurityGroupIDs(sg)
if err != nil {
return err
}
privnet, err := cmd.Flags().GetStringSlice("private-network")
if err != nil {
return err
}
privnets, err := getPrivnetIDs(privnet, zone.ID)
if err != nil {
return err
}
so, err := cmd.Flags().GetString("service-offering")
if err != nil {
return err
}
serviceOffering, err := getServiceOfferingByNameOrID(so)
if err != nil {
return err
}
template, err := getTemplateByNameOrID(zone.ID, coiTemplateName, "community")
if err != nil {
return err
}
dockerImage, err := cmd.Flags().GetString("image")
if err != nil {
return err
}
dockerPorts, err := cmd.Flags().GetStringSlice("port")
if err != nil {
return err
}
dockerComposeSource, err := cmd.Flags().GetString("docker-compose")
if err != nil {
return err
}
if (dockerImage == "" && dockerComposeSource == "") ||
(dockerImage != "" && dockerComposeSource != "") {
return errors.New("either --image or --docker-compose must be specified")
}
if dockerImage != "" {
cloudInitUserdata, err = coiGenerateUserdataWithImage(dockerImage, dockerPorts)
} else {
cloudInitUserdata, err = coiGenerateUserdataWithDockerCompose(dockerComposeSource)
}
if err != nil {
return fmt.Errorf("unable to generate cloud-init userdata: %v", err)
}
cloudInitUserdataEncoded := base64.StdEncoding.EncodeToString([]byte(cloudInitUserdata))
if len(cloudInitUserdataEncoded) >= maxUserDataLength {
return fmt.Errorf("maximum allowed length for Docker Compose configuration is %d bytes",
maxUserDataLength)
}
resp := asyncTasks([]task{{
egoscale.DeployVirtualMachine{
Name: args[0],
ZoneID: zone.ID,
ServiceOfferingID: serviceOffering.ID,
TemplateID: template.ID,
KeyPair: sshKey,
RootDiskSize: diskSize,
SecurityGroupIDs: securityGroups,
NetworkIDs: privnets,
UserData: cloudInitUserdataEncoded,
},
fmt.Sprintf("Creating Compute instance %q", args[0]),
}})
errors := filterErrors(resp)
if len(errors) > 0 {
return errors[0]
}
vm := resp[0].resp.(*egoscale.VirtualMachine)
if !gQuiet {
return output(showVM(vm.Name))
}
return nil
},
}
func coiGenerateUserdataWithImage(image string, ports []string) (string, error) {
dockerCompose, err := yaml.Marshal(map[string]interface{}{
"version": "3",
"services": map[string]interface{}{
"coi": map[string]interface{}{
"image": image,
"ports": ports,
},
},
})
if err != nil {
return "", err
}
return fmt.Sprintf(`#cloud-config
write_files:
- path: /etc/docker-compose.yml
content: %s
encoding: b64
owner: root:root
permissions: '0600'
`, base64.StdEncoding.EncodeToString(dockerCompose)), nil
}
func coiGenerateUserdataWithDockerCompose(source string) (string, error) {
if strings.HasPrefix(source, "http") {
return fmt.Sprintf(`#cloud-config
bootcmd:
- curl -sL "%s" > /etc/docker-compose.yml
- chmod 600 /etc/docker-compose.yml
`, source), nil
}
file, err := os.Open(source)
if err != nil {
return "", err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return "", err
}
return fmt.Sprintf(`#cloud-config
write_files:
- path: /etc/docker-compose.yml
content: %s
encoding: b64
owner: root:root
permissions: '0600'
`, base64.StdEncoding.EncodeToString(data)), nil
}
func init() {
coiCmd.Flags().Int64P("disk-size", "d", 20, "disk size")
coiCmd.Flags().StringP("image", "i", "", "Docker image to run")
coiCmd.Flags().StringP("docker-compose", "c", "",
"Docker Compose configuration file (local path/URL)")
coiCmd.Flags().StringSliceP("port", "p", nil,
"publish container port(s) (format \"[<host port>:]<container port>\")")
coiCmd.Flags().StringP("ssh-key", "k", "", "SSH key name")
coiCmd.Flags().StringSlice("private-network", nil, "Private Network name/ID")
coiCmd.Flags().StringSlice("security-group", nil, "Security Group name/ID")
coiCmd.Flags().StringP("service-offering", "o", "medium", serviceOfferingHelp)
coiCmd.Flags().StringP("zone", "z", "", zoneHelp)
labCmd.AddCommand(coiCmd)
}