
    Vh                        d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z	d dlZd dlZd dlZd dlZd dlZd dlZ	 d dlZdZd dlmZ d d	lmZ d d
lmZmZ ddddddddddZdddddddddddddid ddd!d"d#d$ddd%d&d#d'd(Zg d)d*gg d+g d,g d-g d)d.Zg d/g d0g d1d2Zd3d4d5d6d7d8d9Zd:Z d; Z! G d< d=e"      Z#d> Z$e%d?k(  r e$        yy# e$ r dZY w xY w)@    )absolute_importdivisionprint_functiona  
module: lxc_container
short_description: Manage LXC Containers
description:
  - Management of LXC containers.
author: "Kevin Carter (@cloudnull)"
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: none
  diff_mode:
    support: none
options:
  name:
    description:
      - Name of a container.
    type: str
    required: true
  backing_store:
    choices:
      - dir
      - lvm
      - loop
      - btrfs
      - overlayfs
      - zfs
    description:
      - Backend storage type for the container.
    type: str
    default: dir
  template:
    description:
      - Name of the template to use within an LXC create.
    type: str
    default: ubuntu
  template_options:
    description:
      - Template options when building the container.
    type: str
  config:
    description:
      - Path to the LXC configuration file.
    type: path
  lv_name:
    description:
      - Name of the logical volume, defaults to the container name.
      - If not specified, it defaults to E(CONTAINER_NAME).
    type: str
  vg_name:
    description:
      - If backend store is lvm, specify the name of the volume group.
    type: str
    default: lxc
  thinpool:
    description:
      - Use LVM thin pool called TP.
    type: str
  fs_type:
    description:
      - Create fstype TYPE.
    type: str
    default: ext4
  fs_size:
    description:
      - File system Size.
    type: str
    default: 5G
  directory:
    description:
      - Place rootfs directory under DIR.
    type: path
  zfs_root:
    description:
      - Create zfs under given zfsroot.
    type: str
  container_command:
    description:
      - Run a command within a container.
    type: str
  lxc_path:
    description:
      - Place container under E(PATH).
    type: path
  container_log:
    description:
      - Enable a container log for host actions to the container.
    type: bool
    default: false
  container_log_level:
    choices:
      - Info
      - info
      - INFO
      - Error
      - error
      - ERROR
      - Debug
      - debug
      - DEBUG
    description:
      - Set the log level for a container where O(container_log) was set.
    type: str
    required: false
    default: INFO
  clone_name:
    description:
      - Name of the new cloned server.
      - This is only used when state is clone.
    type: str
  clone_snapshot:
    description:
      - Create a snapshot a container when cloning.
      - This is not supported by all container storage backends.
      - Enabling this may fail if the backing store does not support snapshots.
    type: bool
    default: false
  archive:
    description:
      - Create an archive of a container.
      - This will create a tarball of the running container.
    type: bool
    default: false
  archive_path:
    description:
      - Path the save the archived container.
      - If the path does not exist the archive method will attempt to create it.
    type: path
  archive_compression:
    choices:
      - gzip
      - bzip2
      - none
    description:
      - Type of compression to use when creating an archive of a running container.
    type: str
    default: gzip
  state:
    choices:
      - started
      - stopped
      - restarted
      - absent
      - frozen
      - clone
    description:
      - Define the state of a container.
      - If you clone a container using O(clone_name) the newly cloned container created in a stopped state.
      - The running container will be stopped while the clone operation is happening and upon completion of the clone the
        original container state will be restored.
    type: str
    default: started
  container_config:
    description:
      - A list of C(key=value) options to use when configuring a container.
    type: list
    elements: str
requirements:
  - 'lxc >= 2.0 # OS package'
  - 'python3 >= 3.5 # OS Package'
  - 'python3-lxc # OS Package'
