
    Vh                       d dl mZ dZdZdZd dlZ ej                  dde       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 dlZd dlmZ d d	lmZ d d
lmZ d dlmZmZmZ d dlmZmZ d dl m!Z! d dl"m#Z# dZ$dZ%dZ&dZ'dZ(dZ)dZ* e+dd      Z,dZ-	 d dl.Z.d dl/Z.d dl0Z0dZ- G d de2      Z3d Z4d Z5d Z6d  Z7d! Z8d" Z9d# Z:d$ Z;dddd e8e$      ddddddddfd%Z<d2d&Z=d' Z>dd e8e$      ddfd(Z?ddd e8e$      fd)Z@d* ZAd+ddd e8e$      ddddf	d,ZBd- ZCd. ZDd/ ZEd0 ZFeGd1k(  r eF        yy# e1$ r dxZ.Z0Y w xY w)3    )annotationsa'  
---
module: apt
short_description: Manages apt-packages
description:
  - Manages I(apt) packages (such as for Debian/Ubuntu).
version_added: "0.0.2"
options:
  name:
    description:
      - A list of package names, like V(foo), or package specifier with version, like V(foo=1.0) or V(foo>=1.0).
        Name wildcards (fnmatch) like V(apt*) and version wildcards like V(foo=1.0*) are also supported.
      - Do not use single or double quotes around the version when referring to the package name with a specific version, such as V(foo=1.0) or V(foo>=1.0).
    aliases: [ package, pkg ]
    type: list
    elements: str
  state:
    description:
      - Indicates the desired package state. V(latest) ensures that the latest version is installed. V(build-dep) ensures the package build dependencies
        are installed. V(fixed) attempt to correct a system with broken dependencies in place.
    type: str
    default: present
    choices: [ absent, build-dep, latest, present, fixed ]
  update_cache:
    description:
      - Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as a separate step.
      - Default is not to update the cache.
    aliases: [ update-cache ]
    type: bool
  update_cache_retries:
    description:
      - Amount of retries if the cache update fails. Also see O(update_cache_retry_max_delay).
    type: int
    default: 5
    version_added: '2.10'
  update_cache_retry_max_delay:
    description:
      - Use an exponential backoff delay for each retry (see O(update_cache_retries)) up to this max delay in seconds.
    type: int
    default: 12
    version_added: '2.10'
  cache_valid_time:
    description:
      - Update the apt cache if it is older than the O(cache_valid_time). This option is set in seconds.
      - As of Ansible 2.4, if explicitly set, this sets O(update_cache=yes).
    type: int
    default: 0
  purge:
    description:
     - Will force purging of configuration files if O(state=absent) or O(autoremove=yes).
    type: bool
    default: 'no'
  default_release:
    description:
      - Corresponds to the C(-t) option for I(apt) and sets pin priorities.
    aliases: [ default-release ]
    type: str
  install_recommends:
    description:
      - Corresponds to the C(--no-install-recommends) option for C(apt). V(true) installs recommended packages. V(false) does not install
        recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages are never installed.
    aliases: [ install-recommends ]
    type: bool
  force:
    description:
      - 'Corresponds to the C(--force-yes) to C(apt-get) and implies O(allow_unauthenticated=yes) and O(allow_downgrade=yes).'
      - "This option will disable checking both the packages' signatures and the certificates of the web servers they are downloaded from."
      - 'This option *is not* the equivalent of passing the C(-f) flag to C(apt-get) on the command line.'
      - '**This is a destructive operation with the potential to destroy your system, and it should almost never be used.**
         Please also see C(man apt-get) for more information.'
    type: bool
    default: 'no'
  clean:
    description:
      - Run the equivalent of C(apt-get clean) to clear out the local repository of retrieved package files. It removes everything but
        the lock file from C(/var/cache/apt/archives/) and C(/var/cache/apt/archives/partial/).
      - Can be run as part of the package installation (clean runs before install) or as a separate step.
    type: bool
    default: 'no'
    version_added: "2.13"
  allow_unauthenticated:
    description:
      - Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup.
      - 'O(allow_unauthenticated) is only supported with O(state): V(install)/V(present).'
    aliases: [ allow-unauthenticated ]
    type: bool
    default: 'no'
    version_added: "2.1"
  allow_downgrade:
    description:
      - Corresponds to the C(--allow-downgrades) option for I(apt).
      - This option enables the named package and version to replace an already installed higher version of that package.
      - Note that setting O(allow_downgrade=true) can make this module behave in a non-idempotent way.
      - (The task could end up with a set of packages that does not match the complete list of specified packages to install).
      - 'O(allow_downgrade) is only supported by C(apt) and will be ignored if C(aptitude) is detected or specified.'
    aliases: [ allow-downgrade, allow_downgrades, allow-downgrades ]
    type: bool
    default: 'no'
    version_added: "2.12"
  allow_change_held_packages:
    description:
      - Allows changing the version of a package which is on the apt hold list.
    type: bool
    default: 'no'
    version_added: '2.13'
  upgrade:
    description:
      - If yes or safe, performs an aptitude safe-upgrade.
      - If full, performs an aptitude full-upgrade.
      - If dist, performs an apt-get dist-upgrade.
      - 'Note: This does not upgrade a specific package, use state=latest for that.'
      - 'Note: Since 2.4, apt-get is used as a fall-back if aptitude is not present.'
    version_added: "1.1"
    choices: [ dist, full, 'no', safe, 'yes' ]
    default: 'no'
    type: str
  dpkg_options:
    description:
      - Add C(dpkg) options to C(apt) command. Defaults to C(-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold").
      - Options should be supplied as comma separated list.
    default: force-confdef,force-confold
    type: str
  deb:
     description:
       - Path to a .deb package on the remote machine.
       - If C(://) in the path, ansible will attempt to download deb before installing. (Version added 2.1)
       - Requires the C(xz-utils) package to extract the control file of the deb package to install.
     type: path
     required: false
     version_added: "1.6"
  autoremove:
    description:
      - If V(true), remove unused dependency packages for all module states except V(build-dep). It can also be used as the only option.
      - Previous to version 2.4, O(autoclean) was also an alias for O(autoremove), now it is its own separate command.
        See documentation for further information.
    type: bool
    default: 'no'
    version_added: "2.1"
  autoclean:
    description:
      - If V(true), cleans the local repository of retrieved package files that can no longer be downloaded.
    type: bool
    default: 'no'
    version_added: "2.4"
  policy_rc_d:
    description:
      - Force the exit code of C(/usr/sbin/policy-rc.d).
      - For example, if O(policy_rc_d=101) the installed package will not trigger a service start.
      - If C(/usr/sbin/policy-rc.d) already exists, it is backed up and restored after the package installation.
      - If V(null), the C(/usr/sbin/policy-rc.d) is not created/changed.
    type: int
    default: null
    version_added: "2.8"
  only_upgrade:
    description:
      - Only upgrade a package if it is already installed.
    type: bool
    default: 'no'
    version_added: "2.1"
  fail_on_autoremove:
    description:
      - 'Corresponds to the C(--no-remove) option for C(apt).'
      - 'If V(true), it is ensured that no packages will be removed or the task will fail.'
      - 'O(fail_on_autoremove) is only supported with O(state) except V(absent).'
      - 'O(fail_on_autoremove) is only supported by C(apt) and will be ignored if C(aptitude) is detected or specified.'
    type: bool
    default: 'no'
    version_added: "2.11"
  force_apt_get:
    description:
      - Force usage of apt-get instead of aptitude.
    type: bool
    default: 'no'
    version_added: "2.4"
  lock_timeout:
    description:
      - How many seconds will this action wait to acquire a lock on the apt db.
      - Sometimes there is a transitory lock and this will retry at least until timeout is hit.
    type: int
    default: 60
    version_added: "2.12"
requirements:
   - python-apt (python 2)
   - python3-apt (python 3)
   - aptitude (before 2.4)
author: "Matthew Williams (@mgwilliams)"
extends_documentation_fragment: action_common_attributes
attributes:
    check_mode:
        support: full
    diff_mode:
        support: full
    platform:
        platforms: debian
notes:
   - Three of the upgrade modes (V(full), V(safe) and its alias V(true)) required C(aptitude) up to 2.3, since 2.4 C(apt-get) is used as a fall-back.
   - In most cases, packages installed with I(apt) will start newly installed services by default. Most distributions have mechanisms to avoid this.
     For example when installing Postgresql-9.5 in Debian 9, creating an executable shell script (/usr/sbin/policy-rc.d) that throws
     a return code of 101 will stop Postgresql 9.5 starting up after install. Remove the file or its execute permission afterward.
   - The C(apt-get) commandline supports implicit regex matches here but we do not because it can let typos through easier
     (If you typo C(foo) as C(fo) apt-get would install packages that have "fo" in their name with a warning and a prompt for the user.
     Since there are no warnings and prompts before installing, we disallow this. Use an explicit fnmatch pattern if you want wildcarding).
   - When used with a C(loop:) each package will be processed individually, it is much more efficient to pass the list directly to the O(name) option.
   - When O(default_release) is used, an implicit priority of 990 is used. This is the same behavior as C(apt-get -t).
   - When an exact version is specified, an implicit priority of 1001 is used.
   - If the interpreter can't import C(python-apt)/C(python3-apt) the module will check for it in system-owned interpreters as well.
     If the dependency can't be found, the module will attempt to install it.
     If the dependency is found or installed, the module will be respawned under the correct interpreter.
a
  
- name: Install apache httpd (state=present is optional)
  ansible.builtin.apt:
    name: apache2
    state: present

- name: Update repositories cache and install "foo" package
  ansible.builtin.apt:
    name: foo
    update_cache: yes

- name: Remove "foo" package
  ansible.builtin.apt:
    name: foo
    state: absent

- name: Install the package "foo"
  ansible.builtin.apt:
    name: foo

- name: Install a list of packages
  ansible.builtin.apt:
    pkg:
    - foo
    - foo-tools

- name: Install the version '1.00' of package "foo"
  ansible.builtin.apt:
    name: foo=1.00

- name: Update the repository cache and update package "nginx" to latest version using default release squeeze-backport
  ansible.builtin.apt:
    name: nginx
    state: latest
    default_release: squeeze-backports
    update_cache: yes

- name: Install the version '1.18.0' of package "nginx" and allow potential downgrades
  ansible.builtin.apt:
    name: nginx=1.18.0
    state: present
    allow_downgrade: yes

- name: Install zfsutils-linux with ensuring conflicted packages (e.g. zfs-fuse) will not be removed.
  ansible.builtin.apt:
    name: zfsutils-linux
    state: latest
    fail_on_autoremove: yes

- name: Install latest version of "openjdk-6-jdk" ignoring "install-recommends"
  ansible.builtin.apt:
    name: openjdk-6-jdk
    state: latest
    install_recommends: no

- name: Update all packages to their latest version
  ansible.builtin.apt:
    name: "*"
    state: latest

- name: Upgrade the OS (apt-get dist-upgrade)
  ansible.builtin.apt:
    upgrade: dist

- name: Run the equivalent of "apt-get update" as a separate step
  ansible.builtin.apt:
    update_cache: yes

- name: Only run "update_cache=yes" if the last one is more than 3600 seconds ago
  ansible.builtin.apt:
    update_cache: yes
    cache_valid_time: 3600

- name: Pass options to dpkg on run
  ansible.builtin.apt:
    upgrade: dist
    update_cache: yes
    dpkg_options: 'force-confold,force-confdef'

- name: Install a .deb package
  ansible.builtin.apt:
    deb: /tmp/mypackage.deb

- name: Install the build dependencies for package "foo"
  ansible.builtin.apt:
    pkg: foo
    state: build-dep

- name: Install a .deb package from the internet
  ansible.builtin.apt:
    deb: https://example.com/python-ppq_0.1-1_all.deb

- name: Remove useless packages from the cache
  ansible.builtin.apt:
    autoclean: yes

- name: Remove dependencies that are no longer required
  ansible.builtin.apt:
    autoremove: yes

- name: Remove dependencies that are no longer required and purge their configuration files
  ansible.builtin.apt:
    autoremove: yes
    purge: true

- name: Run the equivalent of "apt-get clean" as a separate step
  ansible.builtin.apt:
    clean: yes
aP  
cache_updated:
    description: if the cache was updated or not
    returned: success, in some cases
    type: bool
    sample: True
cache_update_time:
    description: time of the last cache update (0 if unknown)
    returned: success, in some cases
    type: int
    sample: 1425828348000
stdout:
    description: output from apt
    returned: success, when needed
    type: str
    sample: |-
        Reading package lists...
        Building dependency tree...
        Reading state information...
        The following extra packages will be installed:
          apache2-bin ...
stderr:
    description: error output from apt
    returned: success, when needed
    type: str
    sample: "AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to ..."
Nignorezapt API not stable yet)AnsibleModule)S_IRWXU_RXG_RXO)get_best_parsable_locale)has_respawnedprobe_interpreters_for_modulerespawn_module)	to_nativeto_text)string_types)
fetch_filezforce-confdef,force-confoldz+
0 upgraded, 0 newly installed, 0 to removez4
0 packages upgraded, 0 newly installed, 0 to removez/var/lib/apt/listsz*/var/lib/apt/periodic/update-success-stampzInvalid operationz8Usage: apt-mark [options] {markauto|unmarkauto} packagesz&The following packages will be REMOVEDzDel )
autoremove	autocleanFTc                  "    e Zd ZdZd Zd Zd Zy)	PolicyRcDa   
    This class is a context manager for the /usr/sbin/policy-rc.d file.
    It allow the user to prevent dpkg to start the corresponding service when installing
    a package.
    https://people.debian.org/~hmh/invokerc.d-policyrc.d-specification.txt
    c                    || _         | j                   j                  d   y t        j                  j	                  d      rt        j                  d      | _        y d | _        y )Npolicy_rc_d/usr/sbin/policy-rc.dansible)prefix)mparamsospathexiststempfilemkdtemp
