
    Vha                        d dl mZ dZdZdZd dl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 d
 Zd Zd Zd Zd Zedk(  r e        yy)    )annotationsa  
module: systemd_service
author:
    - Ansible Core Team
version_added: "2.2"
short_description:  Manage systemd units
description:
    - Controls systemd units (services, timers, and so on) on remote hosts.
    - M(ansible.builtin.systemd) is renamed to M(ansible.builtin.systemd_service) to better reflect the scope of the module.
      M(ansible.builtin.systemd) is kept as an alias for backward compatibility.
options:
    name:
        description:
            - Name of the unit. This parameter takes the name of exactly one unit to work with.
            - When no extension is given, it is implied to a C(.service) as systemd.
            - When using in a chroot environment you always need to specify the name of the unit with the extension. For example, C(crond.service).
        type: str
        aliases: [ service, unit ]
    state:
        description:
            - V(started)/V(stopped) are idempotent actions that will not run commands unless necessary.
              V(restarted) will always bounce the unit.
              V(reloaded) will always reload and if the service is not running at the moment of the reload, it is started.
            - If set, requires O(name).
        type: str
        choices: [ reloaded, restarted, started, stopped ]
    enabled:
        description:
            - Whether the unit should start on boot. At least one of O(state) and O(enabled) are required.
            - If set, requires O(name).
        type: bool
    force:
        description:
            - Whether to override existing symlinks.
        type: bool
        version_added: 2.6
    masked:
        description:
            - Whether the unit should be masked or not. A masked unit is impossible to start.
            - If set, requires O(name).
        type: bool
    daemon_reload:
        description:
            - Run C(daemon-reload) before doing any other operations, to make sure systemd has read any changes.
            - When set to V(true), runs C(daemon-reload) even if the module does not start or stop anything.
        type: bool
        default: no
        aliases: [ daemon-reload ]
    daemon_reexec:
        description:
            - Run daemon_reexec command before doing any other operations, the systemd manager will serialize the manager state.
        type: bool
        default: no
        aliases: [ daemon-reexec ]
        version_added: "2.8"
    scope:
        description:
            - Run C(systemctl) within a given service manager scope, either as the default system scope V(system),
              the current user's scope V(user), or the scope of all users V(global).
            - "For systemd to work with V(user), the executing user must have its own instance of dbus started and accessible (systemd requirement)."
            - "The user dbus process is normally started during normal login, but not during the run of Ansible tasks.
              Otherwise you will probably get a 'Failed to connect to bus: no such file or directory' error."
            - The user must have access, normally given via setting the C(XDG_RUNTIME_DIR) variable, see the example below.

        type: str
        choices: [ system, user, global ]
        default: system
        version_added: "2.7"
    no_block:
        description:
            - Do not synchronously wait for the requested operation to finish.
              Enqueued job will continue without Ansible blocking on its completion.
        type: bool
        default: no
        version_added: "2.3"
extends_documentation_fragment: action_common_attributes
attributes:
    check_mode:
        support: full
    diff_mode:
        support: none
    platform:
        platforms: posix
notes:
    - O(state), O(enabled), O(masked) requires O(name).
    - Before 2.4 you always required O(name).
    - Globs are not supported in name, in other words, C(postgres*.service).
    - The service names might vary by specific OS/distribution.
    - The order of execution when having multiple properties is to first enable/disable, then mask/unmask and then deal with the service state.
      It has been reported that C(systemctl) can behave differently depending on the order of operations if you do the same manually.
requirements:
    - A system managed by systemd.