notes:
  - Containers must have a unique name. If you attempt to create a container with a name that already exists in the users
    namespace the module will simply return as "unchanged".
  - The O(container_command) can be used with any state except V(absent). If used with state V(stopped) the container will
    be V(started), the command executed, and then the container V(stopped) again. Likewise if O(state=stopped) and the container
    does not exist it will be first created, V(started), the command executed, and then V(stopped). If you use a C(|) in the
    variable you can use common script formatting within the variable itself. The O(container_command) option will always
    execute as C(bash). When using O(container_command), a log file is created in the C(/tmp/) directory which contains both
    C(stdout) and C(stderr) of any command executed.
  - If O(archive=true) the system will attempt to create a compressed tarball of the running container. The O(archive) option
    supports LVM backed containers and will create a snapshot of the running container when creating the archive.
  - If your distro does not have a package for C(python3-lxc), which is a requirement for this module, it can be installed
    from source at U(https://github.com/lxc/python3-lxc) or installed using C(pip install lxc).
a!  
- name: Create a started container
  community.general.lxc_container:
    name: test-container-started
    container_log: true
    template: ubuntu
    state: started
    template_options: --release trusty

- name: Create a stopped container
  community.general.lxc_container:
    name: test-container-stopped
    container_log: true
    template: ubuntu
    state: stopped
    template_options: --release trusty

- name: Create a frozen container
  community.general.lxc_container:
    name: test-container-frozen
    container_log: true
    template: ubuntu
    state: frozen
    template_options: --release trusty
    container_command: |
      echo 'hello world.' | tee /opt/started-frozen

# Create filesystem container, configure it, and archive it, and start it.
- name: Create filesystem container
  community.general.lxc_container:
    name: test-container-config
    backing_store: dir
    container_log: true
    template: ubuntu
    state: started
    archive: true
    archive_compression: none
    container_config:
      - "lxc.aa_profile=unconfined"
      - "lxc.cgroup.devices.allow=a *:* rmw"
    template_options: --release trusty

# Create an lvm container, run a complex command in it, add additional
# configuration to it, create an archive of it, and finally leave the container
# in a frozen state. The container archive will be compressed using bzip2
- name: Create a frozen lvm container
  community.general.lxc_container:
    name: test-container-lvm
    container_log: true
    template: ubuntu
    state: frozen
    backing_store: lvm
    template_options: --release trusty
    container_command: |
      apt-get update
      apt-get install -y vim lxc-dev
      echo 'hello world.' | tee /opt/started
      if [[ -f "/opt/started" ]]; then
          echo 'hello world.' | tee /opt/found-started
      fi
    container_config:
      - "lxc.aa_profile=unconfined"
      - "lxc.cgroup.devices.allow=a *:* rmw"
    archive: true
    archive_compression: bzip2
  register: lvm_container_info

- name: Debug info on container "test-container-lvm"
  ansible.builtin.debug:
    var: lvm_container_info

- name: Run a command in a container and ensure it is in a "stopped" state.
  community.general.lxc_container:
    name: test-container-started
    state: stopped
    container_command: |
      echo 'hello world.' | tee /opt/stopped

- name: Run a command in a container and ensure it is in a "frozen" state.
  community.general.lxc_container:
    name: test-container-stopped
    state: frozen
    container_command: |
      echo 'hello world.' | tee /opt/frozen

- name: Start a container
  community.general.lxc_container:
    name: test-container-stopped
    state: started

- name: Run a command in a container and then restart it
  community.general.lxc_container:
    name: test-container-started
    state: restarted
    container_command: |
      echo 'hello world.' | tee /opt/restarted

- name: Run a complex command within a "running" container
  community.general.lxc_container:
    name: test-container-started
    container_command: |
      apt-get update
      apt-get install -y curl wget vim apache2
      echo 'hello world.' | tee /opt/started
      if [[ -f "/opt/started" ]]; then
          echo 'hello world.' | tee /opt/found-started
      fi

# Create an archive of an existing container, save the archive to a defined
# path and then destroy it.
- name: Archive container
  community.general.lxc_container:
    name: test-container-started
    state: absent
    archive: true
    archive_path: /opt/archives

# Create a container using overlayfs, create an archive of it, create a
# snapshot clone of the container and and finally leave the container
# in a frozen state. The container archive will be compressed using gzip.
- name: Create an overlayfs container archive and clone it
  community.general.lxc_container:
    name: test-container-overlayfs
    container_log: true
    template: ubuntu
    state: started
    backing_store: overlayfs
    template_options: --release trusty
    clone_snapshot: true
    clone_name: test-container-overlayfs-clone-snapshot
    archive: true
    archive_compression: gzip
  register: clone_container_info

- name: Debug info on container "test-container"
  ansible.builtin.debug:
    var: clone_container_info

- name: Clone a container using snapshot
  community.general.lxc_container:
    name: test-container-overlayfs-clone-snapshot
    backing_store: overlayfs
    clone_name: test-container-overlayfs-clone-snapshot2
    clone_snapshot: true

- name: Create a new container and clone it
  community.general.lxc_container:
    name: test-container-new-archive
    backing_store: dir
    clone_name: test-container-new-archive-clone

- name: Archive and clone a container then destroy it
  community.general.lxc_container:
    name: test-container-new-archive
    state: absent
    clone_name: test-container-new-archive-destroyed-clone
    archive: true
    archive_compression: gzip

- name: Start a cloned container.
  community.general.lxc_container:
    name: test-container-new-archive-destroyed-clone
    state: started

- name: Destroy a container
  community.general.lxc_container:
    name: '{{ item }}'
    state: absent
  with_items:
    - test-container-stopped
    - test-container-started
    - test-container-frozen
    - test-container-lvm
    - test-container-config
    - test-container-overlayfs
    - test-container-overlayfs-clone
    - test-container-overlayfs-clone-snapshot
    - test-container-overlayfs-clone-snapshot2
    - test-container-new-archive
    - test-container-new-archive-clone
    - test-container-new-archive-destroyed-clone
a  
lxc_container:
  description: Container information.
  returned: success
  type: complex
  contains:
    name:
      description: Name of the LXC container.
      returned: success
      type: str
      sample: test_host
    init_pid:
      description: Pid of the LXC init process.
      returned: success
      type: int
      sample: 19786
    interfaces:
      description: List of the container's network interfaces.
      returned: success
      type: list
      sample: ["eth0", "lo"]
    ips:
      description: List of IPs.
      returned: success
      type: list
      sample: ["10.0.3.3"]
    state:
      description: Resulting state of the container.
      returned: success
      type: str
      sample: "running"
    archive:
      description: Resulting state of the container.
      returned: success, when archive is true
      type: str
      sample: "/tmp/test-container-config.tar"
    clone:
      description: If the container was cloned.
      returned: success, when clone_name is specified
      type: bool
      sample: true
NTF)AnsibleModule)BOOLEANS_FALSE)to_textto_bytesztar.tgzz-czf)	extensionargumentztar.bz2z-cjftarz-cf)gzipbzip2none	variablesz--configz
--templatez--bdevz	--lxcpathz--lvnamez--vgnamez
--thinpoolz--fstypez--fssizez--dirz	--zfsroot)configtemplatebacking_storelxc_pathlv_namevg_namethinpoolfs_typefs_size	directoryzfs_rootz--backingstorage--namez	--newname)r   r   r   name
clone_namez--backingstorez--origz--new)variables-lxc-copyvariables-lxc-clone)createclone)r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   )dirlvmbtrfsloop	overlayfszfs)infoINFOInfo)errorERRORError)debugDEBUGDebug)r*   r-   r0   _started_stopped
_restarted
_destroyed_frozen_clone)startedstopped	restartedabsentfrozenr"   z#!/usr/bin/env bash
pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
    if [[ -f ".bashrc" ]];then
        source .bashrc
        unset HOSTNAME
    fi
