
    Vh 8                         d dl mZmZmZ eZdZdZdZd dl	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d Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona  
module: systemd_info
short_description: Gather C(systemd) unit info
description:
  - This module gathers info about systemd units (services, targets, sockets, mounts, timers).
  - Timer units are supported since community.general 10.5.0.
  - It runs C(systemctl list-units) (or processes selected units) and collects properties
    for each unit using C(systemctl show).
  - In case a unit has multiple properties with the same name, only the value of the first one will be collected.
  - Even if a unit has a RV(units.loadstate) of V(not-found) or V(masked), it is returned,
    but only with the minimal properties (RV(units.name), RV(units.loadstate), RV(units.activestate), RV(units.substate)).
  - When O(unitname) and O(extra_properties) are used, the module first checks if the unit exists,
    then check if properties exist. If not, the module fails.
  - When O(unitname) is used with wildcard expressions, the module checks for units that match the indicated expressions,
    if units are not present for all the indicated expressions, the module fails.
version_added: "10.4.0"
options:
  unitname:
    description:
      - List of unit names to process.
      - It supports C(.service), C(.target), C(.socket), C(.mount) and C(.timer) units type.
      - C(.timer) units are supported since community.general 10.5.0.
      - Each name must correspond to the full name of the C(systemd) unit or to a wildcard expression like V('ssh*') and V('*.service').
      - Wildcard expressions in O(unitname) are supported since community.general 10.5.0.
    type: list
    elements: str
    default: []
  extra_properties:
    description:
      - Additional properties to retrieve (appended to the default ones).
      - Note that all property names are converted to lower-case.
    type: list
    elements: str
    default: []
author:
  - Marco Noce (@NomakCooper)
extends_documentation_fragment:
  - community.general.attributes
  - community.general.attributes.info_module
a  
---
# Gather info for all systemd services, targets, sockets, mount and timer
- name: Gather all systemd unit info
  community.general.systemd_info:
  register: results

# Gather info for selected units with extra properties.
- name: Gather info for selected unit(s)
  community.general.systemd_info:
    unitname:
      - systemd-journald.service
      - systemd-journald.socket
      - sshd-keygen.target
      - -.mount
    extra_properties:
      - Description
    register: results

# Gather info using wildcards/expression
- name: Gather info of units that start with 'systemd-'
  community.general.systemd_info:
    unitname:
      - 'systemd-*'
  register: results

# Gather info for systemd-tmpfiles-clean.timer with extra properties
- name: Gather info of systemd-tmpfiles-clean.timer and extra AccuracyUSec
  community.general.systemd_info:
    unitname:
      - systemd-tmpfiles-clean.timer
    extra_properties:
      - AccuracyUSec
  register: results
