예제 #1
0
파일: packages.py 프로젝트: naparuba/opsbro
def has_package(package):
    """**has_package(package)** -> return True if the package is installed on the system, False otherwise.

 * package: (string) name of the package to check for.

<code>
    Example:
        has_package('postfix')
    Returns:
        False
</code>
    """
    systepacketmgr = get_systepacketmgr()
    return systepacketmgr.has_package(package)
 def launch(self, rule):
     
     mode = rule.get_mode()
     if mode is None:
         return
     
     matching_env = rule.get_first_matching_environnement()
     if matching_env is None:
         return
     
     did_error = False
     
     env_name = matching_env.get_name()
     parameters = matching_env.get_parameters()
     
     env_packages = parameters.get('packages', [])
     # Now look if we are compliant, or not
     packages_to_install = []
     systepacketmgr = get_systepacketmgr()
     for package in env_packages:
         is_installed = systepacketmgr.has_package(package)
         self.logger.debug('(%s) is package %s installed? => %s' % (env_name, package, is_installed))
         if not is_installed:
             packages_to_install.append(package)
         else:
             txt = 'Environnement %s: the package %s is installed.' % (env_name, package)
             rule.add_compliance(txt)
     
     # If there is no packages to install, we are done in a good way
     if not packages_to_install:
         txt = 'All packages are already installed'
         rule.add_compliance(txt)
         rule.set_compliant()
         return
     
     # Ok we are not compliant, we need to fix (if allowed) some packages
     self.logger.debug('Installor:: (%s)  in the env %s, trying to detect which packages need to be installed (because they are not currently) => %s ' % (self.name, env_name, ','.join(packages_to_install)))
     for pkg in packages_to_install:
         err = 'Environnement %s: need to install package: %s' % (env_name, pkg)
         rule.add_error(err)
         if mode == 'enforcing':
             try:
                 systepacketmgr.install_package(pkg)
                 txt = 'Environnement %s: package %s is now installed' % (env_name, pkg)
                 rule.add_fix(txt)
             except Exception as exp:
                 err = 'Environnement %s: package (%s) installation fail: %s' % (env_name, pkg, exp)
                 rule.add_error(err)
                 did_error = True
         else:
             err = 'Environnement %s: the package %s is not installed' % (env_name, pkg)
             rule.add_error(err)
     
     # spawn post commands if there are some
     is_ok = rule.launch_post_commands(matching_env)
     if not is_ok:
         return
     
     # If we fail at least one package, exit it
     if did_error:
         rule.set_error()
         return
     
     # We did fix all package, cool
     txt = 'Environnement %s: all packages are now installed' % env_name
     rule.add_fix(txt)
     rule.set_fixed()
     return
예제 #3
0
파일: setup.py 프로젝트: genothomas/opsbro
    del opsbro_test_import
except ImportError as exp:  # great, first install so
    pass

# Now look at loading the local opsbro lib for version and banner
my_dir = os.path.dirname(os.path.abspath(__file__))
opsbro = imp.load_module(
    'opsbro', *imp.find_module('opsbro', [os.path.realpath(my_dir)]))
from opsbro.info import VERSION, BANNER, TXT_BANNER
from opsbro.log import cprint, is_tty, sprintf, core_logger
from opsbro.misc.bro_quotes import get_quote
from opsbro.systempacketmanager import get_systepacketmgr
from opsbro.cli_display import print_h1
from opsbro.characters import CHARACTERS

systepacketmgr = get_systepacketmgr()

##################################       Only root as it's a global system tool.
if os.name != 'nt' and os.getuid() != 0:
    cprint('Setup must be launched as root.', color='red')
    sys.exit(2)

# By default logger should not print anything
core_logger.setLevel('ERROR')
# By maybe we are in verbose more?
if '-v' in sys.argv or os.environ.get('DEBUG_INSTALL', '0') == '1':
    core_logger.setLevel('DEBUG')

core_logger.debug('SCRIPT: install/update script was call with arguments: %s' %
                  orig_sys_argv)