a(  
- name: Make sure a service unit is running
  ansible.builtin.systemd_service:
    state: started
    name: httpd

- name: Stop service cron on debian, if running
  ansible.builtin.systemd_service:
    name: cron
    state: stopped

- name: Restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
  ansible.builtin.systemd_service:
    state: restarted
    daemon_reload: true
    name: crond

- name: Reload service httpd, in all cases
  ansible.builtin.systemd_service:
    name: httpd.service
    state: reloaded

- name: Enable service httpd and ensure it is not masked
  ansible.builtin.systemd_service:
    name: httpd
    enabled: true
    masked: no

- name: Enable a timer unit for dnf-automatic
  ansible.builtin.systemd_service:
    name: dnf-automatic.timer
    state: started
    enabled: true

- name: Just force systemd to reread configs (2.4 and above)
  ansible.builtin.systemd_service:
    daemon_reload: true

- name: Just force systemd to re-execute itself (2.8 and above)
  ansible.builtin.systemd_service:
    daemon_reexec: true

- name: Run a user service when XDG_RUNTIME_DIR is not set on remote login
  ansible.builtin.systemd_service:
    name: myservice
    state: started
    scope: user
  environment:
    XDG_RUNTIME_DIR: "/run/user/{{ myuid }}"
aB  
status:
    description: A dictionary with the key=value pairs returned from C(systemctl show).
    returned: success
    type: dict
    sample: {
            "ActiveEnterTimestamp": "Sun 2016-05-15 18:28:49 EDT",
            "ActiveEnterTimestampMonotonic": "8135942",
            "ActiveExitTimestampMonotonic": "0",
            "ActiveState": "active",
            "After": "auditd.service systemd-user-sessions.service time-sync.target systemd-journald.socket basic.target system.slice",
            "AllowIsolate": "no",
            "Before": "shutdown.target multi-user.target",
            "BlockIOAccounting": "no",
            "BlockIOWeight": "1000",
            "CPUAccounting": "no",
            "CPUSchedulingPolicy": "0",
            "CPUSchedulingPriority": "0",
            "CPUSchedulingResetOnFork": "no",
            "CPUShares": "1024",
            "CanIsolate": "no",
            "CanReload": "yes",
            "CanStart": "yes",
            "CanStop": "yes",
            "CapabilityBoundingSet": "18446744073709551615",
            "ConditionResult": "yes",
            "ConditionTimestamp": "Sun 2016-05-15 18:28:49 EDT",
            "ConditionTimestampMonotonic": "7902742",
            "Conflicts": "shutdown.target",
            "ControlGroup": "/system.slice/crond.service",
            "ControlPID": "0",
            "DefaultDependencies": "yes",
            "Delegate": "no",
            "Description": "Command Scheduler",
            "DevicePolicy": "auto",
            "EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)",
            "ExecMainCode": "0",
            "ExecMainExitTimestampMonotonic": "0",
            "ExecMainPID": "595",
            "ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT",
            "ExecMainStartTimestampMonotonic": "8134990",
            "ExecMainStatus": "0",
            "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
            "ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
            "FragmentPath": "/usr/lib/systemd/system/crond.service",
            "GuessMainPID": "yes",
            "IOScheduling": "0",
            "Id": "crond.service",
            "IgnoreOnIsolate": "no",
            "IgnoreOnSnapshot": "no",
            "IgnoreSIGPIPE": "yes",
            "InactiveEnterTimestampMonotonic": "0",
            "InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT",
            "InactiveExitTimestampMonotonic": "8135942",
            "JobTimeoutUSec": "0",
            "KillMode": "process",
            "KillSignal": "15",
            "LimitAS": "18446744073709551615",
            "LimitCORE": "18446744073709551615",
            "LimitCPU": "18446744073709551615",
            "LimitDATA": "18446744073709551615",
            "LimitFSIZE": "18446744073709551615",
            "LimitLOCKS": "18446744073709551615",
            "LimitMEMLOCK": "65536",
            "LimitMSGQUEUE": "819200",
            "LimitNICE": "0",
            "LimitNOFILE": "4096",
            "LimitNPROC": "3902",
            "LimitRSS": "18446744073709551615",
            "LimitRTPRIO": "0",
            "LimitRTTIME": "18446744073709551615",
            "LimitSIGPENDING": "3902",
            "LimitSTACK": "18446744073709551615",
            "LoadState": "loaded",
            "MainPID": "595",
            "MemoryAccounting": "no",
            "MemoryLimit": "18446744073709551615",
            "MountFlags": "0",
            "Names": "crond.service",
            "NeedDaemonReload": "no",
            "Nice": "0",
            "NoNewPrivileges": "no",
            "NonBlocking": "no",
            "NotifyAccess": "none",
            "OOMScoreAdjust": "0",
            "OnFailureIsolate": "no",
            "PermissionsStartOnly": "no",
            "PrivateNetwork": "no",
            "PrivateTmp": "no",
            "RefuseManualStart": "no",
            "RefuseManualStop": "no",
            "RemainAfterExit": "no",
            "Requires": "basic.target",
            "Restart": "no",
            "RestartUSec": "100ms",
            "Result": "success",
            "RootDirectoryStartOnly": "no",
            "SameProcessGroup": "no",
            "SecureBits": "0",
            "SendSIGHUP": "no",
            "SendSIGKILL": "yes",
            "Slice": "system.slice",
            "StandardError": "inherit",
            "StandardInput": "null",
            "StandardOutput": "journal",
            "StartLimitAction": "none",
            "StartLimitBurst": "5",
            "StartLimitInterval": "10000000",
            "StatusErrno": "0",
            "StopWhenUnneeded": "no",
            "SubState": "running",
            "SyslogLevelPrefix": "yes",
            "SyslogPriority": "30",
            "TTYReset": "no",
            "TTYVHangup": "no",
            "TTYVTDisallocate": "no",
            "TimeoutStartUSec": "1min 30s",
            "TimeoutStopUSec": "1min 30s",
            "TimerSlackNSec": "50000",
            "Transient": "no",
            "Type": "simple",
            "UMask": "0022",
            "UnitFileState": "enabled",
            "WantedBy": "multi-user.target",
            "Wants": "system.slice",
            "WatchdogTimestampMonotonic": "0",
            "WatchdogUSec": "0",
        }
N)AnsibleModule)	is_chroot)sysv_existssysv_is_enabledfail_if_missing)	to_nativec                &    | d   t        ddg      v S )NActiveStateactive
activatingsetservice_statuss    G/home/dcms/DCMS/lib/python3.12/site-packages/ansible/modules/systemd.pyis_running_servicer   $  s    -(C<0H,III    c                $    | d   t        dg      v S )Nr   deactivatingr   r   s    r   is_deactivating_servicer   (  s    -(C0@,AAAr   c                "    d| vxr
 d| v xs d| v S )N=zignoring requestzignoring command )outs    r   request_was_ignoredr   ,  s#    c>V1S8U<NRU<UVr   c                   i }g }d }| D ]  }|d|v s