a6  
units:
  description:
    - Dictionary of systemd unit info keyed by unit name.
    - Additional fields will be returned depending on the value of O(extra_properties).
  returned: success
  type: dict
  elements: dict
  contains:
    name:
      description: Unit full name.
      returned: always
      type: str
      sample: systemd-journald.service
    loadstate:
      description:
        - The state of the unit's configuration load.
        - The most common values are V(loaded), V(not-found), and V(masked), but other values are possible as well.
      returned: always
      type: str
      sample: loaded
    activestate:
      description:
        - The current active state of the unit.
        - The most common values are V(active), V(inactive), and V(failed), but other values are possible as well.
      returned: always
      type: str
      sample: active
    substate:
      description:
        - The detailed sub state of the unit.
        - The most common values are V(running), V(dead), V(exited), V(failed), V(listening), V(active), and V(mounted), but other values are possible as well.
      returned: always
      type: str
      sample: running
    fragmentpath:
      description: Path to the unit's fragment file.
      returned: always except for C(.mount) units.
      type: str
      sample: /usr/lib/systemd/system/systemd-journald.service
    unitfilepreset:
      description:
        - The preset configuration state for the unit file.
        - The most common values are V(enabled), V(disabled), and V(static), but other values are possible as well.
      returned: always except for C(.mount) units.
      type: str
      sample: disabled
    unitfilestate:
      description:
        - The actual configuration state for the unit file.
        - The most common values are V(enabled), V(disabled), and V(static), but other values are possible as well.
      returned: always except for C(.mount) units.
      type: str
      sample: enabled
    mainpid:
      description: PID of the main process of the unit.
      returned: only for C(.service) units.
      type: str
      sample: 798
    execmainpid:
      description: PID of the ExecStart process of the unit.
      returned: only for C(.service) units.
      type: str
      sample: 799
    options:
      description: The mount options.
      returned: only for C(.mount) units.
      type: str
      sample: rw,relatime,noquota
    type:
      description: The filesystem type of the mounted device.
      returned: only for C(.mount) units.
      type: str
      sample: ext4
    what:
      description: The device that is mounted.
      returned: only for C(.mount) units.
      type: str
      sample: /dev/sda1
    where:
      description: The mount point where the device is mounted.
      returned: only for C(.mount) units.
      type: str
      sample: /
  sample:
    {
      "-.mount": {
        "activestate": "active",
        "description": "Root Mount",
        "loadstate": "loaded",
        "name": "-.mount",
        "options": "rw,relatime,seclabel,attr2,inode64,logbufs=8,logbsize=32k,noquota",
        "substate": "mounted",
        "type": "xfs",
        "what": "/dev/mapper/cs-root",
        "where": "/"
      },
      "sshd-keygen.target": {
        "activestate": "active",
        "description": "sshd-keygen.target",
        "fragmentpath": "/usr/lib/systemd/system/sshd-keygen.target",
        "loadstate": "loaded",
        "name": "sshd-keygen.target",
        "substate": "active",
        "unitfilepreset": "disabled",
        "unitfilestate": "static"
      },
      "systemd-journald.service": {
        "activestate": "active",
        "description": "Journal Service",
        "execmainpid": "613",
        "fragmentpath": "/usr/lib/systemd/system/systemd-journald.service",
        "loadstate": "loaded",
        "mainpid": "613",
        "name": "systemd-journald.service",
        "substate": "running",
        "unitfilepreset": "disabled",
        "unitfilestate": "static"
      },
      "systemd-journald.socket": {
        "activestate": "active",
        "description": "Journal Socket",
        "fragmentpath": "/usr/lib/systemd/system/systemd-journald.socket",
        "loadstate": "loaded",
        "name": "systemd-journald.socket",
        "substate": "running",
        "unitfilepreset": "disabled",
        "unitfilestate": "static"
      }
    }
N)AnsibleModule)systemd_runnerc                      | d      5 }|j                         \  }}}d d d        |j                         S # 1 sw Y   j                         S xY w)Nversionrunstrip)runnerctxrcstdoutstderrs        r/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/systemd_info.pyget_versionr      sF    			 'c WWYFF'<<>'<<>s	   6Ac                     d} | |      5 }|j                  |      \  }}}d d d        |j                         S # 1 sw Y   j                         S xY w)Nz$list_units types all plain no_legend)typesr
   )r   types_valuecontextr   r   r   r   s          r   
list_unitsr      sO    4G	 8C WW;W7FF8<<>8<<>s	   :Ac                     d} | |      5 }|j                  ||      \  }}}d d d        |j                         S # 1 sw Y   j                         S xY w)Nzshow props dashdash unit)propsunitr
   )r   	prop_listr   r   r   r   r   r   s           r   show_unit_propertiesr      sT    (G	 AC WW94W@FFA<<>A<<>s	   ;Ac                     i }| j                         D ]6  }d|v s|j                  dd      \  }}|j                         }||vs2|||<   8 |S )N=   )