popd

# User defined command
%(container_command)s
c                 :   t        j                  d      \  }}t        j                  |d      }	 |j	                  t        t        d| iz  d             |j                          |j                          t        j                  |t        dd             t        j                  t        j                  d	      d
   d      }t        j                  t        j                  d      d
   d      }	 t        j                  |g||      j                          |j                          |j                          t        j                  |       y# |j                          w xY w# |j                          |j                          t        j                  |       w xY w)a)  Write out a script onto a target.

    This method should be backward compatible with Python when executing
    from within the container.

    :param command: command to run, this can be a script and can use spacing
                    with newlines as separation.
    :type command: ``str``
    zlxc-attach-script)prefixwbcontainer_commandsurrogate_or_stricterrors0700   zlxc-attach-script-logr   abzlxc-attach-script-err)stdoutstderrN)tempfilemkstemposfdopenwriter	   ATTACH_TEMPLATEflushclosechmodint
subprocessPopencommunicateremove)commandfdscript_filefstdout_filestderr_files         s/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/lxc_container.pycreate_scriptr^   )  sC    !((0CDR
		"dA	,?+IIRghi				 HH[#fa.) ))H,,4KLQOQUVK ))H,,4KLQOQUVKM	
 +- 	 			+1 	
	( 	 			+s   5E 1'E# E #7Fc                      e Zd Zd Zd Zed        Zed&d       Zed        Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd'dZd Zd Zd'dZd(dZd(dZd(dZd(dZd Zd Zd Zd Z	 d)dZd Zd Zd Z d Z!d  Z"d! Z#d" Z$d# Z%d$ Z&d% Z'y)*LxcContainerManagementc                 (   || _         | j                   j                  d   | _        d| _        d| _        | j                   j                  d   | _        | j                   j                  d   | _        | j                         | _        d| _	        d| _
        y)zManagement of LXC containers via Ansible.

        :param module: Processed Ansible Module.
        :type module: ``object``
        stateFNr   r   )moduleparamsrb   state_changelxc_vgr   container_nameget_container_bind	containerarchive_info
clone_info)selfrc   s     r]   __init__zLxcContainerManagement.__init__V  s|     [[''0
!**:6"kk008002     c                 B    t        j                  | j                        S )N)r   )lxc	Containerrg   rl   s    r]   rh   z)LxcContainerManagement.get_container_bindf  s    }}$"5"566rn   c                 |    t        |       j                  d      \  } }t        |       } t        |      dk7  r| dz  } | S )zReturn a rounded floating point number.

        :param num: Number to round up.
        :type: ``float``
        :returns: Rounded up number.
        :rtype: ``int``
        .r      )strsplitrR   )numparts     r]   _roundupzLxcContainerManagement._roundupi  s<     HNN3'	T#ht9>1HC