backup_dir)selfmodules     C/home/dcms/DCMS/lib/python3.12/site-packages/ansible/modules/apt.py__init__zPolicyRcD.__init__  sM     66=='/
 77>>12&..i@DO"DO    c                &   | j                   j                  d   y| j                  r!	 t        j                  d| j                         	 t        dd      5 }|j                  d| j                   j                  d   z         ddd       t        j                  dt               y# t
        $ r, | j                   j                  d| j                  z         Y w xY w# 1 sw Y   \xY w# t
        $ r | j                   j                  d       Y yw xY w)	ud   
        This method will be called when we enter the context, before we call `apt-get …`
        r   Nr   z(Fail to move /usr/sbin/policy-rc.d to %smsgwz#!/bin/sh
exit %d
z/Failed to create or chmod /usr/sbin/policy-rc.d)r   r   r   shutilmove	Exception	fail_jsonopenwriter   chmodr   )r    r   s     r"   	__enter__zPolicyRcD.__enter__  s     66=='/ ??c3T__E
	T-s3 Y{!!"8466==;W"WXY HH,o>  c  %ORVRaRa%a bc
Y Y  	TFF!RS	Ts;    B$ 	C( ,C"C( $2CCC%!C( (%DDc                <   | j                   j                  d   y| j                  r_	 t        j                  t
        j                  j                  | j                  d      d       t        j                  | j                         y	 t        j                  d       y# t        $ rJ | j                   j                  dt
        j                  j                  | j                  d      z         Y yw xY w# t        $ r | j                   j                  d       Y yw xY w)ub   
        This method will be called when we exit the context, after `apt-get …` is done
        r   Nzpolicy-rc.dr   z-Fail to move back %s to /usr/sbin/policy-rc.dr&   zAFail to remove /usr/sbin/policy-rc.d (after package manipulation))r   r   r   r)   r*   r   r   joinrmdirr+   r,   remove)r    typevalue	tracebacks       r"   __exit__zPolicyRcD.__exit__  s     66=='/??UBGGLL-H35)j		12  U  %T')ww||DOO]'S&T  UU  j  %h ijs%   AB C3 AC0/C03%DDN)__name__
