Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
#!/usr/bin/env python

import re
from ansible.module_utils.basic import AnsibleModule
import subprocess

DOCUMENTATION = '''
---
module: wlm_service
short_description: Return service state information as fact data
description:
     - Return service state information as fact data for workloadmgr services
options:
requirements: [ ]
author: Murali Balcha
'''

EXAMPLES = '''
- monit: wlm_service
# Example output:
# host | success >> {
#    "wlm_service_facts": {
#    "wlm_services": {
#            "wlm-api": {
#                    "state": "running",
#                    "name": "wlm-api"
#            },
#            "wlm-scheduler": {
#                    "state": "stopped",
#                    "name": "wlm-scheduler"
#            }
#            "wlm-workloads": {
#                    "state": "stopped",
#                    "name": "wlm-workloads"
#            }
#    }
#   }
'''

class BaseService(object):

    def __init__(self, module):
        self.module = module
        self.incomplete_warning = False


class SystemctlScanService(BaseService):

    def systemd_enabled(self):
        # Check if init is the systemd command, using comm as cmdline could be symlink
        try:
            f = open('/proc/1/comm', 'r')
        except IOError:
            # If comm doesn't exist, old kernel, no systemd
            return False
        for line in f:
            if 'systemd' in line:
                return True
        return False

    def gather_services(self, service_name=None):
        services = {}
        if not self.systemd_enabled():
            return None
        systemctl_path = self.module.get_bin_path("systemctl", opt_dirs=["/usr/bin", "/usr/local/bin"])
        if systemctl_path is None:
            return None
        rc, stdout, stderr = self.module.run_command("%s list-unit-files --type=service | tail -n +2 | head -n -2" % systemctl_path, use_unsafe_shell=True)
        for line in stdout.split("\n"):
            line_data = line.split()
            if len(line_data) != 2:
                continue
            if service_name and not service_name in line_data[0]:
                continue

            command = ['systemctl', 'show', line_data[0]]
            output = subprocess.check_output(command, shell=False)
            for s in output.split('\n'):
                if 'substate' in s.lower():
                    if 'running' in s.lower():
                        state_val = 'Running'
                    else:
                        state_val = 'Stopped'
            services[line_data[0]] = {"name": line_data[0], "state": state_val }
        return services


def main():
    module = AnsibleModule(argument_spec = dict(
                 service_name=dict(required=False),
            ))
    service_name = module.params['service_name']
    service_modules = [SystemctlScanService]
    all_services = {}
    incomplete_warning = False
    for svc_module in service_modules:
        svcmod = svc_module(module)
        svc = svcmod.gather_services(service_name=service_name)
        if svc is not None:
            all_services.update(svc)
            if svcmod.incomplete_warning:
                incomplete_warning = True
    if len(all_services) == 0:
        results = dict(skipped=True, msg="Failed to find any services. Sometimes this is due to insufficient privileges.")
    else:
        results = dict(wlm_service_facts=dict(wlm_services=all_services))
        if incomplete_warning:
            results['msg'] = "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges."
    module.exit_json(**results)


# this is magic, see lib/ansible/module_common.py
# <<INCLUDE_ANSIBLE_MODULE_COMMON>>
if __name__ == '__main__':
    main()