rn   Nc                 T     t         fdt        j                  |      D              S )zCheck if a container exists.

        :param container_name: Name of the container.
        :type: ``str``
        :returns: True or False if the container is found.
        :rtype: ``bol``
        c              3   (   K   | ]	  }|k(    y wN ).0crg   s     r]   	<genexpr>z;LxcContainerManagement._container_exists.<locals>.<genexpr>  s     Z11&Zs   )config_path)anyrp   list_containersrg   r   s   ` r]   _container_existsz(LxcContainerManagement._container_existsx  s"     Z0C0CPX0YZZZrn   c                     | j                         D ]9  \  }}|j                  t        |             |j                  t        |             ; |S )al  Return a command list with all found options.

        :param variables_dict: Pre-parsed optional variables used from a
                               seed command.
        :type variables_dict: ``dict``
        :param build_command: Command to run.
        :type build_command: ``list``
        :returns: list of command options.
        :rtype: ``list``
        )itemsappendrv   )variables_dictbuild_commandkeyvalues       r]   _add_variablesz%LxcContainerManagement._add_variables  sL     )..0 	-JC  S*  U,	- rn   c                 x   |j                         }t        | j                  j                  d      D ]  }|j	                  |d        t        j                  ddg      }|j                         D ci c]:  \  }}| j                  j                  |   |vr|| j                  j                  |   < }}}|S c c}}w )zReturn a dict of all variables as found within the module.

        :param variables: Hash of all variables to find.
        :type variables: ``dict``
        r   N )copyLXC_BACKING_STORErc   rd   popr   unionr   )rl   r   vfalse_valueskresults         r]   	_get_varsz LxcContainerManagement._get_vars  s     NN$	"4;;#5#5o#FG 	#AMM!T"	# &++T2J7 ")
1{{!!!$L8 t{{!!!$$
 

 
s   2?B6c           
         | j                   j                  d   }|sy| j                  j                  }t	        |d      5 }t        |j                         d      j                  d      }ddd       |D cg c]  }|j                  dd	       }}d}|D ]  \  }}	|j                         }|	j                         }	|d
|	d}
t        j                  d|z        }D ]|  }|j                  |      s|j                  dd	      \  }}dj                  |j                               }|j                  |      }|	|k7  r|d	z  }|
|vrd}|j                  ||
         d}|j!                  |
        |r| j#                         }|dk7  r| j                  j%                          t	        |d      5 }|j'                  D cg c]  }t)        |d       c}       ddd       d| _        |dk(  r| j-                          y|dk(  r+| j-                          | j                  j/                          yyy# 1 sw Y   xY wc c}w c c}w # 1 sw Y   oxY w)zConfigure an LXC container.

        Write new configuration values to the lxc config file. This will
        stop the container if it is running write the new options and then
        restart the container upon completion.
        container_configFrbrA   rB   TN=ru   z = 
z	%s(\s+)?= r9   r?   runningr<   )rc   rd   ri   config_file_nameopenr   read
splitlinesrw   striprecompilematchjoinindexinsertr   
_get_statestop
writelinesr	   re   _container_startupfreeze)rl   _container_configcontainer_config_filerZ   r   iparsed_optionsconfig_changer   r   	new_entrykeyreoption_linedummy_valueconfig_value
line_indexcontainer_statelines                      r]   _configzLxcContainerManagement._config  sD    !KK../AB  $ ? ?'. 	`!&qvvx8MNYYZ^_	` 4EEa!''#q/EE( 	3JC))+CKKME'*E2IJJ|c12E/ 3;;{+$/$5$5c1$=ME6#&88FLLN#;L!1!7!7!DJ,"a
$,<<,0M,33J	J3 !% ''	2+	30 "oo/O)+##%+T2 jaWghtht4IJhij !%D)+'') H,'')%%' - ;	` 	` F@ ij js/   +H06H=.I>I
I0H:IIc                    | j                         }|dk7  r!d| _        | j                  j                          d}| j                  j                  d      }|sd}| j                  j                  dd      }|g}| j                  | j                  t        d   |         |	      }| j                  j                  d
   r|j                  d       n-| j                  j                  d   dk(  r|j                  d       | j                  j                  |      \  }}}|dk7  rGdt        j                  j                  |      z  }| j                  |||dj!                  |             yd| _        |dk(  r| j                  j#                          y|dk(  r4| j                  j#                          | j                  j%                          y)a  Clone a new LXC container from an existing container.

        This method will clone an existing container to a new container using
        the `clone_name` variable as the new container name. The method will
        create a container if the container `name` does not exist.

        Note that cloning a container will ensure that the original container
        is "stopped" before the clone can be done. Because this operation can
        require a state change the method will return the original container
        to its prior state upon completion of the clone.

        Once the clone is complete the new container will be left in a stopped
        state.
        r9   Tr   zlxc-copyr    z	lxc-cloner"   r   r   r   clone_snapshotz
--snapshotr   r'   r   zFailed executing %s.r   errrcmsgrW   r   r<   )r   re   ri   r   rc   get_bin_pathr   r   LXC_COMMAND_MAPrd   r   run_commandrK   pathbasenamefailurer   startr   )	rl   r   
clone_vars	clone_cmdr   r   return_datar   messages	            r]   _container_create_clonez.LxcContainerManagement._container_create_clone  s   " //+i' $DNN! *
KK,,Z8	.J00dCI 
 ++>>)'2:> *  (	 , 
 ;;./  . [[0K?  .#{{66}EK7,rww/?/?	/JJGLLBGSXX!6    !%D )+$$&
 	 !H,$$&%%'rn   c                    | j                   j                  dd      d| j                  dg}| j                  | j	                  t
        d   d         |      }| j                   j                  d	   r	 t        j                         d
k7  rt        j                  d      }n6t        j                  j                  d      st        j                  d       d}|j                  dt        j                  j                  |d| j                  z        d| j                   j                  j!                  d      j#                         g       | j                   j                  d   }|r)|j%                  d       |t'        j(                  |      z  }| j                   j+                  |      \  }}}|d
k7  r'd}| j-                  |||dj                  |             yd| _        y# t        $ r t        j                  d      }Y )w xY w)a  Create a new LXC container.

        This method will build and execute a shell command to build the
        container. It would have been nice to simply use the lxc python library
        however at the time this was written the python library, in both py2
        and py3 didn't support some of the more advanced container create
        processes. These missing processes mainly revolve around backing
        LXC containers with block devices.
        z
lxc-createTr   z--quietr!   r   r   r   container_logr   HOMEz/var/log/lxc/z	--logfilez
lxc-%s.logz--logprioritycontainer_log_leveltemplate_optionsz--zFailed executing lxc-create.r   r   N)rc   r   rg   r   r   r   rd   rK   getuidgetenvr   isdirmakedirsOSErrorextendr   getupperr   shlexrw   r   r   re   )rl   r   log_pathr   r   r   r   r   s           r]   _createzLxcContainerManagement._create'  s    KK$$\48d))
 ++>>)(3K@ *  (	 , 
 ;;o.-99;!#!yy0H77==9O4.H   lT-@-@@  ""&&)%'	" 	  ;;--.@A  &U[[)9::M#{{66}EK74GLLBGSXXm5L   !%D7  -99V,-s   2A#G G?>G?c                     | j                   j                         | j                   j                         | j                         t	        | j                   j
                        | j                  dS )zlReturns a dict of container information.

        :returns: container data
        :rtype: ``dict``
        )
interfacesipsrb   init_pidr   )ri   get_interfacesget_ipsr   rR   r   rg   rr   s    r]   _container_dataz&LxcContainerManagement._container_datag  sS     ..779>>))+__&DNN334''
 	
rn   c                 L    | j                   j                         }|rd| _        |S )zUnfreeze a container.

        :returns: True or False based on if the container was unfrozen.
        :rtype: ``bol``
        T)ri   unfreezere   )rl   r   s     r]   	_unfreezez LxcContainerManagement._unfreezev  s&     >>**, $Drn   c                     | j                  | j                  | j                        r-t        | j                  j
                        j                         S t        d      S )zReturn the state of a container.

        If the container is not found the state returned is "absent"

        :returns: state of a container as a lower case string.
        :rtype: ``str``
        r   r;   )r   rg   r   rv   ri   rb   lowerrr   s    r]   r   z!LxcContainerManagement._get_state  sI     !!1D1Dt}}!]t~~++,22448}rn   c                     | j                   j                  d   }|rc| j                         }|dk(  r| j                          n|dk(  r| j	                          | j
                  j                  t        |       d| _        yy)zExecute a shell command.r@   r<   r9   TN)	rc   rd   r   r   r   ri   attach_waitr^   re   )rl   r@   r   s      r]   _execute_commandz'LxcContainerManagement._execute_command  sq     !KK../BC"oo/O(*  I-'')NN&&}6GH $D rn   c                 ^   | j                         | _        t        |      D ]M  }| j                         dk(  r y| j                  j	                          d| _        t        j                  d       O | j                  | j                         d| j                  z  dd| j                  z         y)zEnsure a container is started.

        :param timeout: Time before the destroy operation is abandoned.
        :type timeout: ``int``
        r   Tru    Failed to start container [ %s ]pThe container [ %s ] failed to start. Check to lxc is available and that the container is in a functional state.lxc_containerr,   r   r   N)rh   ri   ranger   r   re   timesleepr   r   rg   rl   timeoutr   s      r]   r   z)LxcContainerManagement._container_startup  s     0027^ 	E I-NN  " $DJJqM	 	..04t7J7JJ //0	 	 	
rn   c                 f    | j                   j                  d   rd| j                         i| _        yy)rCreate a compressed archive of a container.

        This will store archive_info in as self.archive_info
        archiveN)rc   rd   _container_create_tarrj   rr   s    r]   _check_archivez%LxcContainerManagement._check_archive  s3     ;;i(4557!D )rn   c                     | j                   j                  d   }|r?| j                  || j                        sd| j	                         i| _        yddi| _        yy)r   r   r   clonedFN)rc   rd   r   r   r   rk   )rl   r   s     r]   _check_clonez#LxcContainerManagement._check_clone  s^     [[''5
))dmm)\d::<#
 e# rn   c                    t        |      D ]  }| j                  | j                  | j                        s y| j	                          | j                          | j                         dk7  r!d| _        | j                  j                          | j                  j                         rd| _        t        j                  d        | j                  | j                         d| j                  z  dd| j                  z         y)	zEnsure a container is destroyed.

        :param timeout: Time before the destroy operation is abandoned.
        :type timeout: ``int``
        r   r9   Tru   z"Failed to destroy container [ %s ]zyThe container [ %s ] failed to be destroyed. Check that lxc is available and that the container is in a functional state.r   N)r   r   rg   r   r  r  r   re   ri   r   destroyr   r   r   r   r   s      r]   r5   z!LxcContainerManagement._destroyed  s     7^ 	E))9L9LW[WdWd)e !  I-$(!##%~~%%'$(! JJqM%	( LL"224 "&"5"56)+/+>+>?  rn   c                 "   | j                  |d       | j                  | j                  | j                        r| j	                          | j                          | j                         }|dk(  rnX|dk(  r"| j                  j                          d| _	        n1| j                          | j                  j                          d| _	        | j                          | j                          y| j                          |dz  }| j                  |       y)zEnsure a container is frozen.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        r<   countmethodr   r   Tru   N)check_countr   rg   r   r   r   r   ri   r   re   r   r  r  r   r6   rl   r	  r   s      r]   r6   zLxcContainerManagement._frozen  s     	uX6!!1D1Dt}}!]!!# LLN"oo/O(* I-%%'$(!'')%%'$(! ! LLNQJELLrn   c                    | j                  |d       | j                  | j                  | j                        r| j	                          | j                          | j                         dk7  r!| j                  j                          d| _	        | j                          | j                          | j                          y| j                          |dz  }| j                  |       y)zEnsure a container is restarted.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        restartr  r   r9   Tru   N)r  r   rg   r   r   r   r   ri   r   re   r   r  r  r   r4   rl   r	  s     r]   r4   z!LxcContainerManagement._restarted  s     	uY7!!1D1Dt}}!]!!# LLN I-##%$(! ##% ! LLNQJEOOE"rn   c                    | j                  |d       | j                  | j                  | j                        ru| j	                          | j                          | j                         dk7  r!| j                  j                          d| _	        | j                          | j                          y| j                          |dz  }| j                  |       y)zEnsure a container is stopped.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        r   r  r   r9   Tru   N)r  r   rg   r   r   r   r   ri   r   re   r  r  r   r3   r  s     r]   r3   zLxcContainerManagement._stopped=  s     	uV4!!1D1Dt}}!]!!# LLN I-##%$(! ! LLNQJEMM% rn   c                 8   | j                  |d       | j                  | j                  | j                        r| j	                         }|dk(  rnc|dk(  r| j                          nM| j                         s=| j                  | j                         d| j                  z  dd| j                  z  	       | j                          | j                          | j                          | j                          y
| j                          |dz  }| j                  |       y
)zEnsure a container is started.

        If the container does not exist the container will be created.

        :param count: number of times this command has been called by itself.
        :type count: ``int``
        r   r  r   r   r<   r   ru   r   r   N)r  r   rg   r   r   r   r   r   r   r   r   r  r  r   r2   r  s      r]   r2   zLxcContainerManagement._started[  s    	uW5!!1D1Dt}}!]"oo/O)+ H, ,,."&"6"6"8$&*&9&9:"$($7$78   !!# LLN ! LLNQJEMM% rn   c                    | j                   j                  dd      dg}| j                   j                  |      \  }}}|dk7  r%| j                  ||ddj	                  |             yt        |j                               S )	z0Return the name of the Volume Group used in LXC.z
lxc-configTzlxc.bdev.lvm.vgr   z%Failed to read LVM VG from LXC configr   r   N)rc   r   r   r   r   rv   r   )rl   r   r   vgr   s        r]   _get_lxc_vgz"LxcContainerManagement._get_lxc_vg  s}     KK$$\48
 kk--m<B7LL;/	   rxxz?"rn   c                    | j                         }| j                  j                  dd      g}| j                  j                  |      \  }}}|dk7  r$| j	                  ||ddj                  |             |j                         D cg c]  }|j                          c}dd }|D cg c]  }|d   |k(  s|d    c}S c c}w c c}w )	z(Return a list of all lv in a current vg.lvsTr   zFailed to get list of LVsr   r   ru   N)r  rc   r   r   r   r   r   rw   )	rl   r  r   r   rG   r   r   all_lvmslv_entrys	            r]   _lvm_lv_listz#LxcContainerManagement._lvm_lv_list  s     KK$$UD1
 ++11-@FC7LL//	   (.'8'8':;!AGGI;AB?,4Jr8IJJ <Js   C)C7Cc                    d|ddg}| j                   j                  |      \  }}}|dk7  r'| j                  ||d|z  dj                  |             |j	                         D cg c]  }|j                          c}dd	 }|D cg c]  }|j                  d
      s| }}|d   j                         }	t        |	d         |	d   fS c c}w c c}w )zReturn the available size of a given VG.

        :param vg_name: Name of volume.
        :type vg_name: ``str``
        :returns: size and measurement of an LV
        :type: ``tuple``
        	vgdisplay--unitsgr   zfailed to read vg %sr   r   ru   NFree)	rc   r   r   r   r   r   
startswithrw   float)
rl   r   r   r   rG   r   r   vg_infofree_pe_free_pes
             r]   _get_vg_free_pez&LxcContainerManagement._get_vg_free_pe  s     	
 ++11-@FC7LL*W4/	   '-&7&7&9:1779:12>%>f)=1>>1:##%Xb\"HRL00 ;>s   $CCCc                 "   | j                         }t        j                  j                  ||      }d|ddg}| j                  j                  |      \  }}}|dk7  r'| j                  ||d|z  dj                  |             |j                         D cg c]  }|j                          c}dd	 }	|	D cg c]  }|j                  d
      s| }
}|
d   j                         }| j                  t        |d               |d   fS c c}w c c}w )zReturn the available size of a given LV.

        :param lv_name: Name of volume.
        :type lv_name: ``str``
        :returns: size and measurement of an LV
        :type: ``tuple``
        	lvdisplayr  r  r   zfailed to read lv %sr   r   ru   NzLV Sizer  r   )r  rK   r   r   rc   r   r   r   r   r!  rw   rz   r"  )rl   r   r  lvr   r   rG   r   r   lv_infor%  r$  s               r]   _get_lv_sizez#LxcContainerManagement._get_lv_size  s    WW\\"g&	
 ++11-@FC7LL*R//	   '-&7&7&9:1779:12>&B!!,,y*AABB1+##%}}U72;/0'"+== ;Bs   D5DDc           
         | j                         }| j                  |      \  }}|t        |      k  r d|d|d|d}| j                  dd|       | j                  j                  d	d
      d|dt        j                  j                  ||      d|z  g}| j                  j                  |      \  }	}
}|	dk7  r| j                  ||	d|d|d|       yy)a.  Create an LVM snapshot.

        :param source_lv: Name of lv to snapshot
        :type source_lv: ``str``
        :param snapshot_name: Name of lv snapshot
        :type snapshot_name: ``str``
        :param snapshot_size_gb: Size of snapshot to create
        :type snapshot_size_gb: ``int``
        )r   zSnapshot size [ z ] is > greater than [ z ] on volume group [ z ]z#Not enough space to create snapshot   r,   r   r   lvcreateTz-nz-sz-L%sgr   zFailed to Create LVM snapshot /z --> r   r   r   N)
r  r&  r"  r   rc   r   rK   r   r   r   )rl   	source_lvsnapshot_namesnapshot_size_gbr  
free_spacemeasurementr   r   r   rG   r   s               r]   _lvm_snapshot_createz+LxcContainerManagement._lvm_snapshot_create  s     "&"6"6r"6"B
K.// .z2?  LL;   KK$$Z6GGLLY'&&
 ++11-@FC7LL9m5   rn   c           
          | j                         }| j                  j                  dd      d|d||g}| j                  j                  |      \  }}}|dk7  r| j	                  ||d|d|d|       y	y	)
zmount an lv.

        :param lv_name: name of the logical volume to mount
        :type lv_name: ``str``
        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        mountTz/dev/r0  r   zfailed to mountlvm lv  to r1  N)r  rc   r   r   r   )rl   r   mount_pointr  r   r   rG   r   s           r]   _lvm_lv_mountz$LxcContainerManagement._lvm_lv_mount  s      KK$$Wd3(

 ++11-@FC7LL7K1   rn   c                    t        j                  t        dd            }| j                  j                  d   }t         j
                  j                  |      st        j                  |       | j                  j                  d   }t        |   }t         j
                  j                  || j                        d|d   }| j                  j                  dd      d	t         j
                  j                  |      z  |d
   |dg}| j                  j                  |      \  }}	}
t        j                  |       |dk7  r$| j                  |
|ddj                  |             |S )zCreate an archive of a given ``source_dir`` to ``output_path``.

        :param source_dir:  Path to the directory to be archived.
        :type source_dir: ``str``
        0077rE   archive_patharchive_compressionrt   r
   r   Tz--directory=%sr   r   zfailed to create tar archiver   r   )rK   umaskrR   rc   rd   r   r   r   LXC_COMPRESSION_MAPr   rg   r   realpathr   r   )rl   
source_dir	old_umaskr?  r@  compression_typearchive_namer   r   rG   r   s              r]   _create_tarz"LxcContainerManagement._create_tar,  s=    HHS^,	{{)).9ww}}\*KK%"kk001FG./BC GGLL## [)
 KK$$UD1rww//
;;Z(
 ++11
FC 	7LL2/	   rn   c                 
   | j                         }| j                  j                  dd      d|d|g}| j                  j                  |      \  }}}|dk7  r+| j	                  ||d|d|dj                  |             y	y	)
zmRemove an LV.

        :param lv_name: The name of the logical volume
        :type lv_name: ``str``
        lvremoveTz-fr0  r   zFailed to remove LVM LV r   r   N)r  rc   r   r   r   r   )rl   r   r  r   r   rG   r   s          r]   _lvm_lv_removez%LxcContainerManagement._lvm_lv_remove]  s     KK$$Z67#

 ++11-@FC7LL797C/	   rn   c           	         |j                  d      }d|v r |j                  |j                  d             |D ]  }t        j                  j                  |      }| j                  j                  dd      d||g}| j                  j                  |      \  }}}|dk7  sg| j                  ||ddj                  |      	        y
)a	  Sync the container directory to the temp directory.

        :param container_path: path to the container container
        :type container_path: ``str``
        :param temp_dir: path to the temporary local working directory
        :type temp_dir: ``str``
        :r'   rsyncTz-aHAXr   zfailed to perform archiver   r   N)rw   r   r   rK   r   dirnamerc   r   r   r   r   )	rl   container_pathtemp_dirfs_pathsfs_pathr   r   rG   r   s	            r]   _rsync_dataz"LxcContainerManagement._rsync_datas  s     "'',("LL45 	Gggoog.G (($7	M #kk55OB Qw3HH]3	  	rn   c                     | j                   j                  dd      |g}| j                   j                  |      \  }}}|dk7  r(| j                  ||d|z  dj	                  |             yy)zUnmount a file system.

        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        umountTr   zfailed to unmount [ %s ]r   r   N)rc   r   r   r   r   )rl   r;  r   r   rG   r   s         r]   _unmountzLxcContainerManagement._unmount  su     KK$$Xt4
 ++11-@FC7LL.</	   rn   c                     | j                   j                  dd      dddd|d|d|g}| j                   j                  |      \  }}}|dk7  r!| j                  ||d	|d
|d|d|       yy)a2  mount an lv.

        :param lowerdir: name/path of the lower directory
        :type lowerdir: ``str``
        :param upperdir: name/path of the upper directory
        :type upperdir: ``str``
        :param mount_point: path on the file system that is mounted.
        :type mount_point: ``str``
        r9  Tz-tr'   z-oz	lowerdir=z
,upperdir=r   zfailed to mount overlayfs:rM  r:  z -- Command: r1  N)rc   r   r   r   )rl   lowerdirupperdirr;  r   r   rG   r   s           r]   _overlayfs_mountz'LxcContainerManagement._overlayfs_mount  s     KK$$Wd3+xB
 ++11-@FC7LL;G   rn   c                    t        j                         }t        j                  j	                  || j
                        }| j                  j                  d      }|j                  t        j                  j	                  t        j                  d            }|j                  d      }t        j                  j	                  |d      }d| j
                  z  }| j                         }	 |dvr:|dk(  r| j                  j                          n| j                  j                          | j                  ||       |r|| j                         vrt        j                  j                  |      st        j                   |       | j#                  | j
                        \  }	}
| j%                  | j
                  ||		       | j'                  ||
       nH| j)                  d|z  dd|z         n-|r+|j+                  d      dd \  }}| j-                  |||       d| _        | j1                  |      |s|r| j3                  |       |r| j5                  |       |dk(  rH| j                         dk(  r| j                  j7                          n| j                  j9                          t;        j<                  |       S # |s|r| j3                  |       |r| j5                  |       |dk(  rH| j                         dk(  r| j                  j7                          n| j                  j9                          t;        j<                  |       w xY w)a  Create a tar archive from an LXC container.

        The process is as follows:
            * Stop or Freeze the container
            * Create temporary dir
            * Copy container and config to temporary directory
            * If LVM backed:
                * Create LVM snapshot of LV backing the container
                * Mount the snapshot to tmpdir/rootfs
            * Restore the state of the container
            * Create tar of tmpdir
            * Clean up
        z
lxc.rootfsdevr'   rootfsz%s_lxc_snapshot)r9   r<   r   )r   )r2  r3  r4  )r   r;  zsnapshot [ %s ] already existsru   zaThe snapshot [ %s ] already exists. Please clean up old snapshot of containers before continuing.r1  rM  N)rY  rZ  r;  T)rD  r<   )rI   mkdtemprK   r   r   rg   ri   get_config_itemr!  sepr   r   r   rT  r  existsr   r+  r7  r<  r   rw   r[  re   rH  rW  rK  r   r   shutilrmtree)rl   rQ  work_dir
lxc_rootfsblock_backedoverlayfs_backedr;  r3  r   sizer6  rY  rZ  s                r]   r   z,LxcContainerManagement._container_create_tar  s     ##% 77<<$*=*=> ^^33LA
 ",,RWW\\"&&%-HI &00=ggll8X6 *D,?,??//+C	$&;;"i/NN))+NN'') Z2 (9(9(;;77>>+6K0 )-(9(9 $ 3 3 ): )%D+ --"&"5"5&3)- .  && -$/ ' 
 LL<}LP+, !  "%/%5%5c%:12%>"(%%%% + &  !%D##x#8/k*##M2 )+??$0NN++-NN((* MM(#! /k*##M2 )+??$0NN++-NN((* MM(#s   (E	J< <BMc           	      `    |dkD  r)| j                  d|z  dd| j                  d|d       y y )Nru   zFailed to %s containerzThe container [ z ] failed to zL. Check to lxc is available and that the container is in a functional state.r.  )r   rg   )rl   r	  r
  s      r]   r  z"LxcContainerManagement.check_count/  s<    19LL.7 "&!4!4f>   rn   c                 <     | j                   j                  di | y)zReturn a Failure when running an Ansible command.

        :param error: ``str``  Error that occurred.
        :param rc: ``int``     Return code while executing an Ansible command.
        :param msg: ``str``    Message to report.
        Nr~   )rc   	fail_json)rl   kwargss     r]   r   zLxcContainerManagement.failure9  s     	''rn   c                 V   t        | t        | j                           } |        | j                         }| j                  r|j                  | j                         | j                  r|j                  | j                         | j                  j                  | j                  |       y)zRun the main method.)changedr   N)