__module____qualname____doc__r#   r0   r8    r$   r"   r   r     s    # T2jr$   r   c                `    t        j                  d| d      }t        |      dkD  r|S |d   d d fS )Nz(>?=)   r   )resplitlen)pkgspecpartss     r"   package_splitrE     s5    HHXw*E
5zA~8T4r$   c                z    	 t        j                  | |      S # t        $ r t        j                  | |      cY S w xY w)N)apt_pkgversion_compareAttributeErrorVersionCompare)versionother_versions     r"   package_version_comparerM     s<    >&&w>> >%%g}==>s    ::c                   t        j                  |      }|j                  t         j                  j	                  d             |j                  t         j                  j	                  d             |r|j                  d| |d       |dk(  r|j                  d| |d       ||    }|j                  |      }|sy |dk(  r!t        j                  |j                  |      sy |j                  S )NzDir::Etc::preferenceszDir::Etc::preferencespartsReleasei  =Versioni  )
rG   Policyread_pinfileconfig	find_fileread_pindir
create_pinget_candidate_verfnmatchver_str)pkgnameversion_cmprK   releasecachepolicypkgpkgvers           r"   package_best_matchrb     s    ^^E"F
001HIJ
w~~//0LMN)Wgs;c 	)Wgt<
.C%%c*Fc'//&..'"J >>r$   c           
     R   	 ||   }|j                   |   }	 t	        j                        dkD  }	 j                  t        j                  k(  }t!        |||||j                         }d
}d}|r	 j"                  j$                  }|dk(  r6t)        j(                  ||      }|rm||k7  rht)        j(                  ||      rR|}nO|dk(  r<t        j*                  ||      dk\  }|r/||k7  r*t        j*                  ||      dk\  r|}nd	}|r
||k7  r|}n|}||||fS # t        $ r |dk(  r	 |j                  |      }	|	rQ|j                  |      r>t	        |	      dk(  r0|	d   }
t        | |
j                  ||||d      \  }}}}|r||||fcY S Y y| j                  d|z         n# t        $ r Y Y yw xY wY yY w xY w# t        $ r d	}Y t        $ r d
}Y w xY w# t        $ r- 	 j                  }n# t        $ r j                  }Y nw xY wY w xY w# t        $ r j&                  }Y w xY w)aR  
    :return: A tuple of (installed, installed_version, version_installable, has_files). *installed* indicates whether
    the package (regardless of version) is installed. *installed_version* indicates whether the installed package
    matches the provided version criteria. *version_installable* provides the latest matching version that can be
    installed. In the case of virtual packages where we can't determine an applicable match, True is returned.
    *has_files* indicates whether the package has files on the filesystem (even if not installed, meaning a purge is
    required).
    installr?   r   state)FFTFz%No package matching '%s' is availabler&   )FFNFTFNrP   z>=)_cacheKeyErrorget_providing_packagesis_virtual_packagerB   package_statusnamer,   rI   installed_filesUnicodeDecodeErrorcurrent_staterG   CURSTATE_INSTALLEDis_installedisInstalledrb   	installedrK   installedVersionrY   rH   )r   r[   r\   rK   default_releaser^   rf   r`   ll_pkgprovided_packagespackagers   installed_versionversion_installable	has_filespackage_is_installedversion_bestversion_is_installeds                     r"   rk   rk     s    -
 Gng&6++,q0	3%33w7Q7QQ &g{G_V[VbVbcL 	5 # 5 5 ##*??3Dg#N  1\ AgooVbdkFl&2#D #*#:#:;Lg#VZ[#[  1\ AgF]F]^jlsFtxyFy&2##'  1\ A&2#*!57JIUUI  -I1$)$@$@$I!$ //8SAR=SWX=X"3A"6*1gllKRachpyz U	#46I9$#,.?ATV_#__ 5 G' QR! 1 11
 - S'-8  	 	
  3	3#&#3#3  	3#&?? 	3	3  	5 # 4 4	5s   D F5 G -H F2"AFF2FF2	F)%F2(F))F21F25G
GG	H
G+*H
+H H
HH
	H
H&%H&c                f    | j                  d      }d}|D ]
  }|d|d} |j                         S )N, z -o "Dpkg::Options::=--")rA   strip)dpkg_options_compressedoptions_listdpkg_optionsdpkg_options       r"   expand_dpkg_optionsr   b  sC    *005LL# 5&55 r$   c                v   g }|r|D ]  }t        |t              s| j                  dt        |      z         t	        |      \  }}}t        d      j                  |      rTd|vr	 }	n	 }	t        j                  |	|      }|s| j                  dt        |      z         |j                  |       |j                  |        |S # t        $ r4 |D 
cg c]  }
d|
j                  vs|
j                   nc c}
w c}
x}	}Y w xY w# t        $ r% |D 
cg c]  }
|
j                   nc c}
w c}
x}	}Y w xY w)Nz9Invalid type for package name, expected string but got %sr&   z*?[]!:z%No package(s) matching '%s' available)
isinstancer   r,   r5   rE   	frozensetintersection	NameErrorrl   rY   filterr   extendappend)r   rC   r^   new_pkgspecpkgspec_patternpkgname_patternr\   rK   _non_multiarchpkg_name_cacher`   _all_pkg_namesmatchess                r"   expand_pkgspec_from_fnmatchesr   k  sI    K&  	4Oo|< [^bcr^s st4A/4R1O[' !..? o-m)7
V)7 "..IKK$KgVeNf$fKg&&w/ ""?3A 	4B % % mOT:lX[cfckckXk388:l:llm % VOT:U388:U:UUVsB   &C
*D

