forked from kubernetes/kompose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompose.go
403 lines (352 loc) · 12.6 KB
/
compose.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
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 compose
import (
"fmt"
"net"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"k8s.io/kubernetes/pkg/api"
log "github.com/Sirupsen/logrus"
"github.com/docker/libcompose/config"
"github.com/docker/libcompose/lookup"
"github.com/docker/libcompose/project"
"github.com/fatih/structs"
"github.com/kubernetes-incubator/kompose/pkg/kobject"
"github.com/pkg/errors"
)
// Compose is docker compose file loader, implements Loader interface
type Compose struct {
}
// checkUnsupportedKey checks if libcompose project contains
// keys that are not supported by this loader.
// list of all unsupported keys are stored in unsupportedKey variable
// returns list of unsupported YAML keys from docker-compose
func checkUnsupportedKey(composeProject *project.Project) []string {
// list of all unsupported keys for this loader
// this is map to make searching for keys easier
// to make sure that unsupported key is not going to be reported twice
// by keeping record if already saw this key in another service
var unsupportedKey = map[string]bool{
"CgroupParent": false,
"CPUSet": false,
"CPUShares": false,
"Devices": false,
"DependsOn": false,
"DNS": false,
"DNSSearch": false,
"DomainName": false,
"EnvFile": false,
"ExternalLinks": false,
"ExtraHosts": false,
"Hostname": false,
"Ipc": false,
"Logging": false,
"MacAddress": false,
"MemSwapLimit": false,
"NetworkMode": false,
"Pid": false,
"SecurityOpt": false,
"ShmSize": false,
"StopSignal": false,
"VolumeDriver": false,
"Uts": false,
"ReadOnly": false,
"Ulimits": false,
"Net": false,
"Sysctls": false,
"Networks": false, // there are special checks for Network in checkUnsupportedKey function
}
// collect all keys found in project
var keysFound []string
// Root level keys are not yet supported
// Check to see if the default network is available and length is only equal to one.
// Else, warn the user that root level networks are not supported (yet)
if _, ok := composeProject.NetworkConfigs["default"]; ok && len(composeProject.NetworkConfigs) == 1 {
log.Debug("Default network found")
} else if len(composeProject.NetworkConfigs) > 0 {
keysFound = append(keysFound, "root level networks")
}
// Root level volumes are not yet supported
if len(composeProject.VolumeConfigs) > 0 {
keysFound = append(keysFound, "root level volumes")
}
for _, serviceConfig := range composeProject.ServiceConfigs.All() {
// this reflection is used in check for empty arrays
val := reflect.ValueOf(serviceConfig).Elem()
s := structs.New(serviceConfig)
for _, f := range s.Fields() {
// Check if given key is among unsupported keys, and skip it if we already saw this key
if alreadySaw, ok := unsupportedKey[f.Name()]; ok && !alreadySaw {
if f.IsExported() && !f.IsZero() {
// IsZero returns false for empty array/slice ([])
// this check if field is Slice, and then it checks its size
if field := val.FieldByName(f.Name()); field.Kind() == reflect.Slice {
if field.Len() == 0 {
// array is empty it doesn't matter if it is in unsupportedKey or not
continue
}
}
//get yaml tag name instad of variable name
yamlTagName := strings.Split(f.Tag("yaml"), ",")[0]
if f.Name() == "Networks" {
// networks always contains one default element, even it isn't declared in compose v2.
if len(serviceConfig.Networks.Networks) == 1 && serviceConfig.Networks.Networks[0].Name == "default" {
// this is empty Network definition, skip it
continue
} else {
yamlTagName = "networks"
}
}
keysFound = append(keysFound, yamlTagName)
unsupportedKey[f.Name()] = true
}
}
}
}
return keysFound
}
// load environment variables from compose file
func loadEnvVars(envars []string) []kobject.EnvVar {
envs := []kobject.EnvVar{}
for _, e := range envars {
character := ""
equalPos := strings.Index(e, "=")
colonPos := strings.Index(e, ":")
switch {
case equalPos == -1 && colonPos == -1:
character = ""
case equalPos == -1 && colonPos != -1:
character = ":"
case equalPos != -1 && colonPos == -1:
character = "="
case equalPos != -1 && colonPos != -1:
if equalPos > colonPos {
character = ":"
} else {
character = "="
}
}
if character == "" {
envs = append(envs, kobject.EnvVar{
Name: e,
Value: os.Getenv(e),
})
} else {
values := strings.SplitN(e, character, 2)
// try to get value from os env
if values[1] == "" {
values[1] = os.Getenv(values[0])
}
envs = append(envs, kobject.EnvVar{
Name: values[0],
Value: values[1],
})
}
}
return envs
}
// Load ports from compose file
func loadPorts(composePorts []string) ([]kobject.Ports, error) {
ports := []kobject.Ports{}
character := ":"
// For each port listed
for _, port := range composePorts {
// Get the TCP / UDP protocol. Checks to see if it splits in 2 with '/' character.
// ex. 15000:15000/tcp
// else, set a default protocol of using TCP
proto := api.ProtocolTCP
protocolCheck := strings.Split(port, "/")
if len(protocolCheck) == 2 {
if strings.EqualFold("tcp", protocolCheck[1]) {
proto = api.ProtocolTCP
} else if strings.EqualFold("udp", protocolCheck[1]) {
proto = api.ProtocolUDP
} else {
return nil, fmt.Errorf("invalid protocol %q", protocolCheck[1])
}
}
// Split up the ports / IP without the "/tcp" or "/udp" appended to it
justPorts := strings.Split(protocolCheck[0], character)
if len(justPorts) == 3 {
// ex. 127.0.0.1:80:80
// Get the IP address
hostIP := justPorts[0]
ip := net.ParseIP(hostIP)
if ip.To4() == nil && ip.To16() == nil {
return nil, fmt.Errorf("%q contains an invalid IPv4 or IPv6 IP address", port)
}
// Get the host port
hostPortInt, err := strconv.Atoi(justPorts[1])
if err != nil {
return nil, fmt.Errorf("invalid host port %q valid example: 127.0.0.1:80:80", port)
}
// Get the container port
containerPortInt, err := strconv.Atoi(justPorts[2])
if err != nil {
return nil, fmt.Errorf("invalid container port %q valid example: 127.0.0.1:80:80", port)
}
// Convert to a kobject struct with ports as well as IP
ports = append(ports, kobject.Ports{
HostPort: int32(hostPortInt),
ContainerPort: int32(containerPortInt),
HostIP: hostIP,
Protocol: proto,
})
} else if len(justPorts) == 2 {
// ex. 80:80
// Get the host port
hostPortInt, err := strconv.Atoi(justPorts[0])
if err != nil {
return nil, fmt.Errorf("invalid host port %q valid example: 80:80", port)
}
// Get the container port
containerPortInt, err := strconv.Atoi(justPorts[1])
if err != nil {
return nil, fmt.Errorf("invalid container port %q valid example: 80:80", port)
}
// Convert to a kobject struct and add to the list of ports
ports = append(ports, kobject.Ports{
HostPort: int32(hostPortInt),
ContainerPort: int32(containerPortInt),
Protocol: proto,
})
} else {
// ex. 80
containerPortInt, err := strconv.Atoi(justPorts[0])
if err != nil {
return nil, fmt.Errorf("invalid container port %q valid example: 80", port)
}
ports = append(ports, kobject.Ports{
ContainerPort: int32(containerPortInt),
Protocol: proto,
})
}
}
return ports, nil
}
// LoadFile loads compose file into KomposeObject
func (c *Compose) LoadFile(files []string) (kobject.KomposeObject, error) {
komposeObject := kobject.KomposeObject{
ServiceConfigs: make(map[string]kobject.ServiceConfig),
LoadedFrom: "compose",
}
context := &project.Context{}
context.ComposeFiles = files
if context.ResourceLookup == nil {
context.ResourceLookup = &lookup.FileResourceLookup{}
}
if context.EnvironmentLookup == nil {
cwd, err := os.Getwd()
if err != nil {
return kobject.KomposeObject{}, nil
}
context.EnvironmentLookup = &lookup.ComposableEnvLookup{
Lookups: []config.EnvironmentLookup{
&lookup.EnvfileLookup{
Path: filepath.Join(cwd, ".env"),
},
&lookup.OsEnvLookup{},
},
}
}
// load compose file into composeObject
composeObject := project.NewProject(context, nil, nil)
err := composeObject.Parse()
if err != nil {
return kobject.KomposeObject{}, errors.Wrap(err, "composeObject.Parse() failed, Failed to load compose file")
}
noSupKeys := checkUnsupportedKey(composeObject)
for _, keyName := range noSupKeys {
log.Warningf("Unsupported %s key - ignoring", keyName)
}
for name, composeServiceConfig := range composeObject.ServiceConfigs.All() {
serviceConfig := kobject.ServiceConfig{}
serviceConfig.Image = composeServiceConfig.Image
serviceConfig.Build = composeServiceConfig.Build.Context
serviceConfig.ContainerName = composeServiceConfig.ContainerName
serviceConfig.Command = composeServiceConfig.Entrypoint
serviceConfig.Args = composeServiceConfig.Command
serviceConfig.Dockerfile = composeServiceConfig.Build.Dockerfile
envs := loadEnvVars(composeServiceConfig.Environment)
serviceConfig.Environment = envs
// load ports
ports, err := loadPorts(composeServiceConfig.Ports)
if err != nil {
return kobject.KomposeObject{}, errors.Wrap(err, "loadPorts failed. "+name+" failed to load ports from compose file")
}
serviceConfig.Port = ports
serviceConfig.WorkingDir = composeServiceConfig.WorkingDir
if composeServiceConfig.Volumes != nil {
for _, volume := range composeServiceConfig.Volumes.Volumes {
v := normalizeServiceNames(volume.String())
serviceConfig.Volumes = append(serviceConfig.Volumes, v)
}
}
// canonical "Custom Labels" handler
// Labels used to influence conversion of kompose will be handled
// from here for docker-compose. Each loader will have such handler.
for key, value := range composeServiceConfig.Labels {
switch key {
case "kompose.service.type":
serviceType, err := handleServiceType(value)
if err != nil {
return kobject.KomposeObject{}, errors.Wrap(err, "handleServiceType failed")
}
serviceConfig.ServiceType = serviceType
case "kompose.service.expose":
serviceConfig.ExposeService = strings.ToLower(value)
}
}
if len(serviceConfig.Port) == 0 && composeServiceConfig.Labels["kompose.service.type"] == "NodePort" || composeServiceConfig.Labels["kompose.service.type"] == "LoadBalancer" {
log.Fatalf("%s defined in service %s with no ports present. Issues may occur when bringing up artifacts.", composeServiceConfig.Labels["kompose.service.type"], name)
}
// convert compose labels to annotations
serviceConfig.Annotations = map[string]string(composeServiceConfig.Labels)
serviceConfig.CPUQuota = int64(composeServiceConfig.CPUQuota)
serviceConfig.CapAdd = composeServiceConfig.CapAdd
serviceConfig.CapDrop = composeServiceConfig.CapDrop
serviceConfig.Expose = composeServiceConfig.Expose
serviceConfig.Privileged = composeServiceConfig.Privileged
serviceConfig.Restart = composeServiceConfig.Restart
serviceConfig.User = composeServiceConfig.User
serviceConfig.VolumesFrom = composeServiceConfig.VolumesFrom
serviceConfig.Stdin = composeServiceConfig.StdinOpen
serviceConfig.Tty = composeServiceConfig.Tty
serviceConfig.MemLimit = composeServiceConfig.MemLimit
serviceConfig.TmpFs = composeServiceConfig.Tmpfs
komposeObject.ServiceConfigs[normalizeServiceNames(name)] = serviceConfig
if normalizeServiceNames(name) != name {
log.Infof("Service name in docker-compose has been changed from %q to %q", name, normalizeServiceNames(name))
}
}
return komposeObject, nil
}
func handleServiceType(ServiceType string) (string, error) {
switch strings.ToLower(ServiceType) {
case "", "clusterip":
return string(api.ServiceTypeClusterIP), nil
case "nodeport":
return string(api.ServiceTypeNodePort), nil
case "loadbalancer":
return string(api.ServiceTypeLoadBalancer), nil
default:
return "", errors.New("Unknown value " + ServiceType + " , supported values are 'NodePort, ClusterIP or LoadBalancer'")
}
}
func normalizeServiceNames(svcName string) string {
return strings.Replace(svcName, "_", "-", -1)
}