getattrLXC_ANSIBLE_STATESrb   r   rj   updaterk   rc   	exit_jsonre   )rl   actionoutcomes      r]   runzLxcContainerManagement.runC  s     1$**=>&&(NN4,,-??NN4??+%%! 	 	
rn   r}   )<   )r   )   )(__name__
__module____qualname__rm   rh   staticmethodrz   r   r   r   r   r   r   r   r   r   r   r   r  r  r5   r6   r4   r3   r2   r  r  r&  r+  r7  r<  rH  rK  rT  rW  r[  r   r  r   rv  r~   rn   r]   r`   r`   U  s     7   [ [  "(7(rCJ>%@

%
2	"#J# J#B!<)!V#$K&1:>@ /0*X2/b,"H(6g$R(
rn   r`   c                  h   t        t        d2i dt        dd      dt        dd      dt        dt        t        j	                               d	
      dt        d      dt        d      dt        dd      dt        d      dt        dd      dt        dd      dt        d      dt        d      dt        d      dt        d      dt        t        t
        j	                               d      dt        d      dt        dd       d!t        d"d#      d$t        t        j                         D  cg c]  } | D ]  }|  c}} d%      d&t        d      d't        d"d(      d)t        d"d#      d*t        d      d+t        t        t        j	                               d,      d#d)dd*gfg-      }t        s|j                  d./       |j                  d   s|j                  d   |j                  d<   t        |0      }|j                          y1c c}} w )3zAnsible Main module.r   rv   T)typerequiredr   ubuntu)r~  defaultr   r#   )r~  choicesr  r   )r~  r   r   r   rp   r   r   ext4r   5Gr   r   r   r   rb   r8   )r  r  r@   r   list)r~  elementsr   boolFr   r*   r   r   falser   r?  r@  r   )argument_specsupports_check_moderequired_ifz;The `lxc` module is not importable. Check the requirements.)r   )rc   Nr~   )r   dictr  r   keysrq  LXC_LOGGING_LEVELSvaluesrB  HAS_LXCrl  rd   r`   rv  )r   nrc   
lxc_manages       r]   mainr  V  s     T
T

  T
 .3356T
 "T
" #T
( )T
0 1T
6 7T
> ?T
F GT
L MT
R ST
X YT
^ /4467!_T
f #gT
l "mT
t uT
| !%$6$=$=$?KqKAKK!}T
D ET
J  KT
R ST
Z [T
` !%05578!aT
j "~./
oZFx M 	 	
 ==##)==#8i 'v6JNNK Ls   H.__main__)&
__future__r   r   r   r~  __metaclass__DOCUMENTATIONEXAMPLESRETURNrK   os.pathr   rc  rS   rI   r   r   rp   r  ImportErroransible.module_utils.basicr   )ansible.module_utils.parsing.convert_boolr   +ansible.module_utils.common.text.convertersr   r	   rB  r   r   r  rq  rN   r^   objectr`   r  ry  r~   rn   r]   <module>r     s   A @n`un)
V 
  	      G 4 D I 
 
  ( 	 $%#!!$!! #
" 0#!%
 .#!! 
!!N 	! 0 %((   
)X~
V ~
B hV zF q(  Gs   C	 	CC