|j                  dd      \  }}|j                  d      rP|j                         j                  d      r1|j                         j	                  d      s|j                  |       |j                         ||<   d }|j                  |       |j                         j	                  d      sdj                  |      j                         ||<   g }d } |S )Nr      Exec{}
)split
startswithlstriprstripendswithappendstripjoin)linesparsedmultivalklinevs         r   parse_systemctl_showr1   0  s     FHA 9d{zz#q)1<<'AHHJ,A,A#,F88:..s3 * GGIq	OOD!{{}%%c* IIh/557q	  Mr   c                 B   t        t        t        dddg      t        dg d      t        d      t        d      t        d      t        dd	d
g      t        dd	dg      t        ddg d      t        dd	      	      dg dgt        ddd            } | j                  d   }|$dD ]  }||v s| j                  d|d|       ! | j	                  dd      }t        j                  d      (dt        j                         z  t
        j                  d<   | j                  d   dk7  r|d | j                  d   z  z  }| j                  d!   r|d"z  }| j                  d#   r|d$z  }d%}d&x}}t        |d	t               '      }| j                  d(   r| j                  sx| j                  d)|z        \  }}}|d%k7  r[t        |       s"t
        j                  j                  d*      d+k(  r| j                  d,||fz         n| j                  d-||fz         | j                  d.   r| j                  sx| j                  d/|z        \  }}}|d%k7  r[t        |       s"t
        j                  j                  d*      d+k(  r| j                  d0||fz         n| j                  d1||fz         |rZd	}t        |      }	d	}