splitlinessplitlower)outputresultlinekeyvals        r   parse_show_outputr)      s]    F!!# "$;zz#q)HC))+C& !s" M    c                 2    t        | ||      }t        |      S N)r   r)   )r   r   r   r$   s       r   get_unit_propertiesr-      s    !&)T:FV$$r*   c                     | j                  d      ry| j                  d      ry| j                  d      ry| j                  d      ry| j                  d	      ry
y )Nz.serviceservicez.targettargetz.socketsocketz.mountmountz.timertimer)endswith)r   s    r   determine_categoryr5     sP    }}Z 	y	!	y	!	x	 	x	 r*   c                     |D cg c]  }|j                          }}|D ci c]  }|| v s|| |    c}S c c}w c c}w r,   )r#   )	unit_datar   x	lowerpropprops        r   extract_unit_propertiesr;     sD    $-.q.I..7Md49;LD)D/!MM /Ms   7	<<c                 n    |j                  | i       }|j                  dd      j                         }|dvS )N	loadstate 	not-foundmasked)getr#   )r   
units_infoinfor=   s       r   unit_existsrE     s7    >>$#Db)//1I333r*   c                 J    g dg dg dg dg dd}|j                  | g       S )N)FragmentPathUnitFileStateUnitFilePresetMainPIDExecMainPID)rG   rH   rI   )WhereWhatOptionsTyper/   r0   r1   r2   r3   )rB   )category
base_propss     r   get_category_base_propsrS     s+    `EE5DJ >>(B''r*   c                    t        ||      s%t        j                  dj                  |             t	        |      }|s%t        j                  dj                  |             g d}t        |      }t        ||z   |z         }||vrt        | ||      }	|	||<   n||   }	|rY|D 
cg c]  }
|
j                         |	vs|
 }}
|r5t        j                  dj                  |dj                  |                   yc c}
w )Nz-Unit '{0}' does not exist or is inaccessible.msg0Could not determine the category for unit '{0}'.	LoadStateActiveStateSubStatez9The following properties do not exist for unit '{0}': {1}, T)
rE   module	fail_jsonformatr5   rS   setr-   r#   join)r   r   extra_propertiesrC   property_cacherQ   state_propsr   
full_propsr7   r:   missing_propss               r   validate_unit_and_propertiesrg   *  s   tZ(LSSTXYZ!$'HOVVW[\]:K#H-EU[(+;;<J>!'
DA	(t"4(	*:\$djjlR[>[\\!\!c!cdhjnjsjs  uB  kC  "D  E	 ]s   &C<>C<c                     i }g }| D ]8  }t        j                  ||      }|s|j                  |       -|D ]  }d||<   	 : |s0|j                  dj	                  dj                  |                   ||fS )NTz/No units match any of the provided patterns: {}r\   rU   )fnmatchfilterappendr^   r_   ra   )selected_units	all_unitsr]   resolved_unitsnon_matching_patternspatternmatchesmatchs           r   process_wildcardsrs   D  s    N! -..G4!((1  -(,u%-- NUUVZV_V_`uVvwx000r*   c                    t        ||      s|j                  ||dd      S t        | ||||       t        |      }|s%t        j                  dj                  |             t        |      }t        ||z   |z         }||   }	d|i}
g d}|
j                  t        |	|             |	j                  dd      j                         }|d	vr|
j                  t        |	|             |
S )
Nr@   )namer=   rW   rU   ru   rX   r=   r>   r?   )rE   rB   rg   r5   r]   r^   r_   rS   r`   updater;   r#   )r   r   rb   rC   rc   rd   rQ   r   re   r7   factminimal_keyslss                r   process_unitrz   V  s    tZ(~~dT$LMM /?^\!$'HOVVW[\]#H-EU[(+;;<Jt$ID>D;LKK'	<@A	{B	'	-	-	/B	((+IzBCKr*   c            	         t        t        ddg       t        ddg             } t        | d      at        j                  dd      }t	        t        |      }t        |       g d	}i }g d
}t        ||      }i }|j                         D ]?  }|j                         }	t        |	      dk  r"|	d   }
|	d   }|	d   }|	d   }|
|||d||
<   A i }t        j                  d   }t        j                  d   r>t        j                  d   }t        |      }t        ||t              \  }}t        |      }nt        |      }|D ]  }t        ||||||      ||<    t        j                  d|       y )Nliststr)typeelementsdefault)unitnamerb   T)argument_specsupports_check_mode	systemctl)requiredrX   rP      r   r          )ru   r=   activestatesubstaterb   r   F)changedunits)dictr   r]   get_bin_pathr   r   r   r!   r"   lenparamsr|   rs   sortedrz   	exit_json)module_argssystemctl_binbase_runnerrd   results
unit_typeslist_outputrC   r&   tokens	unit_namer=   r   r   rc   rb   rl   rm   rn   non_matchingunits_to_processr   s                         r   mainr   n  s   6E2>6E2FK $OF''d'CM 7K:KGBJ[*5KJ&&( 
v;?1I	1I	Qi!9"& 	!

9
 N}}%78}}Z z2$	'8TZ'[$!.1
+  s$[$8H*Vdfqrs
U'2r*   __main__)
__future__r   r   r   r~   __metaclass__DOCUMENTATIONEXAMPLESRETURNri   ansible.module_utils.basicr   Bansible_collections.community.general.plugins.module_utils.systemdr   r   r   r   r)   r-   r5   r;   rE   rS   rg   rs   rz   r   __name__ r*   r   <module>r      s    A @'R"HB
H  4 ]%
N
4(41$003f zF r*   