Debian Codegraph @

ansible_collections/community/general/plugins/modules/lxc_container.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Kevin Carter <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: lxc_container
11 short_description: Manage LXC Containers
12 description:
13 - Management of LXC containers.
14 author: "Kevin Carter (@cloudnull)"
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 name:
24 description:
25 - Name of a container.
26 type: str
27 required: true
28 backing_store:
29 choices:
30 - dir
31 - lvm
32 - loop
33 - btrfs
34 - overlayfs
35 - zfs
36 description:
37 - Backend storage type for the container.
38 type: str
39 default: dir
40 template:
41 description:
42 - Name of the template to use within an LXC create.
43 type: str
44 default: ubuntu
45 template_options:
46 description:
47 - Template options when building the container.
48 type: str
49 config:
50 description:
51 - Path to the LXC configuration file.
52 type: path
53 lv_name:
54 description:
55 - Name of the logical volume, defaults to the container name.
56 - If not specified, it defaults to E(CONTAINER_NAME).
57 type: str
58 vg_name:
59 description:
60 - If backend store is lvm, specify the name of the volume group.
61 type: str
62 default: lxc
63 thinpool:
64 description:
65 - Use LVM thin pool called TP.
66 type: str
67 fs_type:
68 description:
69 - Create fstype TYPE.
70 type: str
71 default: ext4
72 fs_size:
73 description:
74 - File system Size.
75 type: str
76 default: 5G
77 directory:
78 description:
79 - Place rootfs directory under DIR.
80 type: path
81 zfs_root:
82 description:
83 - Create zfs under given zfsroot.
84 type: str
85 container_command:
86 description:
87 - Run a command within a container.
88 - The O(container_command) can be used with any state except V(absent). If used with state V(stopped) the container
89 is V(started), the command executed, and then the container V(stopped) again. Likewise if O(state=stopped) and the
90 container does not exist it is first created, V(started), the command executed, and then V(stopped). If you use a
91 C(|) in the variable you can use common script formatting within the variable itself. The O(container_command) option
92 always execute as C(bash). When using O(container_command), a log file is created in the C(/tmp/) directory which
93 contains both RV(ignore:stdout) and RV(ignore:stderr) of any command executed.
94 type: str
95 lxc_path:
96 description:
97 - Place container under E(PATH).
98 type: path
99 container_log:
100 description:
101 - Enable a container log for host actions to the container.
102 type: bool
103 default: false
104 container_log_level:
105 choices:
106 - Info
107 - info
108 - INFO
109 - Error
110 - error
111 - ERROR
112 - Debug
113 - debug
114 - DEBUG
115 description:
116 - Set the log level for a container where O(container_log) was set.
117 type: str
118 default: INFO
119 clone_name:
120 description:
121 - Name of the new cloned server.
122 - This is only used when state is clone.
123 type: str
124 clone_snapshot:
125 description:
126 - Create a snapshot a container when cloning.
127 - This is not supported by all container storage backends.
128 - Enabling this may fail if the backing store does not support snapshots.
129 type: bool
130 default: false
131 archive:
132 description:
133 - When set to V(true) the system attempts to create a compressed tarball of the running container. The O(archive) option
134 supports LVM backed containers and creates a snapshot of the running container when creating the archive.
135 type: bool
136 default: false
137 archive_path:
138 description:
139 - Path the save the archived container.
140 - If the path does not exist the archive method attempts to create it.
141 type: path
142 archive_compression:
143 choices:
144 - gzip
145 - bzip2
146 - none
147 description:
148 - Type of compression to use when creating an archive of a running container.
149 type: str
150 default: gzip
151 state:
152 choices:
153 - started
154 - stopped
155 - restarted
156 - absent
157 - frozen
158 - clone
159 description:
160 - Define the state of a container.
161 - If you clone a container using O(clone_name) the newly cloned container created in a stopped state.
162 - The running container is stopped while the clone operation is happening and upon completion of the clone the original
163 container state is restored.
164 type: str
165 default: started
166 container_config:
167 description:
168 - A list of C(key=value) options to use when configuring a container.
169 type: list
170 elements: str
171 requirements:
172 - 'lxc >= 2.0 # OS package'
173 - 'python3 >= 3.5 # OS Package'
174 - 'python3-lxc # OS Package'
175 notes:
176 - Containers must have a unique name. If you attempt to create a container with a name that already exists in the users
177 namespace the module simply returns as "unchanged".
178 - If your distro does not have a package for C(python3-lxc), which is a requirement for this module, it can be installed
179 from source at U(https://github.com/lxc/python3-lxc) or installed using C(pip install lxc).
180 """
181
182 EXAMPLES = r"""
183 - name: Create a started container
184 community.general.lxc_container:
185 name: test-container-started
186 container_log: true
187 template: ubuntu
188 state: started
189 template_options: --release trusty
190
191 - name: Create a stopped container
192 community.general.lxc_container:
193 name: test-container-stopped
194 container_log: true
195 template: ubuntu
196 state: stopped
197 template_options: --release trusty
198
199 - name: Create a frozen container
200 community.general.lxc_container:
201 name: test-container-frozen
202 container_log: true
203 template: ubuntu
204 state: frozen
205 template_options: --release trusty
206 container_command: |
207 echo 'hello world.' | tee /opt/started-frozen
208
209 # Create filesystem container, configure it, and archive it, and start it.
210 - name: Create filesystem container
211 community.general.lxc_container:
212 name: test-container-config
213 backing_store: dir
214 container_log: true
215 template: ubuntu
216 state: started
217 archive: true
218 archive_compression: none
219 container_config:
220 - "lxc.aa_profile=unconfined"
221 - "lxc.cgroup.devices.allow=a *:* rmw"
222 template_options: --release trusty
223
224 # Create an lvm container, run a complex command in it, add additional
225 # configuration to it, create an archive of it, and finally leave the container
226 # in a frozen state. The container archive will be compressed using bzip2
227 - name: Create a frozen lvm container
228 community.general.lxc_container:
229 name: test-container-lvm
230 container_log: true
231 template: ubuntu
232 state: frozen
233 backing_store: lvm
234 template_options: --release trusty
235 container_command: |
236 apt-get update
237 apt-get install -y vim lxc-dev
238 echo 'hello world.' | tee /opt/started
239 if [[ -f "/opt/started" ]]; then
240 echo 'hello world.' | tee /opt/found-started
241 fi
242 container_config:
243 - "lxc.aa_profile=unconfined"
244 - "lxc.cgroup.devices.allow=a *:* rmw"
245 archive: true
246 archive_compression: bzip2
247 register: lvm_container_info
248
249 - name: Debug info on container "test-container-lvm"
250 ansible.builtin.debug:
251 var: lvm_container_info
252
253 - name: Run a command in a container and ensure it is in a "stopped" state.
254 community.general.lxc_container:
255 name: test-container-started
256 state: stopped
257 container_command: |
258 echo 'hello world.' | tee /opt/stopped
259
260 - name: Run a command in a container and ensure it is in a "frozen" state.
261 community.general.lxc_container:
262 name: test-container-stopped
263 state: frozen
264 container_command: |
265 echo 'hello world.' | tee /opt/frozen
266
267 - name: Start a container
268 community.general.lxc_container:
269 name: test-container-stopped
270 state: started
271
272 - name: Run a command in a container and then restart it
273 community.general.lxc_container:
274 name: test-container-started
275 state: restarted
276 container_command: |
277 echo 'hello world.' | tee /opt/restarted
278
279 - name: Run a complex command within a "running" container
280 community.general.lxc_container:
281 name: test-container-started
282 container_command: |
283 apt-get update
284 apt-get install -y curl wget vim apache2
285 echo 'hello world.' | tee /opt/started
286 if [[ -f "/opt/started" ]]; then
287 echo 'hello world.' | tee /opt/found-started
288 fi
289
290 # Create an archive of an existing container, save the archive to a defined
291 # path and then destroy it.
292 - name: Archive container
293 community.general.lxc_container:
294 name: test-container-started
295 state: absent
296 archive: true
297 archive_path: /opt/archives
298
299 # Create a container using overlayfs, create an archive of it, create a
300 # snapshot clone of the container and and finally leave the container
301 # in a frozen state. The container archive will be compressed using gzip.
302 - name: Create an overlayfs container archive and clone it
303 community.general.lxc_container:
304 name: test-container-overlayfs
305 container_log: true
306 template: ubuntu
307 state: started
308 backing_store: overlayfs
309 template_options: --release trusty
310 clone_snapshot: true
311 clone_name: test-container-overlayfs-clone-snapshot
312 archive: true
313 archive_compression: gzip
314 register: clone_container_info
315
316 - name: Debug info on container "test-container"
317 ansible.builtin.debug:
318 var: clone_container_info
319
320 - name: Clone a container using snapshot
321 community.general.lxc_container:
322 name: test-container-overlayfs-clone-snapshot
323 backing_store: overlayfs
324 clone_name: test-container-overlayfs-clone-snapshot2
325 clone_snapshot: true
326
327 - name: Create a new container and clone it
328 community.general.lxc_container:
329 name: test-container-new-archive
330 backing_store: dir
331 clone_name: test-container-new-archive-clone
332
333 - name: Archive and clone a container then destroy it
334 community.general.lxc_container:
335 name: test-container-new-archive
336 state: absent
337 clone_name: test-container-new-archive-destroyed-clone
338 archive: true
339 archive_compression: gzip
340
341 - name: Start a cloned container.
342 community.general.lxc_container:
343 name: test-container-new-archive-destroyed-clone
344 state: started
345
346 - name: Destroy a container
347 community.general.lxc_container:
348 name: '{{ item }}'
349 state: absent
350 with_items:
351 - test-container-stopped
352 - test-container-started
353 - test-container-frozen
354 - test-container-lvm
355 - test-container-config
356 - test-container-overlayfs
357 - test-container-overlayfs-clone
358 - test-container-overlayfs-clone-snapshot
359 - test-container-overlayfs-clone-snapshot2
360 - test-container-new-archive
361 - test-container-new-archive-clone
362 - test-container-new-archive-destroyed-clone
363 """
364
365 RETURN = r"""
366 lxc_container:
367 description: Container information.
368 returned: success
369 type: complex
370 contains:
371 name:
372 description: Name of the LXC container.
373 returned: success
374 type: str
375 sample: test_host
376 init_pid:
377 description: Pid of the LXC init process.
378 returned: success
379 type: int
380 sample: 19786
381 interfaces:
382 description: List of the container's network interfaces.
383 returned: success
384 type: list
385 sample: ["eth0", "lo"]
386 ips:
387 description: List of IPs.
388 returned: success
389 type: list
390 sample: ["10.0.3.3"]
391 state:
392 description: Resulting state of the container.
393 returned: success
394 type: str
395 sample: "running"
396 archive:
397 description: Resulting state of the container.
398 returned: success, when archive is true
399 type: str
400 sample: "/tmp/test-container-config.tar"
401 clone:
402 description: If the container was cloned.
403 returned: success, when clone_name is specified
404 type: bool
405 sample: true
406 """
407
408 import os
409 import re
410 import shlex
411 import tempfile
412 import time
413
414 try:
415 import lxc
416 except ImportError:
417 HAS_LXC = False
418 else:
419 HAS_LXC = True
420
421 from ansible.module_utils.basic import AnsibleModule
422 from ansible.module_utils.common.text.converters import to_bytes, to_text
423 from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE
424
425 from ansible_collections.community.general.plugins.module_utils._lvm import (
426 lvcreate_runner,
427 lvremove_runner,
428 lvs_runner,
429 vgs_runner,
430 )
431 from ansible_collections.community.general.plugins.module_utils._lxc import create_script
432
433 # LXC_COMPRESSION_MAP is a map of available compression types when creating
434 # an archive of a container.
435 LXC_COMPRESSION_MAP = {
436 "gzip": {"extension": "tar.tgz", "argument": "-czf"},
437 "bzip2": {"extension": "tar.bz2", "argument": "-cjf"},
438 "none": {"extension": "tar", "argument": "-cf"},
439 }
440
441
442 # LXC_COMMAND_MAP is a map of variables that are available to a method based
443 # on the state the container is in.
444 LXC_COMMAND_MAP = {
445 "create": {
446 "variables": {
447 "config": "--config",
448 "template": "--template",
449 "backing_store": "--bdev",
450 "lxc_path": "--lxcpath",
451 "lv_name": "--lvname",
452 "vg_name": "--vgname",
453 "thinpool": "--thinpool",
454 "fs_type": "--fstype",
455 "fs_size": "--fssize",
456 "directory": "--dir",
457 "zfs_root": "--zfsroot",
458 }
459 },
460 "clone": {
461 "variables-lxc-copy": {
462 "backing_store": "--backingstorage",
463 "lxc_path": "--lxcpath",
464 "fs_size": "--fssize",
465 "name": "--name",
466 "clone_name": "--newname",
467 },
468 # lxc-clone is deprecated in favor of lxc-copy
469 "variables-lxc-clone": {
470 "backing_store": "--backingstore",
471 "lxc_path": "--lxcpath",
472 "fs_size": "--fssize",
473 "name": "--orig",
474 "clone_name": "--new",
475 },
476 },
477 }
478
479
480 # LXC_BACKING_STORE is a map of available storage backends and options that
481 # are incompatible with the given storage backend.
482 LXC_BACKING_STORE = {
483 "dir": ["lv_name", "vg_name", "fs_type", "fs_size", "thinpool"],
484 "lvm": ["zfs_root"],
485 "btrfs": ["lv_name", "vg_name", "thinpool", "zfs_root", "fs_type", "fs_size"],
486 "loop": ["lv_name", "vg_name", "thinpool", "zfs_root"],
487 "overlayfs": ["lv_name", "vg_name", "fs_type", "fs_size", "thinpool", "zfs_root"],
488 "zfs": ["lv_name", "vg_name", "fs_type", "fs_size", "thinpool"],
489 }
490
491
492 # LXC_LOGGING_LEVELS is a map of available log levels
493 LXC_LOGGING_LEVELS = {
494 "INFO": ["info", "INFO", "Info"],
495 "ERROR": ["error", "ERROR", "Error"],
496 "DEBUG": ["debug", "DEBUG", "Debug"],
497 }
498
499
500 # LXC_ANSIBLE_STATES is a map of states that contain values of methods used
501 # when a particular state is evoked.
502 LXC_ANSIBLE_STATES = {
503 "started": "_started",
504 "stopped": "_stopped",
505 "restarted": "_restarted",
506 "absent": "_destroyed",
507 "frozen": "_frozen",
508 "clone": "_clone",
509 }
510
511
512 class LxcContainerManagement:
513 def __init__(self, module):
514 """Management of LXC containers via Ansible.
515
516 :param module: Processed Ansible Module.
517 :type module: ``object``
518 """
519 self.module = module
520 self.state = self.module.params["state"]
521 self.state_change = False
522 self.lxc_vg = None
523 self.lxc_path = self.module.params["lxc_path"]
524 self.container_name = self.module.params["name"]
525 self.container = self.get_container_bind()
526 self.archive_info = None
527 self.clone_info = None
528 self.run_info = []
529
530 def get_container_bind(self):
531 return lxc.Container(name=self.container_name)
532
533 @staticmethod
534 def _roundup(num):
535 """Return a rounded floating point number.
536
537 :param num: Number to round up.
538 :type: ``float``
539 :returns: Rounded up number.
540 :rtype: ``int``
541 """
542 num, part = str(num).split(".")
543 num = int(num)
544 if int(part) != 0:
545 num += 1
546 return num
547
548 @staticmethod
549 def _container_exists(container_name, lxc_path=None):
550 """Check if a container exists.
551
552 :param container_name: Name of the container.
553 :type: ``str``
554 :returns: True or False if the container is found.
555 :rtype: ``bol``
556 """
557 return any(c == container_name for c in lxc.list_containers(config_path=lxc_path))
558
559 @staticmethod
560 def _add_variables(variables_dict, build_command):
561 """Return a command list with all found options.
562
563 :param variables_dict: Pre-parsed optional variables used from a
564 seed command.
565 :type variables_dict: ``dict``
566 :param build_command: Command to run.
567 :type build_command: ``list``
568 :returns: list of command options.
569 :rtype: ``list``
570 """
571
572 for key, value in variables_dict.items():
573 build_command.append(str(key))
574 build_command.append(str(value))
575 return build_command
576
577 def _get_vars(self, variables):
578 """Return a dict of all variables as found within the module.
579
580 :param variables: Hash of all variables to find.
581 :type variables: ``dict``
582 """
583
584 # Remove incompatible storage backend options.
585 variables = variables.copy()
586 for v in LXC_BACKING_STORE[self.module.params["backing_store"]]:
587 variables.pop(v, None)
588
589 false_values = BOOLEANS_FALSE.union([None, ""])
590 result = {v: self.module.params[k] for k, v in variables.items() if self.module.params[k] not in false_values}
591 return result
592
593 def _config(self):
594 """Configure an LXC container.
595
596 Write new configuration values to the lxc config file. This will
597 stop the container if it is running write the new options and then
598 restart the container upon completion.
599 """
600
601 _container_config = self.module.params["container_config"]
602 if not _container_config:
603 return False
604
605 container_config_file = self.container.config_file_name
606 with open(container_config_file, "rb") as f:
607 container_config = to_text(f.read(), errors="surrogate_or_strict").splitlines(True)
608
609 parsed_options = [i.split("=", 1) for i in _container_config]
610 config_change = False
611 for key, value in parsed_options:
612 key = key.strip()
613 value = value.strip()
614 new_entry = f"{key} = {value}\n"
615 keyre = re.compile(rf"{key}(\s+)?=")
616 for option_line in container_config:
617 # Look for key in config
618 if keyre.match(option_line):
619 dummy, _value = option_line.split("=", 1)
620 config_value = " ".join(_value.split())
621 line_index = container_config.index(option_line)
622 # If the sanitized values don't match replace them
623 if value != config_value:
624 line_index += 1
625 if new_entry not in container_config:
626 config_change = True
627 container_config.insert(line_index, new_entry)
628 # Break the flow as values are written or not at this point
629 break
630 else:
631 config_change = True
632 container_config.append(new_entry)
633
634 # If the config changed restart the container.
635 if config_change:
636 container_state = self._get_state()
637 if container_state != "stopped":
638 self.container.stop()
639
640 with open(container_config_file, "wb") as f:
641 f.writelines([to_bytes(line, errors="surrogate_or_strict") for line in container_config])
642
643 self.state_change = True
644 if container_state == "running":
645 self._container_startup()
646 elif container_state == "frozen":
647 self._container_startup()
648 self.container.freeze()
649
650 def _container_create_clone(self):
651 """Clone a new LXC container from an existing container.
652
653 This method will clone an existing container to a new container using
654 the `clone_name` variable as the new container name. The method will
655 create a container if the container `name` does not exist.
656
657 Note that cloning a container will ensure that the original container
658 is "stopped" before the clone can be done. Because this operation can
659 require a state change the method will return the original container
660 to its prior state upon completion of the clone.
661
662 Once the clone is complete the new container will be left in a stopped
663 state.
664 """
665
666 # Ensure that the state of the original container is stopped
667 container_state = self._get_state()
668 if container_state != "stopped":
669 self.state_change = True
670 self.container.stop()
671
672 # lxc-clone is deprecated in favor of lxc-copy
673 clone_vars = "variables-lxc-copy"
674 clone_cmd = self.module.get_bin_path("lxc-copy")
675 if not clone_cmd:
676 clone_vars = "variables-lxc-clone"
677 clone_cmd = self.module.get_bin_path("lxc-clone", True)
678
679 build_command = [
680 clone_cmd,
681 ]
682
683 build_command = self._add_variables(
684 variables_dict=self._get_vars(variables=LXC_COMMAND_MAP["clone"][clone_vars]), build_command=build_command
685 )
686
687 # Load logging for the instance when creating it.
688 if self.module.params["clone_snapshot"]:
689 build_command.append("--snapshot")
690 # Check for backing_store == overlayfs if so force the use of snapshot
691 # If overlay fs is used and snapshot is unset the clone command will
692 # fail with an unsupported type.
693 elif self.module.params["backing_store"] == "overlayfs":
694 build_command.append("--snapshot")
695
696 rc, return_data, err = self.module.run_command(build_command)
697 if rc != 0:
698 message = f"Failed executing {os.path.basename(clone_cmd)}."
699 self.failure(err=err, rc=rc, msg=message, command=" ".join(build_command))
700 else:
701 self.state_change = True
702 # Restore the original state of the origin container if it was
703 # not in a stopped state.
704 if container_state == "running":
705 self.container.start()
706 elif container_state == "frozen":
707 self.container.start()
708 self.container.freeze()
709
710 return True
711
712 def _create(self):
713 """Create a new LXC container.
714
715 This method will build and execute a shell command to build the
716 container. It would have been nice to simply use the lxc python library
717 however at the time this was written the python library, in both py2
718 and py3 didn't support some of the more advanced container create
719 processes. These missing processes mainly revolve around backing
720 LXC containers with block devices.
721 """
722
723 build_command = [self.module.get_bin_path("lxc-create", True), "--name", self.container_name, "--quiet"]
724
725 build_command = self._add_variables(
726 variables_dict=self._get_vars(variables=LXC_COMMAND_MAP["create"]["variables"]), build_command=build_command
727 )
728
729 # Load logging for the instance when creating it.
730 if self.module.params["container_log"]:
731 # Set the logging path to the /var/log/lxc if uid is root. else
732 # set it to the home folder of the user executing.
733 try:
734 if os.getuid() != 0:
735 log_path = os.getenv("HOME")
736 else:
737 if not os.path.isdir("/var/log/lxc/"):
738 os.makedirs("/var/log/lxc/")
739 log_path = "/var/log/lxc/"
740 except OSError:
741 log_path = os.getenv("HOME")
742
743 build_command.extend(
744 [
745 "--logfile",
746 os.path.join(log_path, f"lxc-{self.container_name}.log"),
747 "--logpriority",
748 self.module.params.get("container_log_level").upper(),
749 ]
750 )
751
752 # Add the template commands to the end of the command if there are any
753 template_options = self.module.params["template_options"]
754 if template_options:
755 build_command.append("--")
756 build_command += shlex.split(template_options)
757
758 rc, return_data, err = self.module.run_command(build_command)
759 if rc != 0:
760 message = "Failed executing lxc-create."
761 self.failure(err=err, rc=rc, msg=message, command=" ".join(build_command))
762 else:
763 self.state_change = True
764
765 def _container_data(self):
766 """Returns a dict of container information.
767
768 :returns: container data
769 :rtype: ``dict``
770 """
771
772 return {
773 "interfaces": self.container.get_interfaces(),
774 "ips": self.container.get_ips(),
775 "state": self._get_state(),
776 "init_pid": int(self.container.init_pid),
777 "name": self.container_name,
778 }
779
780 def _unfreeze(self):
781 """Unfreeze a container.
782
783 :returns: True or False based on if the container was unfrozen.
784 :rtype: ``bol``
785 """
786
787 unfreeze = self.container.unfreeze()
788 if unfreeze:
789 self.state_change = True
790 return unfreeze
791
792 def _get_state(self):
793 """Return the state of a container.
794
795 If the container is not found the state returned is "absent"
796
797 :returns: state of a container as a lower case string.
798 :rtype: ``str``
799 """
800
801 if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
802 return str(self.container.state).lower()
803 return "absent"
804
805 def _execute_command(self):
806 """Execute a shell command."""
807
808 container_command = self.module.params["container_command"]
809 if container_command:
810 container_state = self._get_state()
811 if container_state == "frozen":
812 self._unfreeze()
813 elif container_state == "stopped":
814 self._container_startup()
815
816 self.container.attach_wait(create_script, (container_command, self.module))
817 self.state_change = True
818
819 def _container_startup(self, timeout=60):
820 """Ensure a container is started.
821
822 :param timeout: Time before the destroy operation is abandoned.
823 :type timeout: ``int``
824 """
825
826 self.container = self.get_container_bind()
827 for dummy in range(timeout):
828 if self._get_state() == "running":
829 return True
830
831 self.container.start()
832 self.state_change = True
833 # post startup sleep for 1 second.
834 time.sleep(1)
835 self.failure(
836 lxc_container=self._container_data(),
837 error=f"Failed to start container [ {self.container_name} ]",
838 rc=1,
839 msg=f"The container [ {self.container_name} ] failed to start. Check to lxc is available and that the container is in a functional state.",
840 )
841
842 def _check_archive(self):
843 """Create a compressed archive of a container.
844
845 This will store archive_info in as self.archive_info
846 """
847
848 if self.module.params["archive"]:
849 self.archive_info = {"archive": self._container_create_tar()}
850
851 def _check_clone(self):
852 """Create a compressed archive of a container.
853
854 This will store archive_info in as self.archive_info
855 """
856
857 clone_name = self.module.params["clone_name"]
858 if clone_name:
859 if not self._container_exists(container_name=clone_name, lxc_path=self.lxc_path):
860 self.clone_info = {"cloned": self._container_create_clone()}
861 else:
862 self.clone_info = {"cloned": False}
863
864 def _destroyed(self, timeout=60):
865 """Ensure a container is destroyed.
866
867 :param timeout: Time before the destroy operation is abandoned.
868 :type timeout: ``int``
869 """
870
871 for dummy in range(timeout):
872 if not self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
873 break
874
875 # Check if the container needs to have an archive created.
876 self._check_archive()
877
878 # Check if the container is to be cloned
879 self._check_clone()
880
881 if self._get_state() != "stopped":
882 self.state_change = True
883 self.container.stop()
884
885 if self.container.destroy():
886 self.state_change = True
887
888 # post destroy attempt sleep for 1 second.
889 time.sleep(1)
890 else:
891 self.failure(
892 lxc_container=self._container_data(),
893 error=f"Failed to destroy container [ {self.container_name} ]",
894 rc=1,
895 msg=(
896 f"The container [ {self.container_name} ] failed to be destroyed. "
897 "Check that lxc is available and that the container is in a functional state."
898 ),
899 )
900
901 def _frozen(self, count=0):
902 """Ensure a container is frozen.
903
904 If the container does not exist the container will be created.
905
906 :param count: number of times this command has been called by itself.
907 :type count: ``int``
908 """
909
910 self.check_count(count=count, method="frozen")
911 if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
912 self._execute_command()
913
914 # Perform any configuration updates
915 self._config()
916
917 container_state = self._get_state()
918 if container_state == "frozen":
919 pass
920 elif container_state == "running":
921 self.container.freeze()
922 self.state_change = True
923 else:
924 self._container_startup()
925 self.container.freeze()
926 self.state_change = True
927
928 # Check if the container needs to have an archive created.
929 self._check_archive()
930
931 # Check if the container is to be cloned
932 self._check_clone()
933 else:
934 self._create()
935 count += 1
936 self._frozen(count)
937
938 def _restarted(self, count=0):
939 """Ensure a container is restarted.
940
941 If the container does not exist the container will be created.
942
943 :param count: number of times this command has been called by itself.
944 :type count: ``int``
945 """
946
947 self.check_count(count=count, method="restart")
948 if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
949 self._execute_command()
950
951 # Perform any configuration updates
952 self._config()
953
954 if self._get_state() != "stopped":
955 self.container.stop()
956 self.state_change = True
957
958 # Run container startup
959 self._container_startup()
960
961 # Check if the container needs to have an archive created.
962 self._check_archive()
963
964 # Check if the container is to be cloned
965 self._check_clone()
966 else:
967 self._create()
968 count += 1
969 self._restarted(count)
970
971 def _stopped(self, count=0):
972 """Ensure a container is stopped.
973
974 If the container does not exist the container will be created.
975
976 :param count: number of times this command has been called by itself.
977 :type count: ``int``
978 """
979
980 self.check_count(count=count, method="stop")
981 if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
982 self._execute_command()
983
984 # Perform any configuration updates
985 self._config()
986
987 if self._get_state() != "stopped":
988 self.container.stop()
989 self.state_change = True
990
991 # Check if the container needs to have an archive created.
992 self._check_archive()
993
994 # Check if the container is to be cloned
995 self._check_clone()
996 else:
997 self._create()
998 count += 1
999 self._stopped(count)
1000
1001 def _started(self, count=0):
1002 """Ensure a container is started.
1003
1004 If the container does not exist the container will be created.
1005
1006 :param count: number of times this command has been called by itself.
1007 :type count: ``int``
1008 """
1009
1010 self.check_count(count=count, method="start")
1011 if self._container_exists(container_name=self.container_name, lxc_path=self.lxc_path):
1012 container_state = self._get_state()
1013 if container_state == "running":
1014 pass
1015 elif container_state == "frozen":
1016 self._unfreeze()
1017 elif not self._container_startup():
1018 self.failure(
1019 lxc_container=self._container_data(),
1020 error=f"Failed to start container [ {self.container_name} ]",
1021 rc=1,
1022 msg=f"The container [ {self.container_name} ] failed to start. Check to lxc is available and that the container is in a functional state.",
1023 )
1024
1025 # Return data
1026 self._execute_command()
1027
1028 # Perform any configuration updates
1029 self._config()
1030
1031 # Check if the container needs to have an archive created.
1032 self._check_archive()
1033
1034 # Check if the container is to be cloned
1035 self._check_clone()
1036 else:
1037 self._create()
1038 count += 1
1039 self._started(count)
1040
1041 def _get_lxc_vg(self):
1042 """Return the name of the Volume Group used in LXC."""
1043
1044 build_command = [self.module.get_bin_path("lxc-config", True), "lxc.bdev.lvm.vg"]
1045 rc, vg, err = self.module.run_command(build_command)
1046 if rc != 0:
1047 self.failure(err=err, rc=rc, msg="Failed to read LVM VG from LXC config", command=" ".join(build_command))
1048 else:
1049 return str(vg.strip())
1050
1051 def _lvm_lv_list(self):
1052 """Return a list of all lv in a current vg."""
1053
1054 vg = self._get_lxc_vg()
1055 with lvs_runner(self.module)("noheadings separator fields vg") as ctx:
1056 rc, stdout, err = ctx.run(separator=";", fields="lv_name", vg=[vg])
1057 if self.module._verbosity >= 4:
1058 self.run_info.append(ctx.run_info)
1059 if rc != 0:
1060 self.failure(err=err, rc=rc, msg="Failed to get list of LVs")
1061 return [line.strip() for line in stdout.splitlines() if line.strip()]
1062
1063 def _get_vg_free_pe(self, vg_name):
1064 """Return the available size of a given VG.
1065
1066 :param vg_name: Name of volume.
1067 :type vg_name: ``str``
1068 :returns: size and measurement of an LV
1069 :type: ``tuple``
1070 """
1071
1072 with vgs_runner(self.module)("noheadings nosuffix units separator fields vg") as ctx:
1073 rc, stdout, err = ctx.run(units="g", separator=";", fields="vg_free", vg=[vg_name])
1074 if self.module._verbosity >= 4:
1075 self.run_info.append(ctx.run_info)
1076 if rc != 0:
1077 self.failure(err=err, rc=rc, msg=f"failed to read vg {vg_name}")
1078 return float(stdout.strip()), "g"
1079
1080 def _get_lv_size(self, lv_name):
1081 """Return the available size of a given LV.
1082
1083 :param lv_name: Name of volume.
1084 :type lv_name: ``str``
1085 :returns: size and measurement of an LV
1086 :type: ``tuple``
1087 """
1088
1089 vg = self._get_lxc_vg()
1090 lv = os.path.join(vg, lv_name)
1091 with lvs_runner(self.module)("noheadings nosuffix units separator fields vg") as ctx:
1092 rc, stdout, err = ctx.run(units="g", separator=";", fields="lv_size", vg=[lv])
1093 if self.module._verbosity >= 4:
1094 self.run_info.append(ctx.run_info)
1095 if rc != 0:
1096 self.failure(err=err, rc=rc, msg=f"failed to read lv {lv}")
1097 return self._roundup(float(stdout.strip())), "g"
1098
1099 def _lvm_snapshot_create(self, source_lv, snapshot_name, snapshot_size_gb=5):
1100 """Create an LVM snapshot.
1101
1102 :param source_lv: Name of lv to snapshot
1103 :type source_lv: ``str``
1104 :param snapshot_name: Name of lv snapshot
1105 :type snapshot_name: ``str``
1106 :param snapshot_size_gb: Size of snapshot to create
1107 :type snapshot_size_gb: ``int``
1108 """
1109
1110 vg = self._get_lxc_vg()
1111 free_space, measurement = self._get_vg_free_pe(vg_name=vg)
1112
1113 if free_space < float(snapshot_size_gb):
1114 message = (
1115 f"Snapshot size [ {snapshot_size_gb} ] is > greater than [ {free_space} ] on volume group [ {vg} ]"
1116 )
1117 self.failure(error="Not enough space to create snapshot", rc=2, msg=message)
1118
1119 with lvcreate_runner(self.module)("size_L is_snapshot lv vg") as ctx:
1120 rc, dummy, err = ctx.run(
1121 size_L=f"{snapshot_size_gb}g",
1122 is_snapshot=True,
1123 lv=[snapshot_name],
1124 vg=[os.path.join(vg, source_lv)],
1125 )
1126 if self.module._verbosity >= 4:
1127 self.run_info.append(ctx.run_info)
1128 if rc != 0:
1129 self.failure(err=err, rc=rc, msg=f"Failed to Create LVM snapshot {vg}/{source_lv} --> {snapshot_name}")
1130
1131 def _lvm_lv_mount(self, lv_name, mount_point):
1132 """mount an lv.
1133
1134 :param lv_name: name of the logical volume to mount
1135 :type lv_name: ``str``
1136 :param mount_point: path on the file system that is mounted.
1137 :type mount_point: ``str``
1138 """
1139
1140 vg = self._get_lxc_vg()
1141
1142 build_command = [
1143 self.module.get_bin_path("mount", True),
1144 f"/dev/{vg}/{lv_name}",
1145 mount_point,
1146 ]
1147 rc, stdout, err = self.module.run_command(build_command)
1148 if rc != 0:
1149 self.failure(err=err, rc=rc, msg=f"failed to mountlvm lv {vg}/{lv_name} to {mount_point}")
1150
1151 def _create_tar(self, source_dir):
1152 """Create an archive of a given ``source_dir`` to ``output_path``.
1153
1154 :param source_dir: Path to the directory to be archived.
1155 :type source_dir: ``str``
1156 """
1157
1158 old_umask = os.umask(int("0077", 8))
1159
1160 archive_path = self.module.params["archive_path"]
1161 if not os.path.isdir(archive_path):
1162 os.makedirs(archive_path)
1163
1164 archive_compression = self.module.params["archive_compression"]
1165 compression_type = LXC_COMPRESSION_MAP[archive_compression]
1166
1167 # remove trailing / if present.
1168 archive_name = f"{os.path.join(archive_path, self.container_name)}.{compression_type['extension']}"
1169
1170 build_command = [
1171 self.module.get_bin_path("tar", True),
1172 f"--directory={os.path.realpath(source_dir)}",
1173 compression_type["argument"],
1174 archive_name,
1175 ".",
1176 ]
1177
1178 rc, stdout, err = self.module.run_command(build_command)
1179
1180 os.umask(old_umask)
1181
1182 if rc != 0:
1183 self.failure(err=err, rc=rc, msg="failed to create tar archive", command=" ".join(build_command))
1184
1185 return archive_name
1186
1187 def _lvm_lv_remove(self, lv_name):
1188 """Remove an LV.
1189
1190 :param lv_name: The name of the logical volume
1191 :type lv_name: ``str``
1192 """
1193
1194 vg = self._get_lxc_vg()
1195 with lvremove_runner(self.module)("force lv") as ctx:
1196 rc, dummy, err = ctx.run(force=True, lv=[f"{vg}/{lv_name}"])
1197 if self.module._verbosity >= 4:
1198 self.run_info.append(ctx.run_info)
1199 if rc != 0:
1200 self.failure(err=err, rc=rc, msg=f"Failed to remove LVM LV {vg}/{lv_name}")
1201
1202 def _rsync_data(self, container_path, temp_dir):
1203 """Sync the container directory to the temp directory.
1204
1205 :param container_path: path to the container container
1206 :type container_path: ``str``
1207 :param temp_dir: path to the temporary local working directory
1208 :type temp_dir: ``str``
1209 """
1210 # This loop is created to support overlayfs archives. This should
1211 # squash all of the layers into a single archive.
1212 fs_paths = container_path.split(":")
1213 if "overlayfs" in fs_paths:
1214 fs_paths.pop(fs_paths.index("overlayfs"))
1215
1216 for fs_path in fs_paths:
1217 # Set the path to the container data
1218 fs_path = os.path.dirname(fs_path)
1219
1220 # Run the sync command
1221 build_command = [
1222 self.module.get_bin_path("rsync", True),
1223 "-aHAX",
1224 fs_path,
1225 temp_dir,
1226 ]
1227 rc, stdout, err = self.module.run_command(
1228 build_command,
1229 )
1230 if rc != 0:
1231 self.failure(err=err, rc=rc, msg="failed to perform archive", command=" ".join(build_command))
1232
1233 def _unmount(self, mount_point):
1234 """Unmount a file system.
1235
1236 :param mount_point: path on the file system that is mounted.
1237 :type mount_point: ``str``
1238 """
1239
1240 build_command = [
1241 self.module.get_bin_path("umount", True),
1242 mount_point,
1243 ]
1244 rc, stdout, err = self.module.run_command(build_command)
1245 if rc != 0:
1246 self.failure(err=err, rc=rc, msg=f"failed to unmount [ {mount_point} ]", command=" ".join(build_command))
1247
1248 def _overlayfs_mount(self, lowerdir, upperdir, mount_point):
1249 """mount an lv.
1250
1251 :param lowerdir: name/path of the lower directory
1252 :type lowerdir: ``str``
1253 :param upperdir: name/path of the upper directory
1254 :type upperdir: ``str``
1255 :param mount_point: path on the file system that is mounted.
1256 :type mount_point: ``str``
1257 """
1258
1259 build_command = [
1260 self.module.get_bin_path("mount", True),
1261 "-t",
1262 "overlayfs",
1263 "-o",
1264 f"lowerdir={lowerdir},upperdir={upperdir}",
1265 "overlayfs",
1266 mount_point,
1267 ]
1268 rc, stdout, err = self.module.run_command(build_command)
1269 if rc != 0:
1270 self.failure(
1271 err=err,
1272 rc=rc,
1273 msg=f"failed to mount overlayfs:{lowerdir}:{upperdir} to {mount_point} -- Command: {build_command}",
1274 )
1275
1276 def _container_create_tar(self):
1277 """Create a tar archive from an LXC container.
1278
1279 The process is as follows:
1280 * Stop or Freeze the container
1281 * Create temporary dir
1282 * Copy container and config to temporary directory
1283 * If LVM backed:
1284 * Create LVM snapshot of LV backing the container
1285 * Mount the snapshot to tmpdir/rootfs
1286 * Restore the state of the container
1287 * Create tar of tmpdir
1288 * Clean up
1289 """
1290
1291 with tempfile.TemporaryDirectory() as temp_dir:
1292 # Set the name of the working dir, temp + container_name
1293 work_dir = os.path.join(temp_dir, self.container_name)
1294
1295 # LXC container rootfs
1296 lxc_rootfs = self.container.get_config_item("lxc.rootfs")
1297
1298 # Test if the containers rootfs is a block device
1299 block_backed = lxc_rootfs.startswith(os.path.join(os.sep, "dev"))
1300
1301 # Test if the container is using overlayfs
1302 overlayfs_backed = lxc_rootfs.startswith("overlayfs")
1303
1304 mount_point = os.path.join(work_dir, "rootfs")
1305
1306 # Set the snapshot name if needed
1307 snapshot_name = f"{self.container_name}_lxc_snapshot"
1308
1309 container_state = self._get_state()
1310 try:
1311 # Ensure the original container is stopped or frozen
1312 if container_state not in ["stopped", "frozen"]:
1313 if container_state == "running":
1314 self.container.freeze()
1315 else:
1316 self.container.stop()
1317
1318 # Sync the container data from the container_path to work_dir
1319 self._rsync_data(lxc_rootfs, temp_dir)
1320
1321 if block_backed:
1322 if snapshot_name not in self._lvm_lv_list():
1323 if not os.path.exists(mount_point):
1324 os.makedirs(mount_point)
1325
1326 # Take snapshot
1327 size, measurement = self._get_lv_size(lv_name=self.container_name)
1328 self._lvm_snapshot_create(
1329 source_lv=self.container_name, snapshot_name=snapshot_name, snapshot_size_gb=size
1330 )
1331
1332 # Mount snapshot
1333 self._lvm_lv_mount(lv_name=snapshot_name, mount_point=mount_point)
1334 else:
1335 self.failure(
1336 err=f"snapshot [ {snapshot_name} ] already exists",
1337 rc=1,
1338 msg=f"The snapshot [ {snapshot_name} ] already exists. Please clean up old snapshot of containers before continuing.",
1339 )
1340 elif overlayfs_backed:
1341 lowerdir, upperdir = lxc_rootfs.split(":")[1:]
1342 self._overlayfs_mount(lowerdir=lowerdir, upperdir=upperdir, mount_point=mount_point)
1343
1344 # Set the state as changed and set a new fact
1345 self.state_change = True
1346 return self._create_tar(source_dir=work_dir)
1347 finally:
1348 if block_backed or overlayfs_backed:
1349 # unmount snapshot
1350 self._unmount(mount_point)
1351
1352 if block_backed:
1353 # Remove snapshot
1354 self._lvm_lv_remove(snapshot_name)
1355
1356 # Restore original state of container
1357 if container_state == "running":
1358 if self._get_state() == "frozen":
1359 self.container.unfreeze()
1360 else:
1361 self.container.start()
1362
1363 def check_count(self, count, method):
1364 if count > 1:
1365 self.failure(
1366 error=f"Failed to {method} container",
1367 rc=1,
1368 msg=f"The container [ {self.container_name} ] failed to {method}. Check to lxc is available and that the container is in a functional state.",
1369 )
1370
1371 def failure(self, **kwargs):
1372 """Return a Failure when running an Ansible command.
1373
1374 :param error: ``str`` Error that occurred.
1375 :param rc: ``int`` Return code while executing an Ansible command.
1376 :param msg: ``str`` Message to report.
1377 """
1378 if self.run_info:
1379 kwargs["run_info"] = self.run_info
1380
1381 self.module.fail_json(**kwargs)
1382
1383 def run(self):
1384 """Run the main method."""
1385
1386 action = getattr(self, LXC_ANSIBLE_STATES[self.state])
1387 action()
1388
1389 outcome = self._container_data()
1390 if self.archive_info:
1391 outcome.update(self.archive_info)
1392
1393 if self.clone_info:
1394 outcome.update(self.clone_info)
1395
1396 self.module.exit_json(changed=self.state_change, lxc_container=outcome)
1397
1398
1399 def main():
1400 """Ansible Main module."""
1401
1402 module = AnsibleModule(
1403 argument_spec=dict(
1404 name=dict(type="str", required=True),
1405 template=dict(type="str", default="ubuntu"),
1406 backing_store=dict(type="str", choices=list(LXC_BACKING_STORE.keys()), default="dir"),
1407 template_options=dict(type="str"),
1408 config=dict(
1409 type="path",
1410 ),
1411 vg_name=dict(type="str", default="lxc"),
1412 thinpool=dict(type="str"),
1413 fs_type=dict(type="str", default="ext4"),
1414 fs_size=dict(type="str", default="5G"),
1415 directory=dict(type="path"),
1416 zfs_root=dict(type="str"),
1417 lv_name=dict(type="str"),
1418 lxc_path=dict(type="path"),
1419 state=dict(choices=list(LXC_ANSIBLE_STATES.keys()), default="started"),
1420 container_command=dict(type="str"),
1421 container_config=dict(type="list", elements="str"),
1422 container_log=dict(type="bool", default=False),
1423 container_log_level=dict(choices=[n for i in LXC_LOGGING_LEVELS.values() for n in i], default="INFO"),
1424 clone_name=dict(
1425 type="str",
1426 ),
1427 clone_snapshot=dict(type="bool", default="false"),
1428 archive=dict(type="bool", default=False),
1429 archive_path=dict(
1430 type="path",
1431 ),
1432 archive_compression=dict(choices=list(LXC_COMPRESSION_MAP.keys()), default="gzip"),
1433 ),
1434 supports_check_mode=False,
1435 required_if=([("archive", True, ["archive_path"])]),
1436 )
1437 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
1438
1439 if not HAS_LXC:
1440 module.fail_json(msg="The `lxc` module is not importable. Check the requirements.")
1441
1442 if not module.params["lv_name"]:
1443 module.params["lv_name"] = module.params["name"]
1444
1445 lxc_manage = LxcContainerManagement(module=module)
1446 lxc_manage.run()
1447
1448
1449 if __name__ == "__main__":
1450 main()