DC:+C:9DD
D8D+*D87D8c                j   t        |       j                         }	 |j                  d      }	 t	        d t        |      D              }|dz  }|dz  }ddj                  |||       iS # t        $ r' 	 |j                  d      }n# t        $ r d}Y nw xY wY kw xY w# t        $ r t        |      }Y iw xY w)NzResolving dependencies...zReading state information...c              3  T   K   | ]   \  }}t        j                  d |      s| " yw)z[0-9]+ (packages )?upgradedN)r@   match).0iitems      r"   	<genexpr>zparse_diff.<locals>.<genexpr>  s#     jgaBHHEbdh<ijs   ((r?   prepared
)	r   
splitlinesindex
ValueErrornext	enumerateStopIterationrB   r2   )outputdiff
diff_startdiff_ends       r"   
parse_diffr     s    V'')D	ZZ ;<
j4jj !OJMH		$z(";<==  	$BCJ 	J		  t9sF   A( B (	B2BBBBBBBB21B2c                b   |sy | j                  d      }|| j                  d       y |ddj                  |      }| j                  |      \  }}}t        |v st
        |v r+|ddj                  |      }| j                  |      \  }}}|dk7  r| j                  d|d||||	       y y )
Nzapt-markzMCould not find apt-mark binary, not marking package(s) as manually installed.z manual  z unmarkauto r   '
' failed: r'   stdoutstderrrc)get_bin_pathwarnr2   run_commandAPT_MARK_INVALID_OPAPT_MARK_INVALID_OP_DEB6r,   )r   packagesapt_mark_cmd_pathcmdr   outerrs          r"   mark_installed_manuallyr     s    z2  	^_-sxx/A
BC==%LBSc!%=%D$5sxx7IJ}}S)C	Qw	S#6s3SUV r$   c                   g }d}t        | ||      }g }|D ]  }|r|j                  d|z         t        |      \  }}}|j                  |       t        | |||||d      \  }}}}|s|rV|s|sd}t	        d|z        }||fc S |rU|s|r|s|sM|dur|j                  d	|d
|d	       |r|j                  d	|d
|d	       |j                  d|z         |s|s|d
k(  s|j                  d	|d
|d	        dj                  |      }|r!|rd}nd}| j                  rd}nd}|
rd}
nd}
|rd}nd}|rd}nd}|	rd}	nd}	|rt        d|d|d|	d|d|d|d|}n t        d|d|d|	d|d|
d|d|d|}|r	|d|d	z  }|du r|dz  }n	|du r|dz  }|r|dz  }|r|dz  }|r|dz  }t        |       5  | j                  |      \  } }!}"d d d        | j                  rt        !      }#ni }#d}d}$|rt        !v}$t	        |$!"|#      } r&d}t	        d	|d|"|!|"|       }nd}t	        d      }|s| j                  st        | |       ||fS # 1 sw Y   xY w)Nr   '%s'rd   re   Fz*no available installation candidate for %sr&   Tr   rP   r   --force-yes
--simulate--auto-remove--no-removez--only-upgradez--fix-broken -y z build-dep z	 install  -t 'z -o APT::Install-Recommends=noz -o APT::Install-Recommends=yesz --allow-unauthenticatedz --allow-downgradesz --allow-change-held-packageschangedr   r   r   r   r   r   )r   r   rE   rk   dictr2   
check_modeAPT_GET_CMDr   r   _diffr   APT_GET_ZEROr   )%r   rC   r^   upgraderu   install_recommendsforcer   	build_depfixedr   fail_on_autoremoveonly_upgradeallow_unauthenticatedallow_downgradeallow_change_held_packagespkg_listr   package_namesrx   rl   r\   rK   rs   ry   rz   r{   statusdata	force_yes	check_argr   r   r   r   r   r   s%                                        r"   rd   rd     s   
 HH+Aw>GM "9OOFW,-%27%;"k7T"GUVWY]_jls  vE  GL  T]  H^D	$&99\  )<FH7RSDD>!<G[l"$.T3F GHT7 ;<.#6;#;M OOw78E"9F xx!H%II<<$II(JJ!.!#+LL"EE<GWcejlu  xJ  LU  W_  `C lE9jZlnw  zBCC 22C&33C4'44C !--C((C%22Cq\ 	.==-LBS	. 77c?DD"#-GGC$GFc:3sWYZDE"Q\\=1D>1	. 	.s   
I%%I.c                    | j                  dd      }|d|d|z   }| j                  |      \  }}}|dk7  r| j                  d|z  ||       t        |      j	                  d      S )	NdpkgTz	 --field r   r   	%s failedr'   r   r   r   )r   r   r,   r   r   )r   deb_filefieldcmd_dpkgr   r   r   r   s           r"   get_field_of_debr   F  sj    ~~fd+H
59
9Cs+B	Qw	c)&HV""4((r$   c
                4   d}
g }g }|j                  d      D ]  }	 t        j                  j                  |t        j                               }t        | |d      }t        | |d      }t        t        d      r5t        t        j                               dkD  rt        | |d      }|d	|}n|}	 t        j                         |   }|j                  j                  }t        ||      d
k(  r	 |j                         s/|sd|j                  v r|rn| j!                  |j                         |j#                  |j$                         |rHt        | |d      }|j#                  |j                         D cg c]  }|j)                          c}       |j+                  |        i }|rFt-        | |||||||t/        |	      	      \  }}|s | j                   d!i | |j1                  dd      }
|rdj3                  |	j                  d      D cg c]  }d|z  	 c}      }| j4                  r|dz  }|r|dz  }d|ddj3                  |      }t7        |       5  | j9                  |      \  }}}d d d        d|v r	|d   z   }n}d|v r|d   } d| v r| dxx   d|z   z  cc<   nt;        |      } d|v r	|d   z   }!n}!d
k(  r| j=                  d||!|        y | j!                  d|z  ||!       y | j=                  |
|j1                  dd       |j1                  dd       |j1                  dd              y # t        $ r Y Zw xY w# t        $ r)}| j!                  dt'        |      z         Y d }~1d }~ww xY wc c}w c c}w # 1 sw Y   xY w)"NFr   )r^   PackagerQ   get_architecturesr?   Architecturer   r   zlater versionr&   zUnable to install package: %s
Recommends)	r   rC   r^   r   r   r   r   r   r   r   r   z--%sz --simulatez --force-allzdpkg z -i r   r   r   z

