chef-provisioning-docker 0.11.0 → 1.0.0.beta.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,95 +0,0 @@
1
- require 'socket'
2
- require 'uri'
3
-
4
- class ChefZeroHttpProxy
5
-
6
- def initialize(local_address, local_port, remote_address, remote_port)
7
- @local_address = local_address
8
- @local_port = local_port
9
- @remote_address = remote_address
10
- @remote_port = remote_port
11
- end
12
-
13
- def run
14
- begin
15
- Chef::Log.debug("Running proxy main loop on #{@local_address}:#{@local_port}!")
16
-
17
- # Start our server to handle connections (will raise things on errors)
18
- @socket = TCPServer.new @local_address, @local_port
19
-
20
- # Handle every request in another thread
21
- loop do
22
- s = @socket.accept
23
- Thread.new s, &method(:handle_request)
24
- end
25
-
26
- ensure
27
- @socket.close if @socket
28
- end
29
- end
30
-
31
- def handle_request(to_client)
32
- begin
33
- request_line = to_client.readline
34
-
35
- verb = request_line[/^\w+/]
36
- url = request_line[/^\w+\s+(\S+)/, 1]
37
- version = request_line[/HTTP\/(1\.\d)\s*$/, 1]
38
- uri = URI::parse url
39
-
40
- # Show what got requested
41
- Chef::Log.debug("[C->S]: #{verb} -> #{url}")
42
-
43
- querystr = if uri.query
44
- "#{uri.path}?#{uri.query}"
45
- else
46
- uri.path
47
- end
48
-
49
- to_server = TCPSocket.new(@remote_address, @remote_port)
50
-
51
- to_server.write("#{verb} #{querystr} HTTP/#{version}\r\n")
52
-
53
- content_len = 0
54
-
55
- loop do
56
- line = to_client.readline
57
-
58
- if line =~ /^Content-Length:\s+(\d+)\s*$/
59
- content_len = $1.to_i
60
- end
61
-
62
- # Strip proxy headers
63
- if line =~ /^proxy/i
64
- next
65
- elsif line.strip.empty?
66
- to_server.write("Connection: close\r\n\r\n")
67
-
68
- if content_len >= 0
69
- to_server.write(to_client.read(content_len))
70
- Chef::Log.debug("[C->S]: Wrote #{content_len} bytes")
71
- end
72
-
73
- break
74
- else
75
- to_server.write(line)
76
- end
77
- end
78
-
79
- buff = ''
80
- while to_server.read(8192, buff)
81
- to_client.write(buff)
82
- end
83
-
84
- rescue
85
- Chef::Log.error $!
86
- raise
87
-
88
- ensure
89
- # Close the sockets
90
- to_client.close
91
- to_server.close
92
- end
93
- end
94
-
95
- end
@@ -1,593 +0,0 @@
1
- class Chef
2
- module Provisioning
3
- module DockerDriver
4
- #
5
- # Allows the user to specify docker options that calculate the desired container config
6
- #
7
- # Command line options follow later in the file (search for `cli_option :command` for the first one).
8
- #
9
- # The API allows these settings:
10
- #
11
- # (https://docs.docker.com/engine/reference/api/docker_remote_api_v1.22/#create-a-container)
12
- #
13
- # ArgsEscaped - bool // True if command is already escaped (Windows specific)
14
- # AttachStderr - Boolean value, attaches to stderr.
15
- # - `docker run --attach STDERR`
16
- # AttachStdin - Boolean value, attaches to stdin.
17
- # - `docker run --attach STDIN`
18
- # - `docker run --interactive`
19
- # AttachStdout - Boolean value, attaches to stdout.
20
- # - `docker run --attach STDOUT`
21
- # Cmd - Command to run specified as a string or an array of strings.
22
- # - `docker run <image> COMMAND`
23
- # Cpuset - Deprecated please don’t use. Use CpusetCpus instead.
24
- # Domainname - A string value containing the domain name to use for the container.
25
- # Entrypoint - Set the entry point for the container as a string or an array of strings.
26
- # - `docker run --entrypoint "COMMAND"`
27
- # Env - A list of environment variables in the form of ["VAR=value"[,"VAR2=value2"]]
28
- # - `docker --env "A=B"`
29
- # ExposedPorts - An object mapping ports to an empty object in the form of: "ExposedPorts": { "<port>/<tcp|udp>: {}" }
30
- # - `docker run --expose PORT`
31
- # - `docker run --publish 8080:8081`
32
- # HostConfig/AutoRemove - bool // Automatically remove container when it exits
33
- # - `docker run --rm`
34
- # HostConfig/Binds – A list of volume bindings for this container. Each volume binding is a string in one of these forms:
35
- # - container_path to create a new volume for the container
36
- # - host_path:container_path to bind-mount a host path into the container
37
- # - host_path:container_path:ro to make the bind-mount read-only inside the container.
38
- # - volume_name:container_path to bind-mount a volume managed by a volume plugin into the container.
39
- # - volume_name:container_path:ro to make the bind mount read-only inside the container.
40
- # - `docker run --volume /host/path:/container/path`
41
- # HostConfig/BlkioBps - uint64 // Maximum Bytes per second for the container system drive
42
- # HostConfig/BlkioDeviceReadBps - Limit read rate (bytes per second) from a device in the form of: "BlkioDeviceReadBps": [{"Path": "device_path", "Rate": rate}], for example: "BlkioDeviceReadBps": [{"Path": "/dev/sda", "Rate": "1024"}]"
43
- # - `docker run --device-read-bps=/dev/sda:1mb`
44
- # HostConfig/BlkioDeviceReadIOps - Limit read rate (IO per second) from a device in the form of: "BlkioDeviceReadIOps": [{"Path": "device_path", "Rate": rate}], for example: "BlkioDeviceReadIOps": [{"Path": "/dev/sda", "Rate": "1000"}]
45
- # - `docker run --device-read-iops=/dev/sda:1000`
46
- # HostConfig/BlkioDeviceWriteBps - Limit write rate (bytes per second) to a device in the form of: "BlkioDeviceWriteBps": [{"Path": "device_path", "Rate": rate}], for example: "BlkioDeviceWriteBps": [{"Path": "/dev/sda", "Rate": "1024"}]"
47
- # - `docker run --device-write-bps=/dev/sda:1mb`
48
- # HostConfig/BlkioDeviceWriteIOps - Limit write rate (IO per second) to a device in the form of: "BlkioDeviceWriteIOps": [{"Path": "device_path", "Rate": rate}], for example: "BlkioDeviceWriteIOps": [{"Path": "/dev/sda", "Rate": "1000"}]
49
- # - `docker run --device-write-iops=/dev/sda:1000`
50
- # HostConfig/BlkioIOps - uint64 // Maximum IOps for the container system drive
51
- # HostConfig/BlkioWeight - Block IO weight (relative weight) accepts a weight value between 10 and 1000.
52
- # - `docker run --blkio-weight 0`
53
- # HostConfig/BlkioWeightDevice - Block IO weight (relative device weight) in the form of: "BlkioWeightDevice": [{"Path": "device_path", "Weight": weight}]
54
- # - `docker run --blkio-weight-device path:weight`
55
- # HostConfig/CapAdd - A list of kernel capabilities to add to the container.
56
- # - `docker run --cap-add capability`
57
- # HostConfig/CapDrop - A list of kernel capabilities to drop from the container.
58
- # - `docker run --cap-drop capability`
59
- # HostConfig/CgroupParent - Path to cgroups under which the container’s cgroup is created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups are created if they do not already exist.
60
- # - `docker run --cgroup-parent parent`
61
- # HostConfig/ConsoleSize - [2]int // Initial console size
62
- # HostConfig/ContainerIDFile - string // File (path) where the containerId is written
63
- # - `docker run --cidfile file`
64
- # HostConfig/CpuPeriod - The length of a CPU period in microseconds.
65
- # - `docker run --cpu-period 0`
66
- # HostConfig/CpuQuota - Microseconds of CPU time that the container can get in a CPU period.
67
- # - `docker run --cpu-quota 0`
68
- # HostConfig/CpuShares - An integer value containing the container’s CPU Shares (ie. the relative weight vs other containers).
69
- # - `docker run --cpu-shares 0`
70
- # HostConfig/CpusetCpus - String value containing the cgroups CpusetCpus to use.
71
- # - `docker run --cpuset-cpus 0-3`
72
- # HostConfig/CpusetMems - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
73
- # - `docker run --cpuset-mems 0-3`
74
- # HostConfig/Devices - A list of devices to add to the container specified as a JSON object in the form { "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}
75
- # - `docker run --device path_on_host:path_in_container:cgroup_permissions`
76
- # HostConfig/DiskQuota - int64 // Disk limit (in bytes)
77
- # HostConfig/Dns - A list of DNS servers for the container to use.
78
- # - `docker run --dns ip`
79
- # HostConfig/DnsOptions - A list of DNS options
80
- # - `docker run --dns-opt a=b`
81
- # HostConfig/DnsSearch - A list of DNS search domains
82
- # - `docker run --dns-opt domain`
83
- # HostConfig/ExtraHosts - A list of hostnames/IP mappings to add to the container’s /etc/hosts file. Specified in the form ["hostname:IP"].
84
- # - `docker run --add-host host:ip`
85
- # HostConfig/GroupAdd - A list of additional groups that the container process will run as
86
- # - `docker run --group-add blah`
87
- # HostConfig/IpcMode - IpcMode // IPC namespace to use for the container
88
- # - `docker run --ipc host`
89
- # HostConfig/Isolation - Isolation // Isolation technology of the container (eg default, hyperv)
90
- # - `docker run --isolation host`
91
- # HostConfig/KernelMemory - Kernel memory limit in bytes.
92
- # - `docker run --kernel-memory 4m`
93
- # HostConfig/Links - A list of links for the container. Each link entry should be in the form of container_name:alias.
94
- # - `docker run --link containername`
95
- # HostConfig/LogConfig - Log configuration for the container, specified as a JSON object in the form { "Type": "<driver_name>", "Config": {"key1": "val1"}}. Available types: json-file, syslog, journald, gelf, awslogs, splunk, none. json-file logging driver.
96
- # HostConfig/LogConfig/Type
97
- # - `docker run --log-driver driver`
98
- # HostConfig/LogConfig/Config
99
- # - `docker run --log-opt a=b`
100
- # HostConfig/Memory - Memory limit in bytes.
101
- # - `docker run --memory 4G`
102
- # HostConfig/MemoryReservation - Memory soft limit in bytes.
103
- # - `docker run --memory-reservation 4G`
104
- # HostConfig/MemorySwap - Total memory limit (memory + swap); set -1 to enable unlimited swap. You must use this with memory and make the swap value larger than memory.
105
- # - `docker run --memory-swap 4G`
106
- # HostConfig/MemorySwappiness - Tune a container’s memory swappiness behavior. Accepts an integer between 0 and 100.
107
- # - `docker run --memory-swappiness 50`
108
- # HostConfig/NetworkMode - Sets the networking mode for the container. Supported standard values are: bridge, host, none, and container:<name|id>. Any other value is taken as a custom network’s name to which this container should connect to.
109
- # - `docker run --net host`
110
- # HostConfig/OomKillDisable - Boolean value, whether to disable OOM Killer for the container or not.
111
- # - `docker run --oom-kill-disable`
112
- # HostConfig/OomScoreAdj - An integer value containing the score given to the container in order to tune OOM killer preferences.
113
- # - `docker run --oom-score-adj 1`
114
- # HostConfig/PidMode - PidMode // PID namespace to use for the container
115
- # - `docker run --pid host`
116
- # HostConfig/PidsLimit - int64 // Setting pids limit for a container
117
- # HostConfig/PortBindings - A map of exposed container ports and the host port they should map to. A JSON object in the form { <port>/<protocol>: [{ "HostPort": "<port>" }] } Take note that port is specified as a string and not an integer value.
118
- # - `docker run --publish 8080:8081`
119
- # HostConfig/Privileged - Gives the container full access to the host. Specified as a boolean value.
120
- # - `docker run --privileged`
121
- # HostConfig/PublishAllPorts - Allocates a random host port for all of a container’s exposed ports. Specified as a boolean value.
122
- # - `docker run --publish-all`
123
- # HostConfig/ReadonlyRootfs - Mount the container’s root filesystem as read only. Specified as a boolean value.
124
- # - `docker run --read-only`
125
- # HostConfig/RestartPolicy – The behavior to apply when the container exits. The value is an object with a Name property of either "always" to always restart, "unless-stopped" to restart always except when user has manually stopped the container or "on-failure" to restart only when the container exit code is non-zero. If on-failure is used, MaximumRetryCount controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server.
126
- # - `docker run --restart no`
127
- # HostConfig/RestartPolicy/Name
128
- # - `docker run --restart always`
129
- # HostConfig/RestartPolicy/MaximumRetryCount
130
- # - `docker run --restart on-failure:20`
131
- # HostConfig/SandboxSize - uint64 // System drive will be expanded to at least this size (in bytes)
132
- # HostConfig/SecurityOpt - A list of string values to customize labels for MLS systems, such as SELinux.
133
- # - docker run --security-opt label:disabled
134
- # HostConfig/ShmSize - Size of /dev/shm in bytes. The size must be greater than 0. If omitted the system uses 64MB.
135
- # - `docker run --shm-size 4m`
136
- # HostConfig/StorageOpt - []string // Storage driver options per container.
137
- # HostConfig/Sysctls - map[string]string // List of Namespaced sysctls used for the container
138
- # HostConfig/Tmpfs - map[string]string // List of tmpfs (mounts) used for the container
139
- # HostConfig/Ulimits - A list of ulimits to set in the container, specified as { "Name": <name>, "Soft": <soft limit>, "Hard": <hard limit> }, for example: Ulimits: { "Name": "nofile", "Soft": 1024, "Hard": 2048 }
140
- # - `docker run --ulimit /dev/sda:1024:2048`
141
- # HostConfig/UTSMode - UTSMode // UTS namespace to use for the container
142
- # - `docker run --uts host`
143
- # HostConfig/UsernsMode - UsernsMode // The user namespace to use for the container
144
- # HostConfig/VolumeDriver - Driver that this container users to mount volumes.
145
- # - `docker run --volume-driver supervolume`
146
- # HostConfig/VolumesFrom - A list of volumes to inherit from another container. Specified in the form <container name>[:<ro|rw>]
147
- # - `docker run --volumes-from db`
148
- # Hostname - A string value containing the hostname to use for the container.
149
- # - `docker run --hostname blah`
150
- # Image - A string specifying the image name to use for the container.
151
- # - `docker run IMAGE_NAME ...`
152
- # Labels - Adds a map of labels to a container. To specify a map: {"key":"value"[,"key2":"value2"]}
153
- # - `docker run --label a=b`
154
- # MacAddress - string // Mac Address of the container
155
- # - `docker run --mac-address 92:d0:c6:0a:29:33`
156
- # Mounts - An array of mount points in the container.
157
- # NetworkDisabled - Boolean value, when true disables networking for the container
158
- # NetworkSettings/<network>/IPAMConfig/IPv4Address
159
- # - `docker run --ip address`
160
- # NetworkSettings/<network>/IPAMConfig/IPv6Address
161
- # - `docker run --ip6 address`
162
- # NetworkSettings/<network>/Aliases
163
- # - `docker run --net-alias blah`
164
- # OnBuild - []string // ONBUILD metadata that were defined on the image Dockerfile
165
- # OpenStdin - Boolean value, opens stdin,
166
- # - `docker run --interactive`
167
- # PublishService - string // Name of the network service exposed by the container
168
- # StdinOnce - Boolean value, close stdin after the 1 attached client disconnects.
169
- # StopSignal - Signal to stop a container as a string or unsigned integer. SIGTERM by default.
170
- # - `docker run --stop-signal SIGKILL`
171
- # Tty - Boolean value, Attach standard streams to a tty, including stdin if it is not closed.
172
- # - `docker run --tty`
173
- # User - A string value specifying the user inside the container.
174
- # - `docker run --user bob:wheel`
175
- # Volumes - map[string]struct{} // List of volumes (mounts) used for the container
176
- # - `docker run --volume blarghle`
177
- # WorkingDir - A string specifying the working directory for commands to run in.
178
- # - `docker run --workdir /home/uber`
179
- #
180
- # The following are runtime updateable:
181
- # HostConfig/BlkioBps
182
- # HostConfig/BlkioIOps
183
- # HostConfig/BlkioWeight
184
- # HostConfig/BlkioWeightDevice
185
- # HostConfig/BlkioDeviceReadBps
186
- # HostConfig/BlkioDeviceWriteBps
187
- # HostConfig/BlkioDeviceReadIOps
188
- # HostConfig/BlkioDeviceWriteIOps
189
- # HostConfig/CgroupParent
190
- # HostConfig/CpuPeriod
191
- # HostConfig/CpuQuota
192
- # HostConfig/CpuShares
193
- # HostConfig/CpusetCpus
194
- # HostConfig/CpusetMems
195
- # HostConfig/Devices
196
- # HostConfig/DiskQuota
197
- # HostConfig/KernelMemory
198
- # HostConfig/Memory
199
- # HostConfig/MemoryReservation
200
- # HostConfig/MemorySwap
201
- # HostConfig/MemorySwappiness
202
- # HostConfig/OomKillDisable
203
- # HostConfig/PidsLimit
204
- # HostConfig/RestartPolicy
205
- # HostConfig/SandboxSize
206
- # HostConfig/Ulimits
207
- #
208
- class DockerRunOptions
209
- def self.include_command_line_options_in_container_config(config, docker_options)
210
-
211
- # Grab the command line options we've begun supporting
212
- # The following are command line equivalents for `docker run`
213
- docker_options.each do |key, value|
214
- # Remove -, symbolize key
215
- key = key.to_s.gsub('-', '_').to_sym
216
- option = cli_options[key]
217
- if !option
218
- raise "Unknown option in docker_options: #{key.inspect}"
219
- end
220
-
221
- # Figure out the new value
222
- if option[:type] == :boolean
223
- value == !!value
224
- elsif option[:type] == Array
225
- value = Array(value)
226
- elsif option[:type] == Integer
227
- value = parse_int(value) if value.is_a?(String)
228
- elsif option[:type].is_a?(String)
229
- # If it's A:B:C, translate [ "a:b:c", "d:e:f" ] -> [ { "A" => "a", "B" => "b", "C" => "c" }, { "A" => "d", "B" => "e", "C" => "f" } ]
230
- names = option[:type].split(":")
231
- if names.size == 2 && value.is_a?(Hash)
232
- value.map { |key,value| { names[0] => key, names[1] => value } }
233
- else
234
- Array(value).map do |item|
235
- item_values = item.split(":", names.size)
236
- item = Hash[names.zip(item_values)]
237
- end
238
- end
239
- end
240
-
241
- option[:api].each do |api|
242
- # Grab the parent API key so we know what we're setting
243
- api_parent = config
244
- api.split("/")[0..-2].each do |api_key|
245
- api_parent[api_key] = {} if !api_parent[api_key]
246
- api_parent = api_parent[api_key]
247
- end
248
- api_key = api.split("/")[-1] if api
249
-
250
- # Bring in the current value
251
- if option[:type] == Array || option[:type].is_a?(String)
252
- api_parent[api_key] ||= []
253
- api_parent[api_key] += value
254
- else
255
- api_parent[api_key] = value
256
- end
257
- end
258
-
259
- # Call the block (if any)
260
- if option[:block]
261
- option[:block].call(config, value)
262
- end
263
- end
264
- config
265
- end
266
-
267
- def self.cli_options
268
- @cli_options ||= {}
269
- end
270
-
271
- def self.cli_option(option_name, type=nil, aliases: nil, api: nil, &block)
272
- api = Array(api)
273
- cli_options[option_name] = { type: type, api: Array(api), block: block }
274
- Array(aliases).each do |option_name|
275
- cli_options[option_name] = { type: type, api: Array(api), block: block }
276
- end
277
- end
278
-
279
- # docker run [OPTIONS] IMAGE COMMAND
280
- cli_option :command do |config, command|
281
- command = Shellwords.split(command) if command.is_a?(String)
282
- config["Cmd"] = command
283
- end
284
-
285
- # docker run [OPTIONS] IMAGE COMMAND
286
- cli_option :image, api: "Image"
287
-
288
- # -a, --attach=[] Attach to STDIN, STDOUT or STDERR
289
- cli_option :attach, Array, aliases: :a do |config,value|
290
- Array(value).each do |stream|
291
- # STDIN -> Stdin
292
- stream = stream.to_s.downcase.capitalize
293
- config["Attach#{stream}"] = true
294
- end
295
- end
296
- # --add-host=[] Add a custom host-to-IP mapping (host:ip)
297
- cli_option :add_host, Array, api: "HostConfig/ExtraHosts", aliases: :add_hosts
298
- # --blkio-weight=0 Block IO weight (relative weight)
299
- cli_option :blkio_weight, api: "HostConfig/BlkioWeight"
300
- # --blkio-weight-device=[] Block IO weight (relative device weight, format: `DEVICE_NAME:WEIGHT`)
301
- cli_option :blkio_weight, Array, api: "HostConfig/BlkioWeightDevice", aliases: :blkio_weights
302
- # --cap-add=[] Add Linux capabilities
303
- cli_option :cap_add, Array, api: "HostConfig/CapAdd"
304
- # --cap-drop=[] Drop Linux capabilities
305
- cli_option :cap_drop, Array, api: "HostConfig/CapDrop"
306
- # --cgroup-parent="" Optional parent cgroup for the container
307
- cli_option :cgroup_parent, api: "HostConfig/CgroupParent"
308
- # --cidfile="" Write the container ID to the file
309
- cli_option :cidfile, api: "HostConfig/ContainerIDFile"
310
- # --cpu-period=0 Limit CPU CFS (Completely Fair Scheduler) period
311
- cli_option :cpu_period, api: "HostConfig/CpuShares"
312
- # --cpu-quota=0 Limit CPU CFS (Completely Fair Scheduler) quota
313
- cli_option :cpu_quota, api: "HostConfig/CpuQuota"
314
- # --cpu-shares=0 CPU shares (relative weight)
315
- cli_option :cpu_period, api: "HostConfig/CpuPeriod"
316
- # --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1)
317
- cli_option :cpuset_cpus, api: "HostConfig/CpusetCpus"
318
- # --cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1)
319
- cli_option :cpuset_mems, api: "HostConfig/CpusetMems"
320
- # --device=[] Add a host device to the container
321
- cli_option :device, "PathOnHost:PathInContainer", api: "HostConfig/Devices", aliases: :devices
322
- # --device-read-bps=[] Limit read rate (bytes per second) from a device (e.g., --device-read-bps=/dev/sda:1mb)
323
- cli_option :device_read_bps, "Path:Rate", api: "HostConfig/BlkioDeviceReadBps"
324
- # --device-read-iops=[] Limit read rate (IO per second) from a device (e.g., --device-read-iops=/dev/sda:1000)
325
- cli_option :device_read_iops, "Path:Rate", api: "HostConfig/BlkioDeviceReadIOps"
326
- # --device-write-bps=[] Limit write rate (bytes per second) to a device (e.g., --device-write-bps=/dev/sda:1mb)
327
- cli_option :device_write_bps, "Path:Rate", api: "HostConfig/BlkioDeviceWriteBps"
328
- # --device-write-iops=[] Limit write rate (IO per second) to a device (e.g., --device-write-bps=/dev/sda:1000)
329
- cli_option :device_write_iops, "Path:Rate", api: "HostConfig/BlkioDeviceWriteIOps"
330
- # --dns=[] Set custom DNS servers
331
- cli_option :dns, Array, api: "HostConfig/Dns"
332
- # --dns-opt=[] Set custom DNS options
333
- cli_option :dns_opt, Array, api: "HostConfig/DnsOptions", aliases: :dns_opts
334
- # --dns-search=[] Set custom DNS search domains
335
- cli_option :dns_search, Array, api: "HostConfig/DnsSearch"
336
- # --entrypoint="" Overwrite the default ENTRYPOINT of the image
337
- cli_option :entrypoint do |config, command|
338
- command = Shellwords.split(command) if command.is_a?(String)
339
- config["Entrypoint"] = command
340
- end
341
- # -e, --env=[] Set environment variables
342
- cli_option :env, aliases: :e do |config, env|
343
- if env.is_a?(Hash)
344
- env = env.map { |k,v| "#{k}=#{v}" }
345
- end
346
- config["Env"] ||= []
347
- config["Env"] += Array(env)
348
- end
349
- # --expose=[] Expose a port or a range of ports
350
- cli_option :expose do |config, value|
351
- config["ExposedPorts"] ||= {}
352
- Array(value).each do |port|
353
- parse_port(port).each do |host_ip, host_port, container_port|
354
- config["ExposedPorts"][container_port] = {}
355
- end
356
- end
357
- end
358
- # --group-add=[] Add additional groups to run as
359
- cli_option :group_add, Array, api: 'HostConfig/GroupAdd'
360
- # -h, --hostname="" Container host name
361
- cli_option :hostname, api: 'HostConfig/Hostname', aliases: :h
362
- # -i, --interactive Keep STDIN open even if not attached
363
- cli_option :interactive, :boolean, api: [ 'OpenStdin', 'AttachStdin' ]
364
- # --ip="" Container IPv4 address (e.g. 172.30.100.104)
365
- cli_option :ip do |config, value|
366
- # Where this goes depends on the network! TODO doesn't work with `--net`
367
- config["NetworkSettings"] ||= {}
368
- network = config["NetworkMode"] || "default"
369
- config["NetworkSettings"][network] ||= {}
370
- config["NetworkSettings"][network]["IPAMConfig"] ||= {}
371
- config["NetworkSettings"][network]["IPAMConfig"]["IPv4Address"] = value
372
- end
373
- # --ip6="" Container IPv6 address (e.g. 2001:db8::33)
374
- cli_option :ip6 do |config, value|
375
- # Where this goes depends on the network! TODO doesn't work with `--net`
376
- config["NetworkSettings"] ||= {}
377
- network = config["NetworkMode"] || "default"
378
- config["NetworkSettings"][network] ||= {}
379
- config["NetworkSettings"][network]["IPAMConfig"] ||= {}
380
- config["NetworkSettings"][network]["IPAMConfig"]["IPv6Address"] = value
381
- end
382
- # --ipc="" IPC namespace to use
383
- cli_option :ipc, api: 'HostConfig/IpcMode' do |config, value|
384
- # TODO this should ONLY be set if security-opt isn't set at all.
385
- config["HostConfig"]["SecurityOpt"] ||= [ "label:disable" ]
386
- end
387
- # --isolation="" Container isolation technology
388
- cli_option :isolation, api: 'Isolation'
389
- # --kernel-memory="" Kernel memory limit
390
- cli_option :kernel_memory, Integer, api: 'KernelMemory'
391
- # -l, --label=[] Set metadata on the container (e.g., --label=com.example.key=value)
392
- cli_option :label, Array, api: "Labels", aliases: [ :l, :labels ]
393
- # --link=[] Add link to another container
394
- cli_option :link, Array, api: "HostConfig/Links", aliases: :links
395
- # --log-driver="" Logging driver for container
396
- cli_option :log_driver, api: "HostConfig/LogConfig/Type"
397
- # --log-opt=[] Log driver specific options
398
- cli_option :log_opt, aliases: :log_opts do |config, value|
399
- config["HostConfig"] ||= {}
400
- config["HostConfig"]["LogConfig"] ||= {}
401
- config["HostConfig"]["LogConfig"]["Type"] ||= {}
402
- Array(value).each do |keyval|
403
- k,v = keyval.split("=", 2)
404
- config["HostConfig"]["LogConfig"][k] = v
405
- end
406
- end
407
- # --mac-address="" Container MAC address (e.g. 92:d0:c6:0a:29:33)
408
- cli_option :mac_address, api: "MacAddress"
409
- # -m, --memory="" Memory limit
410
- cli_option :memory, Integer, api: "HostConfig/Memory", aliases: :m
411
- # --memory-reservation="" Memory soft limit
412
- cli_option :memory_reservation, Integer, api: "HostConfig/MemoryReservation"
413
- # --memory-swap="" A positive integer equal to memory plus swap. Specify -1 to enable unlimited swap.
414
- cli_option :memory_swap, Integer, api: "HostConfig/MemorySwap"
415
- # --memory-swappiness="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100.
416
- cli_option :memory_swappiness, Integer, api: "HostConfig/MemorySwappiness"
417
- # --net="bridge" Connect a container to a network
418
- # 'bridge': create a network stack on the default Docker bridge
419
- # 'none': no networking
420
- # 'container:<name|id>': reuse another container's network stack
421
- # 'host': use the Docker host network stack
422
- # '<network-name>|<network-id>': connect to a user-defined network
423
- cli_option :net do |config, value|
424
- value = value.to_s
425
- old_network = config["NetworkMode"] || "default"
426
- config["NetworkMode"] = value
427
- # If we already stored stuff in the default network, move it to the new network
428
- if config["NetworkSettings"] && config["NetworkSettings"][old_network]
429
- config["NetworkSettings"][value] = config["NetworkSettings"].delete(old_network)
430
- end
431
- end
432
- # --net-alias=[] Add network-scoped alias for the container
433
- cli_option :net_alias, aliases: :net_aliases do |config, value|
434
- # Where this goes depends on the network! TODO doesn't work with `--net`
435
- config["NetworkSettings"] ||= {}
436
- network = config["NetworkMode"] || "default"
437
- config["NetworkSettings"][network] ||= {}
438
- config["NetworkSettings"][network]["Aliases"] ||= []
439
- config["NetworkSettings"][network]["Aliases"] += Array(value)
440
- end
441
- # --oom-kill-disable Whether to disable OOM Killer for the container or not
442
- cli_option :oom_kill_disable, :boolean, api: "HostConfig/OomKillDisable"
443
- # --oom-score-adj=0 Tune the host's OOM preferences for containers (accepts -1000 to 1000)
444
- cli_option :oom_score_adj, Integer, api: "HostConfig/OomScoreAdj"
445
- # --pid="" PID namespace to use
446
- cli_option :pid, api: "HostConfig/PidMode" do |config, value|
447
- # TODO this should ONLY be set if security-opt isn't set at all.
448
- config["HostConfig"]["SecurityOpt"] ||= [ "label:disable" ]
449
- end
450
- # --privileged Give extended privileges to this container
451
- cli_option :privileged, :boolean, api: "HostConfig/Privileged"
452
- # -p, --publish=[] Publish a container's port(s) to the host
453
- cli_option :publish, aliases: [ :p, :ports ] do |config, value|
454
- config["HostConfig"] ||= {}
455
- config["HostConfig"]["PortBindings"] ||= {}
456
- config["ExposedPorts"] ||= {}
457
-
458
- Array(value).each do |port|
459
- parse_port(port).each do |host_ip, host_port, container_port|
460
- config["HostConfig"]["PortBindings"][container_port] ||= []
461
- config["HostConfig"]["PortBindings"][container_port] << { "HostIp" => host_ip, "HostPort" => host_port }
462
- config["ExposedPorts"][container_port] = {}
463
- end
464
- end
465
- end
466
- # -P, --publish-all Publish all exposed ports to random ports
467
- cli_option :publish_all, :boolean, api: "HostConfig/PublishAllPorts", aliases: :P
468
- # --read-only Mount the container's root filesystem as read only
469
- cli_option :read_only, :boolean, api: "HostConfig/ReadonlyRootfs"
470
- # --restart="no" Restart policy (no, on-failure[:max-retry], always, unless-stopped)
471
- cli_option :restart do |config, value|
472
- name, retries = value.split(':')
473
- config["HostConfig"] ||= {}
474
- config["HostConfig"]["RestartPolicy"] ||= {}
475
- config["HostConfig"]["RestartPolicy"]["Name"] = name
476
- if retries
477
- config["HostConfig"]["RestartPolicy"]["MaximumRetryCount"] = retries
478
- else
479
- config["HostConfig"]["RestartPolicy"].delete("MaximumRetryCount")
480
- end
481
- end
482
- # --rm Automatically remove the container when it exits
483
- cli_option :rm, :boolean, api: "HostConfig/AutoRemove"
484
- # --shm-size=[] Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`. Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`.
485
- cli_option :shm_size, Integer, api: "HostConfig/ShmSize", aliases: :shm_sizes
486
- # --security-opt=[] Security Options
487
- cli_option :security_opt, Array, api: "HostConfig/SecurityOpt", aliases: :security_opts
488
- # --stop-signal="SIGTERM" Signal to stop a container
489
- cli_option :stop_signal, api: "StopSignal"
490
- # -t, --tty Allocate a pseudo-TTY
491
- cli_option :tty, :boolean, api: "Tty", aliases: :tty
492
- # -u, --user="" Username or UID (format: <name|uid>[:<group|gid>])
493
- cli_option :user, api: "User", aliases: :u
494
- # --ulimit=[] Ulimit options
495
- cli_option :ulimit, aliases: :ulimits do |config, value|
496
- config["HostConfig"] ||= {}
497
- config["HostConfig"]["Ulimits"] ||= []
498
- value.each do |ulimit|
499
- type, values = ulimit.split("=", 2)
500
- soft, hard = values.split(":", 2)
501
- config["HostConfig"]["Ulimits"] << { "Name" => type, "Soft" => soft, "Hard" => hard }
502
- end
503
- end
504
- # --uts="" UTS namespace to use
505
- cli_option :uts, api: "HostConfig/UTSMode"
506
- # -v, --volume=[host-src:]container-dest[:<options>]
507
- # Bind mount a volume. The comma-delimited
508
- # `options` are [rw|ro], [z|Z], or
509
- # [[r]shared|[r]slave|[r]private]. The
510
- # 'host-src' is an absolute path or a name
511
- # value.
512
- cli_option :volume, aliases: [ :v, :volumes ] do |config, value|
513
- # Things without : in them at all, are just volumes.
514
- binds, volumes = Array(value).partition { |v| v.include?(':') }
515
- config["HostConfig"] ||= {}
516
- unless binds.empty?
517
- config["HostConfig"]["Binds"] ||= []
518
- config["HostConfig"]["Binds"] += binds
519
- end
520
- unless volumes.empty?
521
- config["Volumes"] ||= []
522
- config["Volumes"] += volumes
523
- end
524
- end
525
- # --volume-driver="" Container's volume driver
526
- cli_option :volume_driver, api: "HostConfig/VolumeDriver"
527
- # -w, --workdir="" Working directory inside the container
528
- cli_option :workdir, api: "WorkingDir", aliases: :w
529
- # --volumes-from=[] Mount volumes from the specified container(s)
530
- cli_option :volumes_from, Array, api: 'HostConfig/VolumesFrom'
531
-
532
- # Not relevant to API or Chef:
533
- # -d, --detach Run container in background and print container ID
534
- # --detach-keys Specify the escape key sequence used to detach a container
535
- # --disable-content-trust=true Skip image verification
536
- # --env-file=[] Read in a file of environment variables
537
- # --help Print usage
538
- # --label-file=[] Read in a file of labels (EOL delimited)
539
- # --name="" Assign a name to the container
540
- # --sig-proxy=true Proxy received signals to the process
541
-
542
- private
543
-
544
- # Lifted from docker cookbook
545
- def self.parse_port(v)
546
- parts = v.to_s.split(':')
547
- case parts.length
548
- when 3
549
- host_ip = parts[0]
550
- host_port = parts[1]
551
- container_port = parts[2]
552
- when 2
553
- host_ip = '0.0.0.0'
554
- host_port = parts[0]
555
- container_port = parts[1]
556
- when 1
557
- host_ip = ''
558
- host_port = ''
559
- container_port = parts[0]
560
- end
561
- port_range, protocol = container_port.split('/')
562
- if port_range.include?('-')
563
- port_range = container_port.split('-')
564
- port_range.map!(&:to_i)
565
- Chef::Log.fatal("FATAL: Invalid port range! #{container_port}") if port_range[0] > port_range[1]
566
- port_range = (port_range[0]..port_range[1]).to_a
567
- end
568
- # qualify the port-binding protocol even when it is implicitly tcp #427.
569
- protocol = 'tcp' if protocol.nil?
570
- Array(port_range).map do |port|
571
- [ host_ip, host_port, "#{port}/#{protocol}"]
572
- end
573
- end
574
-
575
- def self.parse_int(value)
576
- value = value.upcase
577
- if value.end_with?("TB") || value.end_with?("T")
578
- value.to_i * 1024*1024*1024*1024
579
- elsif value.end_with?("GB") || value.end_with?("G")
580
- value.to_i * 1024*1024*1024
581
- elsif value.end_with?("MB") || value.end_with?("M")
582
- value.to_i * 1024*1024
583
- elsif value.end_with?("KB") || value.end_with?("K")
584
- value.to_i * 1024
585
- else
586
- value.to_i
587
- end
588
- end
589
-
590
- end
591
- end
592
- end
593
- end