Debian Codegraph @

heartbeat/docker

raw
1 #!/bin/sh
2 #
3 # The docker HA resource agent creates and launches a docker container
4 # based off a supplied docker image. Containers managed by this agent
5 # are both created and removed upon the agent's start and stop actions.
6 #
7 # Copyright (c) 2014 David Vossel <[email protected]>
8 # All Rights Reserved.
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of version 2 of the GNU General Public License as
12 # published by the Free Software Foundation.
13 #
14 # This program is distributed in the hope that it would be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17 #
18 # Further, this software is distributed without any warranty that it is
19 # free of the rightful claim of any third person regarding infringement
20 # or the like. Any license provided herein, whether implied or
21 # otherwise, applies only to this software file. Patent licenses, if
22 # any, provided herein do not apply to combinations of this program with
23 # other software, or any other product whatsoever.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write the Free Software Foundation,
27 # Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
28 #
29
30 #######################################################################
31 # Initialization:
32
33 : ${OCF_FUNCTIONS_DIR=${OCF_ROOT}/lib/heartbeat}
34 . ${OCF_FUNCTIONS_DIR}/ocf-shellfuncs
35
36 # Parameter defaults
37
38 OCF_RESKEY_reuse_default="0"
39
40 : ${OCF_RESKEY_reuse=${OCF_RESKEY_reuse_default}}
41
42 #######################################################################
43
44 meta_data()
45 {
46 cat <<END
47 <?xml version="1.0"?>
48 <!DOCTYPE resource-agent SYSTEM "ra-api-1.dtd">
49 <resource-agent name="docker" version="1.0">
50 <version>1.0</version>
51
52 <longdesc lang="en">
53 The docker HA resource agent creates and launches a docker container
54 based off a supplied docker image. Containers managed by this agent
55 are both created and removed upon the agent's start and stop actions.
56 </longdesc>
57 <shortdesc lang="en">Docker container resource agent.</shortdesc>
58
59 <parameters>
60 <parameter name="image" required="1" unique="0">
61 <longdesc lang="en">
62 The docker image to base this container off of.
63 </longdesc>
64 <shortdesc lang="en">docker image</shortdesc>
65 <content type="string"/>
66 </parameter>
67
68 <parameter name="name" required="0" unique="0">
69 <longdesc lang="en">
70 The name to give the created container. By default this will
71 be that resource's instance name.
72 </longdesc>
73 <shortdesc lang="en">docker container name</shortdesc>
74 <content type="string"/>
75 </parameter>
76
77 <parameter name="allow_pull" unique="0">
78 <longdesc lang="en">
79 Allow the image to be pulled from the configured docker registry when
80 the image does not exist locally. NOTE, this can drastically increase
81 the time required to start the container if the image repository is
82 pulled over the network.
83 </longdesc>
84 <shortdesc lang="en">Allow pulling non-local images</shortdesc>
85 <content type="boolean"/>
86 </parameter>
87
88 <parameter name="run_opts" required="0" unique="0">
89 <longdesc lang="en">
90 Add options to be appended to the 'docker run' command which is used
91 when creating the container during the start action. This option allows
92 users to do things such as setting a custom entry point and injecting
93 environment variables into the newly created container. Note the '-d'
94 option is supplied regardless of this value to force containers to run
95 in the background.
96
97 NOTE: Do not explicitly specify the --name argument in the run_opts. This
98 agent will set --name using either the resource's instance or the name
99 provided in the 'name' argument of this agent.
100
101 </longdesc>
102 <shortdesc lang="en">run options</shortdesc>
103 <content type="string"/>
104 </parameter>
105
106 <parameter name="run_cmd" required="0" unique="0">
107 <longdesc lang="en">
108 Specify a command to launch within the container once
109 it has initialized.
110 </longdesc>
111 <shortdesc lang="en">run command</shortdesc>
112 <content type="string"/>
113 </parameter>
114
115 <parameter name="mount_points" required="0" unique="0">
116 <longdesc lang="en">
117 A comma separated list of directories that the container is expecting to use.
118 The agent will ensure they exist by running 'mkdir -p'
119 </longdesc>
120 <shortdesc lang="en">Required mount points</shortdesc>
121 <content type="string"/>
122 </parameter>
123
124 <parameter name="monitor_cmd" required="0" unique="0">
125 <longdesc lang="en">
126 Specify the full path of a command to launch within the container to check
127 the health of the container. This command must return 0 to indicate that
128 the container is healthy. A non-zero return code will indicate that the
129 container has failed and should be recovered.
130
131 If 'docker exec' is supported, it is used to execute the command. If not,
132 nsenter is used.
133
134 Note: Using this method for monitoring processes inside a container
135 is not recommended, as containerd tries to track processes running
136 inside the container and does not deal well with many short-lived
137 processes being spawned. Ensure that your container monitors its
138 own processes and terminates on fatal error rather than invoking
139 a command from the outside.
140 </longdesc>
141 <shortdesc lang="en">monitor command</shortdesc>
142 <content type="string"/>
143 </parameter>
144
145 <parameter name="force_kill" required="0" unique="0">
146 <longdesc lang="en">
147 Kill a container immediately rather than waiting for it to gracefully
148 shutdown
149 </longdesc>
150 <shortdesc lang="en">force kill</shortdesc>
151 <content type="boolean"/>
152 </parameter>
153
154 <parameter name="reuse" required="0" unique="0">
155 <longdesc lang="en">
156 Allow the container to be reused once it is stopped. By default,
157 containers get removed once they are stopped. Enable this option
158 to have the particular one persist when this happens.
159 </longdesc>
160 <shortdesc lang="en">reuse container</shortdesc>
161 <content type="boolean" default="${OCF_RESKEY_reuse_default}"/>
162 </parameter>
163
164 <parameter name="query_docker_health" required="0" unique="0">
165 <longdesc lang="en">
166 Query the builtin healthcheck of docker (v1.12+) to determine health of the
167 container. If left empty or set to false it will not be used.
168
169 The healthcheck itself has to be configured within docker, e.g. via
170 HEALTHCHECK in Dockerfile. This option just queries in what condition
171 docker considers the container to be and lets ocf do its thing accordingly.
172
173 Note that the time a container is in "starting" state counts against the
174 monitor timeout.
175
176 This is an additional check besides the standard check for the container
177 to be running, and the optional monitor_cmd check. It doesn't disable or
178 override them, so all of them (if used) have to come back healthy for the
179 container to be considered healthy.
180 </longdesc>
181 <shortdesc lang="en">use healthcheck</shortdesc>
182 <content type="boolean"/>
183 </parameter>
184
185 </parameters>
186
187 <actions>
188 <action name="start" timeout="90s" />
189 <action name="stop" timeout="90s" />
190 <action name="monitor" timeout="30s" interval="30s" depth="0" />
191 <action name="meta-data" timeout="5s" />
192 <action name="validate-all" timeout="30s" />
193 </actions>
194 </resource-agent>
195 END
196 }
197
198 #######################################################################
199 REQUIRE_IMAGE_PULL=0
200
201 docker_usage()
202 {
203 cat <<END
204 usage: $0 {start|stop|monitor|validate-all|meta-data}
205
206 Expects to have a fully populated OCF RA-compliant environment set.
207 END
208 }
209
210
211 monitor_cmd_exec()
212 {
213 local rc=$OCF_SUCCESS
214 local out
215
216 if [ -z "$OCF_RESKEY_monitor_cmd" ]; then
217 return $rc
218 fi
219
220 if docker exec --help >/dev/null 2>&1; then
221 out=$(docker exec ${CONTAINER} $OCF_RESKEY_monitor_cmd 2>&1)
222 rc=$?
223 else
224 out=$(echo "$OCF_RESKEY_monitor_cmd" | nsenter --target $(docker inspect --type=container --format {{.State.Pid}} ${CONTAINER}) --mount --uts --ipc --net --pid 2>&1)
225 rc=$?
226 fi
227
228 if [ $rc -eq 127 ]; then
229 ocf_log err "monitor cmd failed (rc=$rc), output: $out"
230 ocf_exit_reason "monitor_cmd, ${OCF_RESKEY_monitor_cmd} , not found within container."
231 # there is no recovering from this, exit immediately
232 exit $OCF_ERR_ARGS
233 elif [ $rc -ne 0 ]; then
234 ocf_exit_reason "monitor cmd failed (rc=$rc), output: $out"
235 rc=$OCF_ERR_GENERIC
236 else
237 ocf_log debug "monitor cmd passed: exit code = $rc"
238 fi
239
240 return $rc
241 }
242
243 container_exists()
244 {
245 local err
246
247 err=$(docker inspect --type=container $CONTAINER 2>&1 >/dev/null)
248
249 if [ $? -ne $OCF_SUCCESS ]; then
250 case $err in
251 *"No such container"*)
252 # Return failure instead of exiting if container does not exist
253 return 1
254 ;;
255 *)
256 # Exit if error running command
257 ocf_exit_reason "$err"
258 exit $OCF_ERR_GENERIC
259 ;;
260 esac
261 fi
262
263 return $OCF_SUCCESS
264 }
265
266 remove_container()
267 {
268 if ocf_is_true "$OCF_RESKEY_reuse"; then
269 # never remove the container if we have reuse enabled.
270 return 0
271 fi
272
273 container_exists
274 if [ $? -ne 0 ]; then
275 # don't attempt to remove a container that doesn't exist
276 return 0
277 fi
278 ocf_log notice "Cleaning up inactive container, ${CONTAINER}."
279 ocf_run docker rm $CONTAINER
280 }
281
282 docker_simple_status()
283 {
284 local val
285
286 if [ ! -x "$(command -v docker)" ]; then
287 ocf_exit_reason "docker is not installed on this host"
288 return $OCF_ERR_INSTALLED
289 fi
290
291
292 # let's first check if the daemon is up and running.
293 VERSION_OUT=$(docker version)
294 version_ret=$?
295 if [ $version_ret -eq 1 ]; then
296 ocf_log err "Docker service is not running or in error state while checking for ${CONTAINER}, based on image, ${OCF_RESKEY_image}: ${VERSION_OUT}"
297 return $OCF_NOT_RUNNING
298 fi
299
300 container_exists
301 if [ $? -ne 0 ]; then
302 return $OCF_NOT_RUNNING
303 fi
304
305 # retrieve the 'Running' attribute for the container
306 val=$(docker inspect --type=container --format {{.State.Running}} $CONTAINER 2>/dev/null)
307 if [ $? -ne 0 ]; then
308 #not running as a result of container not being found
309 return $OCF_NOT_RUNNING
310 fi
311
312 if ocf_is_true "$val"; then
313 # container exists and is running
314 return $OCF_SUCCESS
315 fi
316
317 return $OCF_NOT_RUNNING
318 }
319
320 docker_health_status()
321 {
322
323 if ocf_is_true "$OCF_RESKEY_query_docker_health"; then
324 local val
325
326 container_exists
327 if [ $? -ne 0 ]; then
328 return $OCF_NOT_RUNNING
329 fi
330
331 # retrieve the 'Health' attribute for the container
332 # This is a bash-style do-while loop to wait until instance is started.
333 # if starting takes longer than monitor timeout then upstream will make this fail.
334 while
335
336 val=$(docker inspect --type=container --format {{.State.Health.Status}} $CONTAINER 2>/dev/null)
337 if [ $? -ne 0 ]; then
338 #not healthy as a result of container not being found
339 return $OCF_NOT_RUNNING
340 fi
341 test "$val" = "starting"
342 do
343
344 sleep 1
345 done
346
347 if [ "$val" = "healthy" ]; then
348 # container exists and is healthy
349 return $OCF_SUCCESS
350 fi
351
352 return $OCF_NOT_RUNNING
353 fi
354
355 return 0
356 }
357
358
359
360 docker_monitor()
361 {
362 local rc=0
363
364 docker_simple_status
365 rc=$?
366
367 if [ $rc -ne 0 ]; then
368 return $rc
369 fi
370
371 docker_health_status
372 rc=$?
373
374 if [ $rc -ne 0 ]; then
375 return $rc
376 fi
377
378 monitor_cmd_exec
379 }
380
381 docker_create_mounts() {
382 oldIFS="$IFS"
383 IFS=","
384 for directory in $OCF_RESKEY_mount_points; do
385 mkdir -p "$directory"
386 done
387 IFS="$oldIFS"
388 }
389
390 docker_start()
391 {
392 docker_create_mounts
393 local run_opts="-d --name=${CONTAINER}"
394 # check to see if the container has already started
395 docker_simple_status
396 if [ $? -eq $OCF_SUCCESS ]; then
397 return $OCF_SUCCESS
398 fi
399
400 if [ -n "$OCF_RESKEY_run_opts" ]; then
401 run_opts="$run_opts $OCF_RESKEY_run_opts"
402 fi
403
404 if [ $REQUIRE_IMAGE_PULL -eq 1 ]; then
405 ocf_log notice "Beginning pull of image, ${OCF_RESKEY_image}"
406 docker pull "${OCF_RESKEY_image}"
407 if [ $? -ne 0 ]; then
408 ocf_exit_reason "failed to pull image ${OCF_RESKEY_image}"
409 return $OCF_ERR_GENERIC
410 fi
411 fi
412
413 if ocf_is_true "$OCF_RESKEY_reuse" && container_exists; then
414 ocf_log info "starting existing container $CONTAINER."
415 ocf_run docker start $CONTAINER
416 else
417 # make sure any previous container matching our container name is cleaned up first.
418 # we already know at this point it wouldn't be running
419 remove_container
420 ocf_log info "running container $CONTAINER for the first time"
421 ocf_run docker run $run_opts $OCF_RESKEY_image $OCF_RESKEY_run_cmd
422 fi
423
424 if [ $? -ne 0 ]; then
425 ocf_exit_reason "docker failed to launch container"
426 return $OCF_ERR_GENERIC
427 fi
428
429
430 # wait for monitor to pass before declaring that the container is started
431 while true; do
432 docker_simple_status
433 if [ $? -ne $OCF_SUCCESS ]; then
434 ocf_exit_reason "Newly created docker container exited after start"
435 return $OCF_ERR_GENERIC
436 fi
437
438 monitor_cmd_exec
439 if [ $? -eq $OCF_SUCCESS ]; then
440 ocf_log notice "Container $CONTAINER started successfully"
441 return $OCF_SUCCESS
442 fi
443
444 ocf_exit_reason "waiting on monitor_cmd to pass after start"
445 sleep 1
446 done
447 }
448
449 docker_stop()
450 {
451 local timeout=60
452 docker_simple_status
453 ret=$?
454 if [ $ret -eq $OCF_NOT_RUNNING ]; then
455 remove_container
456 return $OCF_SUCCESS
457 elif [ $ret -eq $OCF_ERR_GENERIC ]; then
458 return $OCF_ERR_GENERIC
459 fi
460
461 if [ -n "$OCF_RESKEY_CRM_meta_timeout" ]; then
462 timeout=$((($OCF_RESKEY_CRM_meta_timeout/1000) -10 ))
463 if [ $timeout -lt 10 ]; then
464 timeout=10
465 fi
466 fi
467
468 if ocf_is_true "$OCF_RESKEY_force_kill"; then
469 ocf_run docker kill $CONTAINER
470 else
471 ocf_log debug "waiting $timeout second[s] before killing container"
472 ocf_run docker stop -t=$timeout $CONTAINER
473 fi
474
475 if [ $? -ne 0 ]; then
476 ocf_exit_reason "Failed to stop container, ${CONTAINER}, based on image, ${OCF_RESKEY_image}."
477 return $OCF_ERR_GENERIC
478 fi
479
480 remove_container
481 if [ $? -ne 0 ]; then
482 ocf_exit_reason "Failed to remove stopped container, ${CONTAINER}, based on image, ${OCF_RESKEY_image}."
483 return $OCF_ERR_GENERIC
484 fi
485
486 return $OCF_SUCCESS
487 }
488
489 image_exists()
490 {
491 # if no tag was specified, use default "latest"
492 local COLON_FOUND=0
493 local SLASH_FOUND=0
494 local SERVER_NAME=""
495 local IMAGE_NAME="${OCF_RESKEY_image}"
496 local IMAGE_TAG="latest"
497
498 # try to extract server name before tag, as it might also contain a colon (server:port/image:tag)
499 SLASH_FOUND="$(echo "${OCF_RESKEY_image}" | grep -o '/' | grep -c .)"
500 if [ ${SLASH_FOUND} -ge 1 ]; then
501 SERVER_NAME="$(echo ${IMAGE_NAME} | cut -d / -f 1-${SLASH_FOUND})"
502 IMAGE_NAME="$(echo ${IMAGE_NAME} | awk -F'/' '{print $NF}')"
503 fi
504
505 # extract image tag if specified
506 COLON_FOUND="$(echo "${IMAGE_NAME}" | grep -o ':' | grep -c .)"
507 if [ ${COLON_FOUND} -ge 1 ]; then
508 IMAGE_TAG="$(echo ${IMAGE_NAME} | awk -F':' '{print $NF}')"
509 IMAGE_NAME="$(echo ${IMAGE_NAME} | cut -d : -f 1-${COLON_FOUND})"
510 fi
511
512 # Check for existence of image, which might be in following formats:
513 # - image
514 # - server_name/image (as extracted above)
515 # - docker.io/image (some distro will display "docker.io/" as prefix)
516 docker image ls --all --format '{{.Repository}}:{{.Tag}}' | $EGREP -q -s "^(docker.io\/|${SERVER_NAME}\/)?${IMAGE_NAME}:${IMAGE_TAG}\$"
517 if [ $? -eq 0 ]; then
518 # image found
519 return $OCF_SUCCESS
520 fi
521
522 if ocf_is_true "$OCF_RESKEY_allow_pull"; then
523 REQUIRE_IMAGE_PULL=1
524 ocf_log notice "Image (${OCF_RESKEY_image}) does not exist locally but will be pulled during start"
525 return $OCF_SUCCESS
526 fi
527
528 # image not found.
529 return $OCF_ERR_ARGS
530 }
531
532 docker_validate()
533 {
534 check_binary docker
535 if [ -z "$OCF_RESKEY_image" ]; then
536 ocf_exit_reason "'image' option is required"
537 exit $OCF_ERR_CONFIGURED
538 fi
539
540 if [ -n "$OCF_RESKEY_monitor_cmd" ]; then
541 docker exec --help >/dev/null 2>&1
542 if [ ! $? ]; then
543 ocf_log info "checking for nsenter, which is required when 'monitor_cmd' is specified"
544 check_binary nsenter
545 fi
546 fi
547
548 image_exists
549 if [ $? -ne 0 ]; then
550 ocf_exit_reason "base image, ${OCF_RESKEY_image}, could not be found."
551 exit $OCF_ERR_CONFIGURED
552 fi
553
554 return $OCF_SUCCESS
555 }
556
557 # TODO :
558 # When a user starts plural clones in a node in globally-unique, a user cannot appoint plural name parameters.
559 # When a user appoints reuse, the resource agent cannot connect plural clones with a container.
560
561 if ocf_is_true "$OCF_RESKEY_CRM_meta_globally_unique"; then
562 if [ -n "$OCF_RESKEY_name" ]; then
563 if [ -n "$OCF_RESKEY_CRM_meta_clone_node_max" ] && [ "$OCF_RESKEY_CRM_meta_clone_node_max" -ne 1 ]
564 then
565 ocf_exit_reason "Cannot make plural clones from the same name parameter."
566 exit $OCF_ERR_CONFIGURED
567 fi
568 if [ -n "$OCF_RESKEY_CRM_meta_master_node_max" ] && [ "$OCF_RESKEY_CRM_meta_master_node_max" -ne 1 ]
569 then
570 ocf_exit_reason "Cannot make plural master from the same name parameter."
571 exit $OCF_ERR_CONFIGURED
572 fi
573 fi
574 : ${OCF_RESKEY_name=`echo ${OCF_RESOURCE_INSTANCE} | tr ':' '-'`}
575 else
576 : ${OCF_RESKEY_name=${OCF_RESOURCE_INSTANCE}}
577 fi
578
579 if [ -n "$OCF_RESKEY_container" ]; then
580 # we'll keep the container attribute around for a bit in order not to break
581 # any existing deployments. The 'name' attribute is prefered now though.
582 CONTAINER=$OCF_RESKEY_container
583 ocf_log warn "The 'container' attribute is depreciated"
584 else
585 CONTAINER=$OCF_RESKEY_name
586 fi
587
588 case $__OCF_ACTION in
589 meta-data) meta_data
590 exit $OCF_SUCCESS;;
591 start)
592 docker_validate
593 docker_start;;
594 stop) docker_stop;;
595 monitor) docker_monitor;;
596 validate-all) docker_validate;;
597 usage|help) docker_usage
598 exit $OCF_SUCCESS
599 ;;
600 *) docker_usage
601 exit $OCF_ERR_UNIMPLEMENTED
602 ;;
603 esac
604 rc=$?
605 ocf_log debug "${OCF_RESOURCE_INSTANCE} $__OCF_ACTION : $rc"
606 exit $rc
607