예제 #4
0
    def launch(self):
        logger = self.logger

        logger.debug('getSystem: start')
        res = {}

        res['hostname'] = platform.node()
        res['fqdn'] = socket.getfqdn()

        res['os'] = {}
        res['os']['name'] = platform.system().lower()
        res['os']['platform'] = sys.platform
        res['architecture'] = platform.uname()[-1]
        # Lazy load multiprocessing
        from multiprocessing import cpu_count
        res['cpu_count'] = cpu_count()
        res['cpu_model_name'] = ''
        res['cpu_mhz'] = 0

        systepacketmgr = get_systepacketmgr()
        # Linux, directly ask python
        if res['os']['name'] == 'linux':
            (distname, version, _id) = systepacketmgr.get_distro()
            linux = {}
            res['os']['linux'] = linux
            linux['distribution'] = distname  # .lower()
            linux['version'] = version  # .lower()
            linux['id'] = _id  # .lower()
            # Maybe version is directly an int, get it
            _version = linux['version']
            _major = None
            _minor = None
            # something like 7.2
            if '.' in _version:
                elts = _version.split('.')  # no limit, if 8.0.1, will give 8.0
                try:
                    _major = int(elts[0])
                    _minor = int(elts[1])
                except ValueError:
                    pass
            else:
                try:
                    _major = int(_version)
                    _minor = 0
                except ValueError:
                    pass
            linux['major_version'] = _major
            linux['minor_version'] = _minor

            # Also get CPU info
            with open('/proc/cpuinfo', 'r') as f:
                buf = f.read()
                lines = buf.splitlines()
                for line in lines:
                    if ':' not in line:
                        continue
                    key, value = line.split(':', 1)
                    if key.startswith('model name'):
                        res['cpu_model_name'] = value.strip()
                    if key.startswith('cpu MHz'):
                        res['cpu_mhz'] = int(float(value.strip()))

        # Windows, get data from Win32_OperatingSystem
        if os.name == 'nt':
            win = {}
            res['windows'] = win
            _os = wmiaccess.get_table_where('Win32_OperatingSystem',
                                            {'Primary': 1})
            # only the first entry
            _os = _os[0]
            props = [
                'Caption', 'ServicePackMajorVersion',
                'ServicePackMinorVersion', 'SerialNumber', 'OSArchitecture',
                'MUILanguages', 'CSDVersion'
            ]
            for prop in props:
                win[prop.lower()] = getattr(_os, prop)

            # Also get server roles
            win['features'] = []
            try:
                _features = wmiaccess.get_table_where('Win32_ServerFeature')
            except AttributeError:  # maybe the Win32_ServerFeature is missing
                _features = []
            for f in _features:
                win['features'].append(f.Name)
            win['features'].sort()

        if hasattr(os, 'getlogin'):
            try:
                res['user'] = os.getlogin()
            except OSError:  # some background daemon can have problem on ancien os
                if pwd is not None:
                    res['user'] = pwd.getpwuid(os.geteuid()).pw_name
            if hasattr(os, 'getuid'):  # windows python 3 do not have it
                res['uid'] = os.getuid()
                res['gid'] = os.getgid()

        # Get public & local address, and directly from the hosting driver as it already does the job
        hostingdrvmgr = get_hostingdrivermgr()
        res['public_ip'] = hostingdrvmgr.get_public_address()
        res['local_ip'] = hostingdrvmgr.get_local_address()

        logger.debug('getsystem: completed, returning')
        return res