r   Tr   r   r   r   r=   )rA   aptdebfile
DebPackageCacher   hasattrrG   rB   r   rs   rK   rM   r+   check_failure_stringr,   r   missing_depsr   r   r   rd   r   getr2   r   r   r   r   	exit_json)"r   debsr^   r   r   r   r   r   r   r   r   deps_to_installpkgs_to_installr   r`   pkg_namepkg_versionpkg_archpkg_keyinstalled_pkgry   epkg_recommendsretvalssuccessxoptionsr   r   r   r   r   r   r   s"                                     r"   install_debr  O  s    GOOJJsO ')	L++(((EC'8Y?H*1h	BKw 34W=V=V=X9Y\]9]+AxH%-x8" #		G 4$1$;$;$C$C!*;8IJaO P 99;_0C0CCKKC$7$7K8 ""3#3#34 -a<HN""^EYEYE[#\HNN$4#\] 	x(O')T G$q/8J8J;P5D@Z2El2SU' AKK"'"++i/((0B0B30GH1FQJHI<<}$G~%G!(#((?*CDq\ 	.==-LBS	. wX&,FFW6?DT!Z FSL0 c?DwX&,FF7KKVFKNKKK#-fVKL	GGKK",EgkkZbdfNgnunyny  {A  CE  oF  	GO    	LKK;ilJKKK	L $]( I	. 	.sU   BM2<L>/AM6N
N N>	MM
MM	N M;;N Nc                   g }t        | ||      }|D ]D  }	t        |	      \  }
}}t        | |
||d |d      \  }}}}|s|s.|s1|j                  d|	z         F dj	                  |      }|s| j                  d       y |rd}nd}|rd	}nd}|rd
}nd}| j                  rd}nd}|rd}nd}t        d|d|d|d|d|d|d|}t        |       5  | j                  |      \  }}}d d d        | j                  rt              }ni }r| j                  d|d||       | j                  d|       y # 1 sw Y   VxY w)Nr4   re   r   r   Fr   r   r   --purger   r   z--allow-change-held-packagesz -q -y z remove z'apt-get remove r   r   Tr   )r   rE   rk   r   r2   r   r   r   r   r   r   r   r,   )r   rC   r^   purger   r   r   r   r   rx   rl   r\   rK   rs   ry   
upgradabler{   r   r   r   r   r   r   r   r   s                            r"   r4   r4     s    H+Aw>G .%27%;"k7>LQPTVacjlprw  @H  ?I;	$j)uOOFW,-	.
 xx!H	E"%IIEE(JJ<<$II%)G&)+& &	
 q\ 	.==-LBS	. 77c?DDKK#NWZcfkmKn	DStD	. 	.s   D??Ec                   |t        ddg      vrt        d|z        |rd}nd}|rd}nd}| j                  rd}nd}t        d|d	|d	|d	|d	|}t	        |       5  | j                  |      \  }}	}