| j                  |d2|d3      \  }}}|d%k(  rt        |      st        |      s|rt!        t#        |      j%                  d4            |d5<   d6|d5   v xr |d5   d6   d7k7  }
d6|d5   v xr |d5   d6   d8k(  }|
rV|sSd9|d5   v rK| j                  d:|d;|d5   d9          n+|r|d<k(  rd=|v rt!        t#        |      j%                  d4            |d5<   |j'                  d>      \  }}}d?j)                  ||@      }| j                  dAj)                  ||B            \  }}}||v }
| j                  dCj)                  ||D            \  }}}|j+                  d4      |d5   dE<   njg dF}| j                  |dG|d3      \  }}}|j-                         |v rd}
n6| j                  |dH|d3      \  }}}|d%k(  rd}
n| j                  |dI       |
xs |	}|	r|
s| j                  dJ|z         | j                  d8   | j                  |dG|d3      \  }}}|j-                         d8k(  }|| j                  d8   k7  rd|dK<   | j                  d8   rdL}ndM}| j                  s[| j                  |dN|dO|d3      \  }}}|d%k7  r8t/        | ||dP       | j                  dQ| dR| dS|j-                                 | j                  dT   | j                  dT   rdU}ndV}t/        | ||dP       d	}| j                  |dG|dW      \  }}}|d%k(  r|j+                         dXv rd	}nHd}nE|d<k(  r@| j                  d   dk(  r.|	r,|j-                         j1                  dY      st3        |      rd}||dT<   || j                  dT   k7  rXd|dK<   | j                  sA| j                  |dN|dO|d3      \  }}}|d%k7  r| j                  dZ|d[|d\||z          | |dT<   | j                  d]   Mt/        | ||dP       | j                  d]   |d]<   dE|d5   v rd }| j                  d]   d^k(  rt5        |d5         s\d_}nY| j                  d]   d`k(  rt5        |d5         st7        |d5         r+da}n(t5        |d5         sd_}n| j                  d]   d db }d^|d]<   |rd|dK<   | j                  s| j                  |dN|dO|d3      \  }}}|d%k7  rq| j                  dZ|d[|d\|       nUt        |       s"t
        j                  j                  d*      d+k(  r| j                  dc       n| j                  dd|d5   e        | j8                  dfi | y )gNstrserviceunit)typealiases)reloaded	restartedstartedstopped)r6   choicesbool)r6   Fzdaemon-reload)r6   defaultr7   zdaemon-reexecsystem)r?   userglobal)r6   r>   r<   )r6   r>   )	namestateenabledforcemaskeddaemon_reloaddaemon_reexecscopeno_blockT)rC   rD   rF   rG   rH   )rB   )rC   rD   rF   )argument_specsupports_check_moderequired_one_ofrequired_byrB   )*?[zCThis module does not currently support using glob patterns, found 'z' in service name: )msg	systemctlXDG_RUNTIME_DIRz/run/user/%srI   z --%srJ   z --no-blockrE   z --forcer    )rB   changedstatusrG   z%s daemon-reloadSYSTEMD_OFFLINE1zbdaemon-reload failed, but target is a chroot or systemd is offline. Continuing. Error was: %d / %sz#failure %d during daemon-reload: %srH   z%s daemon-reexeczbdaemon-reexec failed, but target is a chroot or systemd is offline. Continuing. Error was: %d / %sz#failure %d during daemon-reexec: %sz show ''r"   rW   	LoadStatez	not-foundrF   	LoadErrorzError loading unit file 'z': r   zFailed to parse bus message@z{unit_base}{sep})	unit_basesepz,{systemctl} list-unit-files '{unit_search}*')rS   unit_searchz{systemctl} is-active '{unit}')rS   r5   r   )rD   enabled-runtimelinkedzlinked-runtimerF   zmasked-runtimestaticindirectdisabled	generated	transientz is-enabled 'z list-unit-files ')check_rczPThe service (%s) is actually an init script but the system is managed by systemdrV   maskunmask z 'hostz
Failed to z the service (z): rD   enabledisablez' -l)ra   rd   aliasre   z
Unable to z	 service z: rC   r:   startr;   stopzyTarget is a chroot or systemd is offline. This can lead to false positives or prevent the init system tools from working.zService is in unknown state)rR   rW   r   )r   dictparams	fail_jsonget_bin_pathosgetenvgeteuidenviron
check_moderun_commandr   getwarnr   r   r1   r	   r#   	partitionformatr&   r)   r   r'   r   r   r   	exit_json)moduler5   globpatternrS   rcr   errresultfoundis_initd
is_systemd	is_maskedr^   r_   suffixr`   valid_enabled_statesrF   actionrD   s                       r   mainr   V  s   59f*=>E+Z[f%F#V$FEOCTUFEOCTUE8=YZvu5

 !YZ
F* == D- 	YKd"    FQ  SW  &X   Y	Y ##K6I	yy"#+(6(E

$%
 }}W)Wv}}W555	}}Z ]"	}}WZ		
BNC#vF }}_%f.?.?++,>),LMS#7 BJJNN3D$E$L  A  EG  IL  DM  M  N  %JbRUY%V W }}_%f.?.?++,>),LMS#7 BJJNN3D$E$L  A  EG  IL  DM  M  N  %JbRUY%V Wt$
  ++i,NOS#7/48KC8P#7	#8L8LT8R#Sx (F8,<<mAQR]A^bmAm
'6(+;;ix@PQ\@]ai@i	 iK6(CS4S$$tU[\dUefqUr)s$t R1W!>#!E3IcN4H4H4NOF8%)^^C%8"IsF,33iS3QK#//0^0e0epy  HS0e  1T  UNRc$+J#//0P0W0Wbkrv0W0wxNRc.1jj.>F8]+$  $//	SW0XYNRcyy{22!
 "(!3!3QZ\`4a!bS#7!%J &&y4&@ &hJKKjmqqr ==".#//	SW0XYNRcYY[H,Fx00$(y!==*#F%F((%+%7%7	SY[_8`%aNRcQw'tH((z&PTvUXY\YbYbYdXe-f(g ==#/}}Y'!"FE4V< G#//9VZ0[\NRc Qw::< $! !
 $G"Gq==)X5 IIK00<'-"G !(F9 &--	22$(y!((%+%7%7	SY[_8`%aNRcQw((fVZ\_be\e-f(g(/Ky! ==!-FE4V< %mmG4F7O x 00==)Y6-fX.>?!(]]7+y8)&*:;?VW]^fWg?h!'-fX.>?!(!'w!7!<&/F7O(,F9%!,,)/););IW]_c<d)eS#7",,RXZ^`c1d,e6"bjjnn5F&G3&N  X  Y   %B6RZK[ \Fvr   __main__)
__future__r   DOCUMENTATIONEXAMPLESRETURNrw   ansible.module_utils.basicr   (ansible.module_utils.facts.system.chrootr   ansible.module_utils.servicer   r   r   +ansible.module_utils.common.text.convertersr	   r   r   r   r1   r   __name__r   r   r   <module>r      sk    #\|1f@
D 
 4 > V V AJBW Lqh zF r   