예제 #5
0
        def get_info():
            response.content_type = 'application/json'

            from opsbro.systempacketmanager import get_systepacketmgr

            systepacketmgr = get_systepacketmgr()
            system_distro, system_distroversion, _ = systepacketmgr.get_distro(
            )

            r = {
                'agent_state':
                self.agent_state,
                'logs':
                raw_logger.get_errors(),
                'pid':
                os.getpid(),
                'name':
                self.name,
                'display_name':
                self.display_name,
                'port':
                self.port,
                'local_addr':
                self.addr,
                'public_addr':
                self.public_addr,
                'socket':
                self.socket_path,
                'zone':
                gossiper.zone,
                'is_zone_protected':
                libstore.get_encrypter().is_zone_have_key(gossiper.zone),
                'uuid':
                gossiper.uuid,
                'threads':
                threader.get_info(),
                'version':
                VERSION,
                'groups':
                gossiper.groups,
                'docker':
                dockermgr.get_info(),
                'collectors':
                collectormgr.get_info(),
                'kv':
                kvmgr.get_info(),
                'hosting_driver':
                get_hostingdrivermgr().get_driver_name(),
                'hosting_drivers_state':
                get_hostingdrivermgr().get_drivers_state(),
                'topics':
                topiker.get_topic_states(),
                'monitoring':
                monitoringmgr.get_infos(),
                'compliance':
                compliancemgr.get_infos(),
                'cpu_consumption':
                get_cpu_consumption(),
                'memory_consumption':
                get_memory_consumption(),
                'generators':
                generatormgr.get_infos(),
                'is_managed_system':
                systepacketmgr.is_managed_system(),
                'system_distro':
                system_distro,
                'system_distroversion':
                system_distroversion,
            }

            # Update the infos with modules ones
            mod_infos = modulemanager.get_infos()
            r['modules'] = mod_infos

            r['httpservers'] = {}
            # Look at both http servers
            for (k, server) in gserver.items():
                if server is None:
                    r['httpservers'][k] = None
                    continue
                # if available get stats (some old cherrypy versions do not have them, like in debian 6)
                s = getattr(server, 'stats', None)
                if not s:
                    continue
                nb_threads = s['Threads'](s)
                idle_threads = s['Threads Idle'](s)
                q = s['Queue'](s)
                r['httpservers'][k] = {
                    'nb_threads': nb_threads,
                    'idle_threads': idle_threads,
                    'queue': q
                }
            return r
    def launch(self, rule):

        mode = rule.get_mode()
        if mode is None:
            return

        check_only = (mode == 'audit')

        matching_env = rule.get_first_matching_environnement()
        if matching_env is None:
            return

        env_name = matching_env.get_name()

        did_error = False
        systepacketmgr = get_systepacketmgr()

        # Now we can get our parameters
        parameters = matching_env.get_parameters()
        url = parameters.get('url')
        key = parameters.get('key', '')
        name = parameters.get('name')
        key_server = parameters.get('key-server', '')

        if not url or not name:
            err = 'No url or name defined'
            rule.add_error(err)
            rule.set_error()
            return

        # STEP1: First key
        if key or key_server:
            try:
                is_set = systepacketmgr.assert_repository_key(
                    key, key_server, check_only=check_only)
                if not is_set:
                    err = 'The key %s from the serveur key %s is not imported' % (
                        key, key_server)
                    rule.add_error(err)
                    rule.set_error()
                    did_error = True
                else:
                    compl = 'The key %s from the server key %s is imported' % (
                        key, key_server)
                    rule.add_compliance(compl)
            except Exception as exp:
                err = 'Cannot import the key %s from the server %s : %s' % (
                    key, key_server, exp)
                rule.add_error(err)
                rule.set_error()
                did_error = True

        # STEP2: repository
        try:
            is_repository_set = systepacketmgr.assert_repository(
                name, url, key_server, check_only=check_only)
            if not is_repository_set:
                err = 'The repository named %s is not set' % name
                rule.add_error(err)
                rule.set_error()
                # Nothing more to do, we can exit
                return
        except Exception as exp:
            err = 'Cannot set the repository %s (url=%s) : %s' % (name, url,
                                                                  exp)
            rule.add_error(err)
            rule.set_error()
            return

        # If we fail at least one package, exit it
        if did_error:
            rule.set_error()
            return

        # spawn post commands if there are some
        is_ok = rule.launch_post_commands(matching_env)
        if not is_ok:
            return

        # We did fix all package, cool
        txt = 'Environnement %s: the repository %s is configured' % (env_name,
                                                                     name)
        rule.add_compliance(txt)
        rule.set_compliant()
        return