d d d        | j                  rt        	      }ni }r| j                  d
|d
	|
|       t        |   	v }| j                  ||	
|       y # 1 sw Y   axY w)Nr   r   z>Expected "autoremove" or "autoclean" cleanup operation, got %sr   r   r	  r   r   r   z	'apt-get r   r   r   )r   AssertionErrorr   r   r   r   r   r   r,   CLEAN_OP_CHANGED_STRr   )r   r
  r   	operationr   r   r   r   r   r   r   r   r   s                r"   cleanupr    s     	<"=>>]`iijj!		|| 		$/uiQZ\e
fC	1 *}}S)C* 	ww#		YDSY\acd"9-4GKKCdKC* *s   CCc                    | j                  ddg      \  }}}| j                  rt        |      ni }|r| j                  d||       |r| j                  d|z  ||       |||fS )Napt-getcleanzapt-get clean failedr'   r   r   zapt-get clean failed: %s)r   r   r   r,   )r   clean_rc	clean_out	clean_err
clean_diffs        r"   aptcleanr    sm    %&]]Iw3G%H"Hi*+''I&rJ	.yXN	2Y>yU]^y*--r$   yesc
                   |rd}nd}| j                   rd}
nd}
d }d }|dk(  s|dk(  r|rt        }d|z  }n(|dk(  r|s	t        }d}n|rt        }d|z  }n
t        }d	}d
}|r|t        k(  rd}nd}nd}|r |t        k(  rd}n| j                  d       d}nd}|rdnd}|	r |t        k(  rd}	n| j                  d       d}	nd}	||rt        }n| j	                  d       | j                  |d      }|d|d|d|d|d|	d|
d|}|r	|d|dz  }t        |       5  | j                  ||      \  }}}d d d        | j                  rt              }ni }r| j	                  d|d|d|       |t        k(  rt        v s|t        k(  rt        v r| j                  d||       | j                  d||       y # 1 sw Y   xY w) Nr   r   r   distfullzdist-upgrade %szfull-upgradezupgrade --with-new-pkgs %szsafe-upgradezR(^Do you want to ignore this warning and proceed anyway\?|^\*\*\*.*\[default=.*\])r   z--assume-yes --allow-untrustedr   zUAPTITUDE does not support '--no-remove', ignoring the 'fail_on_autoremove' parameter.z--allow-unauthenticatedz--allow-downgradeszYAPTITUDE does not support '--allow-downgrades', ignoring the 'allow_downgrade' parameter.zfUnable to find APTITUDE in path. Please make sure to have APTITUDE in path or use 'force_apt_get=True'r&   T)requiredr   r   r   r   )prompt_regexr   r  F)r   r'   r   r   r   r'   r   r   r   )r   r   APTITUDE_CMDr   r,   r   r   r   r   r   r   APTITUDE_ZEROr   )r   moder   ru   use_apt_getr   r   r   r   r   r   apt_cmdr  upgrade_commandr   apt_cmd_pathr   r   r   r   r   s                        r"   r   r   #  s    $

|| 		GLv~$&.[+z:	(!G:jIO #G,OpLk!%I8I	k!!.FFjk!#9N5TVk!2OFFno O!GKK SK T>>'D>9L 		C _..	1 E}}S|}DCE 	ww#		#NWZ_ab;<3#6G|<SXeilXl	Es3sCKK#c#DKIE Es   GGc                 &   d} t         j                  j                  t              r%t        j                  t              j
                  } | S t         j                  j                  t              r#t        j                  t              j
                  } | S )zReturn mtime of a valid apt cache file.
    Stat the apt cache file and if no cache file is found return 0
    :returns: ``int``
    r   )r   r   r   APT_UPDATE_SUCCESS_STAMP_PATHstatst_mtimeAPT_LISTS_PATH)
cache_times    r"   get_cache_mtimer.    sc    
 J	ww~~34WW:;DD
  
	'WW^,55
r$   c                     t               } t        j                  j                  |       }t        t	        j
                  |j                                     }||fS )zReturn the mtime time stamp and the updated cache time.
    Always retrieve the mtime of the apt cache or set the `cache_mtime`
    variable to 0
    :returns: ``tuple``
    )r.  datetimefromtimestampinttimemktime	timetuple)cache_mtime
mtimestampupdated_cache_times      r"   get_updated_cache_timer9    sK     "#K""00=JT[[)=)=)?@A)))r$   c                   d}	 t        j                         }|S # t        $ r}dt        |      j	                         v rnd}|dk  r(| j                  g d      \  }}}|dz  }|dk(  rn|dk  r(dk7  r%| j                  dt        |      dz   |	       t        j                         }n| j                  t        |      
       Y d}~|S d}~ww xY w)z8Attempt to get the cache object and update till it worksNz/var/lib/apt/lists/r      )r  update-qr?   z<Updating the cache to correct corrupt package lists failed:
r   )r'   r   r&   )r   r   SystemErrorr   lowerr   r,   )r!   r^   r  retriesr   soses          r"   	get_cacherC    s    E/		  L  / IaL$6$6$88GA+%112MNR17	 A+
 Qw  nwxynz|~  BD  }D  &E  JL   MIIKE1.L/s    	CA	C-ACCc                    t        t        ddi dt        ddg d      dt        ddg	      d
t        dd      dt        dd      dt        dd      dt        dd      dt        ddddg      dt        d      dt        ddg	      dt        ddg	      d t        dd      d!t        dg d"d#$      d%t        dt              d&t        dd      d't        dd      d(t        dd      d)t        dd       d*t        dd      d+t        dd      d,t        dd      d-t        ddd.g/      d0t        ddg d1/      d2t        dd      d3t        dd4      g d5gg d6gd78      } t        |       }t	        j
                  t        j                  |       t        d9d:|||||;      }|| _        | j                  d<d      a	| j                  d=      a
| j                  }|d   }t        |d%         }t        sqd>}t               r0| j                  d?j!                  |t"        j$                        @       dAdBg}t'        |dC      }|rt)        |       | j*                  r| j                  dD|z  @       | j                  j-                  d      du r| j/                  dE|z         n-| j/                  dF|z         | j1                  t        dGgd7H       t        dI|dJdK|g}	|du r|	j3                  dLdMg       n|d7u r|	j3                  dLdNg       | j1                  |	d7H       t'        |dC      }|rt)        |       n0| j                  d?j!                  |t"        j$                        @       |d,   d7u r7t5        |       \  }
}}|d   s#|d!   d#k(  r|d   s| j7                  d7|
|
||O       |d!   d#k(  rd |d!<   |d+   }|st        sd7}d}d}|d-   }|d0   }|d2   }|d&   }|d(   }|d'   }t9        j8                         |d3   z   }	 t;        |       }	 |d   r)	 |d   t<        j>                  dP<   |jE                  d Q       tG               \  }}d}|d   s|d   r2tH        jH                  jK                         }tI        jL                  |d   R      }||z   |k\  sdS}| j                  j-                  d
      }| j                  j-                  d      }tO        jP                  dT      dUz  }tS        |      D ]   }	 | j*                  s|jU                           n d]| d^|r|nd_ }"| j                  |"@       |jE                  d Q       tG               \  }}#| j*                  s||#k7  rd7}|#}|d   s|d!   s|d   s| j7                  |||`       |d    }$|d!   rte        | |d!   |$|d   ||||||
       |d   rN|d   dk7  r| j                  da@       db|d   v rtg        | |d         |d<   ti        | |d   ||||||$||d%   c
       |d   xs dd}%|%D &cg c]  }&|&dek7  s	|&jk                          }'}&de|%v }(|d   dfk(  })|)r-|(r+|'r| j                  dg@       te        | dh|$|d   ||||||
       |'r1|'D ],  }&|&jm                  di      dWkD  s| j                  dj|&z  @       . |'s*|rto        | |d   |$d'|k       |rto        | |d   |$d&|k       |d   dlv rzd}*d}+d},|d   dfk(  rd7}*|d   dmk(  rd7}+|d   dnk(  rd7},tq        | |'||*|d   ||$||+|,|||d*   |||o      \  }-}.||.dp<   ||.dq<   |-r | j6                  ddi |. n1 | j                  ddi |. n|d   drk(  rts        | |'||d   |$|||s       | j                  dv@       v# t@        $ r |d   t<        jB                  dP<   Y pw xY w# tV        jX                  jZ                  $ r0} | }| j/                  dV|dWz    dXt]        |        dY       Y d } ~ nd } ~ ww xY wdZ|z  |z   }!|!|kD  r||z   }!t9        j^                  |!       | j/                  d[ta        tc        |!             d\       Nc c}&w # tV        jX                  jt                  $ r=}/t9        j8                         |k  rY d }/~/|| j                  dt|/z  @       Y d }/~/4d }/~/wtV        jX                  jZ                  $ r }0| j                  du|0z  @       Y d }0~0od }0~0ww xY w)wNrf   strpresent)absent	build-depr   latestrF  )r5   defaultchoicesupdate_cacheboolzupdate-cache)r5   aliasesupdate_cache_retriesr2     )r5   rJ  update_cache_retry_max_delay   cache_valid_timer   r
  Frx   listr`   rl   )r5   elementsrN  debr   )r5   ru   zdefault-releaser   zinstall-recommendsr   r   )r  r  nosafer  rW  )r5   rK  rJ  r   r   r   r   r   r   force_apt_getr  r   zallow-unauthenticated)r5   rJ  rN  r   )zallow-downgradeallow_downgradeszallow-downgradesr   lock_timeout<   )rV  rx   r   )r   rV  rx   rL  r   T)argument_specmutually_exclusiverequired_one_ofsupports_check_modenoninteractivecritical)DEBIAN_FRONTENDDEBIAN_PRIORITYLANGLC_ALLLC_MESSAGESLC_CTYPELANGUAGEaptituder  zpython3-aptz+{0} must be installed and visible from {1}.r&   z/usr/bin/python3z/usr/bin/pythonr   zX%s must be installed to use check mode. If run normally this module can auto-install it.z=Auto-installing missing dependency without updating cache: %sz9Updating cache and auto-installing missing dependency: %sr<  )check_rcrd   z-yr=  z-ozAPT::Install-Recommends=nozAPT::Install-Recommends=yesr   zAPT::Default-Release)progress)secondsr   i  g     @@zFailed to update cache after r?   z retries due to z
, retryingr;  zSleeping for z6 seconds, before attempting to refresh the cache againz!Failed to update apt cache after z
 retries: zunknown reason)r   cache_updatedcache_update_timezdeb only supports state=presentz://)r   r   r   r   r   r   r   r=   *rI  zKunable to install additional packages when upgrading all installed packagesr  rP   zinvalid package spec: %s)r   r  r   )rI  rF  rH  r   rH  r   )r   ru   r   r   r   r   r   r   r   r   r   r   r   rn  ro  rG  )r   r   r   r   z.Failed to lock apt for exclusive operation: %sz%Could not fetch updated apt files: %szNUnexpected code path taken, we really should have exited before, this is a bug);r   r   DPKG_OPTIONSr   locale_module	setlocalerf  run_command_environ_updater   r!  r   r   r   HAS_PYTHON_APTr   r,   formatsys
executabler	   r
   r   r   r   r   r   r  r   r3  rC  rG   rT   rI   Configr-   r9  r0  now	timedeltasecrets	randbelowranger<  r   r^   FetchFailedExceptionr   sleepr2  roundr   r   r  r   countr  rd   r4   LockFailedException)1r!   localeAPT_ENV_VARSpr   r   apt_pkg_nameinterpretersinterpreterapt_pkg_cmdaptclean_stdoutaptclean_stderraptclean_diffr$  updated_cacher8  r   r   r   r   r   r   deadliner^   r7  rz  tdeltar   rO  rQ  	randomizeretryfetch_failed_excdelayr'   post_cache_update_timer   unfiltered_packagesrx   r   all_installedrI  state_upgradestate_builddepstate_fixedr  r  lockFailedExceptionfetchFailedExceptions1                                                    r"   mainr    s
    
E9>st
6N3CD
 "&5!!<
 *.5")E	

 "ua8
 FE2
 fuufoN
 &!
 !e6G5HI
  $:N9OP
 FE2
 e-R\`a
 5,?
 7
 6
   $?!
" %6#
$ 659%
& FE:'
( FE2)
* #'FELcKd"e+
, !fe  FA  B-
. (,'G/
0 5"51
4 ::TU ;FF &f-FM00&9("L )5F% &&z59L%%i0KA/0&q'89L %?!N!U!UVbdgdrdr!st*,=>3L%H;'  "TVb"c d
 ==^,5KKWZffgKKSVbbcX6F #I|T4V&&BCD4'&CDE 	;6 4L%H ;' !N!U!UVbdgdrdr!stzT:B6:J7- |) 4QuX#&&"   	|t)O$K|M56)*O!"#?!@<J/0+I yy{Q~..H  &!s	a"#R=>?P=QGNN#9: 

D
)-C-E*J* "M A&8$9''++-!++A6H4IJ!F*c1C+1==+<+<=S+T(39==3D3DEc3d0 ' 1 1$ 7& @I!&';!< 2	#)#4#4 %!	2( @@T?UU_&)s/?@B  ((S(1JJJ-9O9Q6J 6((,>BX,X(,)?& |AiL5$$ -&3*< %  '
I|iL'( &)# xW:*$$)J$KAeH$)&!E(;AeHFAeHe/A2G7Q,;"+@Rabcqart #$I,"4"7J]GgY\n]H]#66MwZ8+F-$$)v$w'( &)# ' SG}}S)A-((-G'-Q(RS FAgJi;eqrFAgJi<frszHH %!&#W:)$(MW:,%)NW:("&K#*)$%&7$8'9#!-,%)'9!">!2*?$3/I!$ ( ,9(/A+,$F$$/w/$F$$/w/7x'gJ#!-)/I	& 	mnw  & R=>?P=QGNN#9:R0  #yy== "2C"KK"?	{ K&&/0@&A%B*!N  !"U
Y 6 #??$@9$LE

5)mCe4E3FF|$}~h ^d yy,, 	iyy{X%!QTg!ghhyy-- 	a!HK_!_``	as   &a ,^ C	a ^6(C<a $
a/aAa C"a ^3/a 2^33a 6`&_>9a >`Aa c08b0b00 c0c++c0__main__)rQ   )H
__future__r   DOCUMENTATIONEXAMPLESRETURNwarningsfilterwarningsFutureWarningr0  rY   r  rr  r   r@   r|  r)   rw  r   r3  ansible.module_utils.basicr    ansible.module_utils.common.filer   "ansible.module_utils.common.localer   #ansible.module_utils.common.respawnr   r	   r
   +ansible.module_utils.common.text.convertersr   r   ansible.module_utils.sixr   ansible.module_utils.urlsr   rq  r   r"  r,  r)  r   r   r   r  ru  r   apt.debfilerG   ImportErrorobjectr   rE   rM   rb   rk   r   r   r   r   rd   r   r  r4   r  r  r   r.  r9  rC  r  r9   r=   r$   r"   <module>r     s   #Pdl\
:    ":M J    	 	   
   4 < G l l J 1 0,=G% L ) U 7  N
Jj JjZ >0TVn ,^>,W, (-d#5,\:5Uuch"'[`	}@)aGH %*+L9e&+<E~ %4,\:#DL. ,\:uaf"'!	bJJ
	*.Wot
 zF #  C's   D4 4	E ?E 