Exemple #1
0
class FactsModule(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "Has some useful about Facts module"

    def list_fact_modules(self):
        """
        List facts that are availible in that system
        """
        return minion_query.load_facts_modules().keys()

    def list_fact_methods(self, abort_on_conflict=False):
        """
        List facts that are availible in that system
        """
        methods = minion_query.load_fact_methods(abort_on_conflict)
        if not methods.has_key('__conflict__'):
            return methods.keys()
        else:
            return methods

    def show_fact_module(self, module_name):
        """
        Show some info about fact module
        """

        for name, module in minion_query.load_facts_modules().iteritems():
            if name == module_name:
                return {
                    'name': name,
                    'description': getattr(module, "description", ""),
                    'version': getattr(module, "version", "")
                }
        return {}

    def show_fact_method(self, method_name):
        """
        Display info about fact method
        """

        for name, method in minion_query.load_fact_methods().iteritems():
            if name == method_name:
                return {
                    'name': name,
                    'tag': getattr(method, "tag", ""),
                }
        return {}

    def call_fact(self, method_name):
        """
        Sometimes we may need to get some of the facts live
        """
        for name, method in minion_query.load_fact_methods().iteritems():
            if name == method_name:
                return method()
        return {}

    def grep(self, word):
        """
        Get some info about facts
        """
        result = {self.list_fact_modules: [], self.list_fact_methods: []}

        #search in modules
        for m in self.list_fact_modules():
            if m.lower().find(word) != -1:
                result[self.list_fact_modules].append(m)

        #search in methods
        for m in self.list_fact_methods():
            if m.lower().find(word) != -1:
                val = self.call_fact(m)
                result[self.list_fact_methods].append("%s: %s" % (m, val))

        #the final collected stuff here
        return result

    grep = func_module.findout(grep)
Exemple #2
0
class HardwareModule(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "Hardware profiler."

    def hal_info(self):
        """
        Returns the output of lshal, but split up into seperate devices
        for easier parsing.  Each device is a entry in the return hash.
        """

        cmd = sub_process.Popen(["/usr/bin/lshal"],
                                shell=False,
                                stdout=sub_process.PIPE,
                                close_fds=True)
        data = cmd.communicate()[0]

        data = data.split("\n")

        results = {}
        current = ""
        label = data[0]
        for d in data:
            if d == '':
                results[label] = current
                current = ""
                label = ""
            else:
                if label == "":
                    label = d
                current = current + d

        return results

    def inventory(self):
        data = self.info()
        # remove bogomips because it keeps changing for laptops
        # and makes inventory tracking noisy
        if data.has_key("bogomips"):
            del data["bogomips"]
        return data

    def grep(self, word):
        """
        Find something in hardware info
        """
        result = {self.info: []}
        hw_info = self.info()

        if hw_info == []:
            return []

        for hw_k, hw_v in hw_info.iteritems():
            if hw_k.lower().find(word) != -1:
                result[self.info].append({hw_k: hw_v})
            #we should see if the value is
            elif type(hw_v) == str and hw_v.lower().find(word) != -1:
                result[self.info].append({hw_k: hw_v})
            elif type(hw_v) == list:
                #as it si known the hw_info has a devices
                #in its final data and it is in format of:
                #[{key:val}] so should check it also
                for device in hw_v:
                    for d_k, d_v in device.iteritems():
                        if d_k.lower().find(word) != -1:
                            result[self.info].append({d_k: d_v})
                        elif d_v.lower().find(word) != -1:
                            result[self.info].append({d_k: d_v})

        #get the final result
        return result

    grep = func_module.findout(grep)

    def info(self, with_devices=True):
        """
        Returns a struct of hardware information.  By default, this pulls down
        all of the devices.  If you don't care about them, set with_devices to
        False.
        """

        # this will fail if smolt is not installed.  That's ok.  hal_info will
        # still work.

        # hack: smolt is not installed in site-packages
        try:
            sys.path.append("/usr/share/smolt/client")
            import smolt
        except ImportError, e:
            errmsg = _(
                "Import error while loading smolt module. Smolt is probably not installed. This method is useless without it."
            )
            self.logger.warning(errmsg)
            self.logger.warning("%s" % traceback.format_exc())
            # hmm, what to return...
            return []

        hardware = smolt.Hardware()
        host = hardware.host

        # NOTE: casting is needed because these are DBusStrings, not real strings
        data = {
            'os': str(host.os),
            'defaultRunlevel': str(host.defaultRunlevel),
            'bogomips': str(host.bogomips),
            'cpuVendor': str(host.cpuVendor),
            'cpuModel': str(host.cpuModel),
            'numCpus': str(host.numCpus),
            'cpuSpeed': str(host.cpuSpeed),
            'systemMemory': str(host.systemMemory),
            'systemSwap': str(host.systemSwap),
            'kernelVersion': str(host.kernelVersion),
            'language': str(host.language),
            'platform': str(host.platform),
            'systemVendor': str(host.systemVendor),
            'systemModel': str(host.systemModel),
            'formfactor': str(host.formfactor),
            'selinux_enabled': str(host.selinux_enabled),
            'selinux_enforce': str(host.selinux_enforce)
        }

        # if no hardware info requested, just return the above bits
        if not with_devices:
            return data

        collection = data["devices"] = []

        for item in hardware.deviceIter():

            (VendorID, DeviceID, SubsysVendorID, SubsysDeviceID, Bus, Driver,
             Type, Description) = item

            collection.append({
                "VendorID": str(VendorID),
                "DeviceID": str(DeviceID),
                "SubsysVendorID": str(SubsysVendorID),
                "Bus": str(Bus),
                "Driver": str(Driver),
                "Type": str(Type),
                "Description": str(Description)
            })

        return data

        def register_method_args(self):
            """
            Implementing the argument getter
            """

            return {
                'hal_info': {
                    'args': {},
                    'description': 'Returns the output of lshal'
                },
                'inventory': {
                    'args': {},
                    'description': "The inventory part"
                },
                'info': {
                    'args': {
                        'with_devices': {
                            'type': 'boolean',
                            'optional': True,
                            'default': True,
                            'description': 'All devices'
                        }
                    },
                    'description': "A struct of hardware information"
                }
            }
Exemple #3
0
class RpmModule(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "RPM related commands."

    def inventory(self, flatten=True):
        """
        Returns information on all installed packages.
        By default, 'flatten' is passed in as True, which makes printouts very
        clean in diffs for use by func-inventory.  If you are writting another
        software application, using flatten=False will prevent the need to
        parse the returns.
        """
        return self.glob('', flatten)

    def grep(self, word):
        """
        Grep some info from packages we got from
        inventory especially
        """
        results = {self.inventory:[]}
        inventory_res = self.inventory()

        for res in inventory_res:
            if res.lower().find(word)!= -1:
                results[self.inventory].append(res)
        return results

    grep = func_module.findout(grep)

    def verify(self, pattern='', flatten=True):
        """
        Returns information on the verified package(s).
        """
        results = []
        import yum
        for rpm in self.glob(pattern, False):
            name = rpm[0]
            yb = yum.YumBase()
            pkgs = yb.rpmdb.searchNevra(name)
            for pkg in pkgs:
                errors = pkg.verify()
                for fn in errors.keys():
                    for prob in errors[fn]:
                        if flatten:
                            results.append('%s %s %s' % (name, fn, prob.message))
                        else:
                            results.append([name, fn, prob.message])
        return results

    def glob(self, pattern, flatten=True):
        """
        Return a list of installed packages that match a pattern
        """
        import rpm
        ts = rpm.TransactionSet()
        mi = ts.dbMatch()
        results = []
        if not mi:
            return results
        if (pattern != ''):
            mi.pattern('name', rpm.RPMMIRE_GLOB, pattern)
        for hdr in mi:
            name = hdr['name']
            # not all packages have an epoch
            epoch = (hdr['epoch'] or 0)
            version = hdr['version']
            release = hdr['release']
            # gpg-pubkeys have no arch
            arch = (hdr['arch'] or "")
            if flatten:
                # flatten forms a simple text list separated by spaces
                results.append("%s %s %s %s %s" % (name, epoch, version,
                                                   release, arch))
            else:
                # Otherwise we return it as a list
                results.append([name, epoch, version, release, arch])
        results.sort()
        return results


    def register_method_args(self):
        """
        Implementing the method argument getter
        """
        return {
                'inventory':{
                    'args':{
                        'flatten':{
                            'type':'boolean',
                            'optional':True,
                            'default':True,
                            'description':"Print clean in difss"
                            }
                        },
                    'description':"Returns information on all installed packages"
                    },
                'verify':{
                    'args':{
                        'flatten':{
                            'type':'boolean',
                            'optional':True,
                            'default':True,
                            'description':"Print clean in difss"
                            }
                        },
                    'description':"Returns information on the verified package(s)"
                    },
                'glob':{
                    'args':{
                        'pattern':{
                            'type':'string',
                            'optional':False,
                            'description':"The glob packet pattern"
                            },
                        'flatten':{
                            'type':'boolean',
                            'optional':True,
                            'default':True,
                            'description':"Print clean in difss"
                                }
                        },
                    'description':"Return a list of installed packages that match a pattern"
                    }
                }
Exemple #4
0
class SysctlModule(func_module.FuncModule):

    version = "0.0.1"
    description = "Configure kernel parameters at runtime"

    def __run(self, cmd):
        cmd = sub_process.Popen(cmd.split(),
                                stdout=sub_process.PIPE,
                                stderr=sub_process.PIPE,
                                shell=False,
                                close_fds=True)
        return [line for line in cmd.communicate()[0].strip().split('\n')]

    def list(self):
        return self.__run("/sbin/sysctl -a")

    def get(self, name):
        return self.__run("/sbin/sysctl -n %s" % name)

    def set(self, name, value):
        return self.__run("/sbin/sysctl -w %s=%s" % (name, value))

    def grep(self, word):
        """
        Grep info from sysctl
        """
        results = {self.list: []}
        sys_res = self.list()  #the ist fo sysctl

        for res in sys_res:
            if res.lower().find(word) != -1:
                results[self.list].append(res)

        return results

    grep = func_module.findout(grep)

    def register_method_args(self):
        """
        Implementing the method argument getter
        """

        return {
            'list': {
                'args': {},
                'description': "Display all values currently available."
            },
            'get': {
                'args': {
                    'name': {
                        'type':
                        'string',
                        'optional':
                        False,
                        'description':
                        "The name of a key to read from.  An example is kernel.ostype"
                    }
                },
                'description':
                "Use this option to disable printing of the key name when printing values"
            },
            'set': {
                'args': {
                    'name': {
                        'type':
                        'string',
                        'optional':
                        False,
                        'description':
                        "The name of a key to read from.  An example is kernel.ostype"
                    },
                    'value': {
                        'type': 'string',
                        'optional': False,
                        'description': "The name value to be set."
                    }
                },
                'description':
                "Use this option when you want to change a sysctl setting"
            }
        }
Exemple #5
0
    def grep(self, word):
        """
        Grep some info from grep test
        especially netstat is very suitable 
        for that purpose ...
        """
        results = {
                   self.netstat:[]
                   }
        netstat_result = self.netstat()
        for res in netstat_result:
            if res.lower().find(word)!=-1:
                results[self.netstat].append(res)
        
        return results
    grep = func_module.findout(grep)

    def __args_to_list(self, args):
        return [arg for arg in args]

    def __run_command(self, command, opts=[]):
        full_cmd = [command] + opts
        cmd = sub_process.Popen(full_cmd, stdout=sub_process.PIPE, close_fds=True)
        return [line for line in cmd.communicate()[0].split('\n')]

    def register_method_args(self):
        """
        Implementing method getter part
        """

        return{
Exemple #6
0
class MountModule(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "Mounting, unmounting and getting information on mounted filesystems."

    def list(self):
        cmd = sub_process.Popen(["/bin/cat", "/proc/mounts"],
                                executable="/bin/cat",
                                stdout=sub_process.PIPE,
                                shell=False,
                                close_fds=True)
        data = cmd.communicate()[0]

        mounts = []
        lines = [l for l in data.split("\n")
                 if l]  #why must you append blank crap?

        for line in lines:
            curmount = {}
            tokens = line.split()
            curmount['device'] = tokens[0]
            curmount['dir'] = tokens[1]
            curmount['type'] = tokens[2]
            curmount['options'] = tokens[3]
            mounts.append(curmount)

        return mounts

    def mount(self, device, dir, type="auto", options=None, createdir=False):
        cmdline = ["/bin/mount", "-t", type]
        if options:
            cmdline.append("-o")
            cmdline.append(options)
        cmdline.append(device)
        cmdline.append(dir)
        if createdir:
            try:
                os.makedirs(dir)
            except:
                return False
        cmd = sub_process.Popen(cmdline,
                                executable="/bin/mount",
                                stdout=sub_process.PIPE,
                                shell=False,
                                close_fds=True)
        if cmd.wait() == 0:
            return True
        else:
            return False

    def umount(self, dir, killall=False, force=False, lazy=False):
        # succeed if its not mounted
        if not os.path.ismount(dir):
            return True

        if killall:
            cmd = sub_process.Popen(["/sbin/fuser", "-mk", dir],
                                    executable="/sbin/fuser",
                                    stdout=sub_process.PIPE,
                                    shell=False,
                                    close_fds=True)
            cmd.wait()

        cmdline = ["/bin/umount"]
        if force:
            cmdline.append("-f")
        if lazy:
            cmdline.append("-l")
        cmdline.append(dir)

        cmd = sub_process.Popen(cmdline,
                                executable="/bin/umount",
                                stdout=sub_process.PIPE,
                                shell=False,
                                close_fds=True)
        if cmd.wait() == 0:
            return True
        else:
            return False

    def inventory(self, flatten=True):
        return self.list()

    def grep(self, word):
        """
        Get some info about mounted devices
        """
        results = {self.list: []}
        list_res = self.list()

        if list_res:
            for list_dict in list_res:
                for m_k, m_v in list_dict.iteritems():
                    if m_k.lower().find(word) != -1 or m_v.lower().find(
                            word) != -1:
                        results[self.list].append({m_k: m_v})
        return results

    grep = func_module.findout(grep)

    def register_method_args(self):
        """
        Implementing the method arg getter
        """

        return {
            'list': {
                'args': {},
                'description': "Listing the mounting points"
            },
            'mount': {
                'args': {
                    'device': {
                        'type': 'string',
                        'optional': False,
                        'description': 'The device to be mounted',
                    },
                    'dir': {
                        'type':
                        'string',
                        'optional':
                        False,
                        'description':
                        'The directory which will the device mounted under'
                    },
                    'type': {
                        'type': 'string',
                        'optional': True,
                        'default': 'auto',
                        'description': 'The type of the mount'
                    },
                    'options': {
                        'type':
                        'list',
                        'optional':
                        True,
                        'description':
                        "Some extra options to be added to mount command"
                    },
                    'createdir': {
                        'type':
                        'boolean',
                        'optional':
                        True,
                        'description':
                        'Check if you want to create the dir place if not exist'
                    }
                },
                'description':
                "Mount the specified device under some directory"
            },
            'umount': {
                'args': {
                    'dir': {
                        'type': 'string',
                        'optional': False,
                        'description': 'The directory which will be unmounted'
                    },
                    'killall': {
                        'type': 'boolean',
                        'optional': True,
                        'description': 'The killal option'
                    },
                    'force': {
                        'type': 'boolean',
                        'optional': True,
                        'description': 'To force operation check it'
                    },
                    'lazy': {
                        'type': 'boolean',
                        'optional': True,
                        'description': 'The lazy option'
                    }
                },
                'description': "Unmounting the specified directory."
            },
            'inventory': {
                'args': {
                    'flatten': {
                        'type': 'boolean',
                        'optional': True,
                        'description': "To flatten check."
                    }
                },
                'description': "The inventory part of that module"
            }
        }
Exemple #7
0
class Yum(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.1.0"
    description = "Package updates through yum."

    from yum import __version__ as yumversion
    yvertuple = yumversion.split('.')
    if int(yvertuple[0]) == 3 and int(yvertuple[2]) >= 25:
        def rpmdbVersion(self, **kwargs):
            import yum
            ayum = yum.YumBase()
            versionlist = ayum.rpmdb.simpleVersion(main_only=True)
            version = versionlist[0]
            return versionlist

    def update(self, pkg=None, config_dict={}):
        return _singleAction('update', items=pkg, config_dict=config_dict)

    def install(self, pkg=None, config_dict={}):
        return _singleAction('install', items=pkg, config_dict=config_dict)

    def remove(self, pkg=None, config_dict={}):
        return _singleAction('remove', items=pkg, config_dict=config_dict)

    #def multiple(self, cmdlist=[]):
    #    """take multiple commands as a single transaction - equiv of yum shell"""
    #    raise FuncException("Not Implemented Yet!"

    def get_package_lists(self, pkgspec='installed,available,obsoletes,updates,extras', config_dict={}):
        import yum
        ayum = yum.YumBase()
        ayum.doGenericSetup()
        ayum.doRepoSetup()
        resultsdict = {}
        pkgspec = pkgspec.replace(',',' ')
        pkgtypes = pkgspec.split(' ')
        for pkgtype in pkgtypes:
            pkgtype = pkgtype.strip()
            obj = ayum.doPackageLists(pkgnarrow=pkgtype)
            if hasattr(obj, pkgtype):
                thislist = getattr(obj, pkgtype)
                output_list = sorted(map(str, thislist))
                resultsdict[pkgtype] = output_list

        return resultsdict

    def check_update(self, filter=[], repo=None):
        """Returns a list of packages due to be updated
           You can specify a filter using the standard yum wildcards
        """
        # parsePackages expects a list and doesn't react well if you send in a plain string with a wildcard in it
        # (the string is broken into a list and one of the list elements is "*" which matches every package)
        if type(filter) not in [list, tuple]:
            filter = [filter]

        import yum
        ayum = yum.YumBase()
        ayum.doConfigSetup()
        ayum.doTsSetup()
        if repo is not None:
            ayum.repos.enableRepo(repo)

        pkg_list = ayum.doPackageLists('updates').updates

        if filter:
            # exactmatch are all the packages with exactly the same name as one in the filter list
            # matched are all the packages that matched under any wildcards
            # unmatched are all the items in the filter list that didn't match anything
            exactmatch, matched, unmatched = yum.packages.parsePackages(pkg_list, filter)
            pkg_list = exactmatch + matched

        return map(str, pkg_list)

    def grep(self, word):
        """
        Grep info from module
        """
        results = {self.check_update:[]}
        update_res = self.check_update()
        results[self.check_update].extend([res for res in update_res if res.lower().find(word)!=-1])

        return results
    grep = func_module.findout(grep)

    def register_method_args(self):
        """
        Implementing the argument getter
        """

        return{
                'update':{
                    'args':{
                        'pkg':{
                            'type':'string',
                            'optional':True,
                            'description':"The yum pattern for updating package"
                            }
                        },
                    'description':"Updating system according to a specified pattern"
                    },
                'install':{
                    'args':{
                        'pkg':{
                            'type':'string',
                            'optional':False,
                            'description':"The yum pattern for installing package"
                            }
                        },
                    'description':"install package(s) according to a specified pattern"
                    },
                'remove':{
                    'args':{
                        'pkg':{
                            'type':'string',
                            'optional':False,
                            'description':"The yum pattern for removing package"
                            }
                        },
                    'description':"remove package(s) according to a specified pattern"
                    },
                'check_update':{
                    'args':{
                        'filter':{
                            'type':'list',
                            'optional':True,
                            'description':"A list of what you want to update"
                            },
                        'repo':{
                            'type':'string',
                            'optional':True,
                            'description':'Repo name to use for that update'
                            }
                        },
                    'description':"Cheking for updates with supplied filter patterns and repo"
                    }
                }
Exemple #8
0
class FileTracker(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.2"
    description = "Maintains a manifest of files to keep track of."

    def __load(self):
        """
        Parse file and return data structure.
        """

        filehash = {}
        if os.path.exists(CONFIG_FILE):
            config = open(CONFIG_FILE, "r")
            data = config.read()
            lines = data.split("\n")
            for line in lines:
                tokens = line.split(None)
                if len(tokens) < 2:
                    continue
                scan_mode = tokens[0]
                path = " ".join(tokens[1:])
                if str(scan_mode).lower() == "0":
                    scan_mode = 0
                else:
                    scan_mode = 1
                filehash[path] = scan_mode
        return filehash

    #==========================================================

    def __save(self, filehash):
        """
        Write data structure to file.
        """

        config = open(CONFIG_FILE, "w+")
        for (path, scan_mode) in filehash.iteritems():
            config.write("%s     %s\n" % (scan_mode, path))
        config.close()

    #==========================================================

    def track(self, file_name_globs, full_scan=0, recursive=0, files_only=0):
        """
        Adds files to keep track of.
        file_names can be a single filename, a list of filenames, a filename glob
           or a list of filename globs
        full_scan implies tracking the full contents of the file, defaults to off
        recursive implies tracking the contents of every subdirectory
        files_only implies tracking files that are files (not directories)
        """

        filehash = self.__load()
        filenameglobs = []

        # accept a single string or list
        filenameglobs.append(file_name_globs)
        if type(file_name_globs) == type([]):
            filenameglobs = file_name_globs

        def _recursive(original_filenames):
            for filename in original_filenames:
                for (dir, subdirs, subfiles) in os.walk(filename):
                    for subdir in subdirs:
                        yield "%s/%s" % (dir, subdir)
                    for subfile in subfiles:
                        yield "%s/%s" % (dir, subfile)

        # expand everything that might be a glob to a list
        # of names to track
        for filenameglob in filenameglobs:
            filenames = glob.glob(filenameglob)
            if recursive:
                filenames += _recursive(filenames)
            if files_only:
                filenames = [f for f in filenames if os.path.isfile(f)]
            for filename in filenames:
                filehash[filename] = full_scan
        self.__save(filehash)
        return 1

    #==========================================================

    def untrack(self, file_name_globs):
        """
        Stop keeping track of a file.
        file_name_globs can be a single filename, a list of filenames, a filename glob
           or a list of filename globs
        This routine is tolerant of most errors since we're forgetting about the file anyway.
        """

        filehash = self.__load()
        filenames = filehash.keys()
        for filename in filenames:
            for file_name_glob in file_name_globs:
                if fnmatch.fnmatch(filename, file_name_glob):
                    del filehash[filename]
        self.__save(filehash)
        return 1

    #==========================================================

    def inventory(self, flatten=1, checksum_enabled=1):
        """
        Returns information on all tracked files
        By default, 'flatten' is passed in as True, which makes printouts very clean in diffs
        for use by func-inventory.  If you are writting another software application, using flatten=False will
        prevent the need to parse the returns.
        """

        # XMLRPC feeds us strings from the CLI when it shouldn't
        flatten = int(flatten)
        checksum_enabled = int(checksum_enabled)

        filehash = self.__load()

        # we'll either return a very flat string (for clean diffs)
        # or a data structure
        if flatten:
            results = ""
        else:
            results = []

        for (file_name, scan_type) in filehash.iteritems():

            if not os.path.exists(file_name):
                if flatten:
                    results = results + "%s: does not exist\n" % file_name
                else:
                    results.append("%s: does not exist\n" % file_name)
                continue

            this_result = []

            # ----- always process metadata
            filestat = os.stat(file_name)
            mode = filestat[ST_MODE]
            mtime = filestat[ST_MTIME]
            uid = filestat[ST_UID]
            gid = filestat[ST_GID]
            if not os.path.isdir(file_name) and checksum_enabled:
                sum_handle = open(file_name)
                hash = self.__sumfile(sum_handle)
                sum_handle.close()
            else:
                hash = "N/A"

            # ------ what we return depends on flatten
            if flatten:
                this_result = "%s:  mode=%s  mtime=%s  uid=%s  gid=%s  md5sum=%s\n" % (
                    file_name, mode, mtime, uid, gid, hash)
            else:
                this_result = [file_name, mode, mtime, uid, gid, hash]

            # ------ add on file data only if requested
            if scan_type != 0 and os.path.isfile(file_name):
                tracked_file = open(file_name)
                data = tracked_file.read()
                if flatten:
                    this_result = this_result + "*** DATA ***\n" + data + "\n*** END DATA ***\n\n"
                else:
                    this_result.append(data)
                tracked_file.close()

            if os.path.isdir(file_name):
                if not file_name.endswith("/"):
                    file_name = file_name + "/"
                files = glob.glob(file_name + "*")
                if flatten:
                    this_result = this_result + "*** FILES ***\n" + "\n".join(
                        files) + "\n*** END FILES ***\n\n"
                else:
                    this_result.append({"files": files})

            if flatten:
                results = results + "\n" + this_result
            else:
                results.append(this_result)

        return results

    #==========================================================

    def grep(self, word):
        """
        Some search utility about tracked files
        """
        results = {self.inventory: []}
        tracked_files = self.inventory()

        if type(tracked_files
                ) == str and tracked_files.lower().find(word) != -1:
            results[self.inventory].append(tracked_files)

        else:
            for res in tracked_files:
                if res.lower().find(word) != -1:
                    results[self.inventory].append(res)

        return results

    grep = func_module.findout(grep)

    def __sumfile(self, fobj):
        """
        Returns an md5 hash for an object with read() method.
        credit: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/266486
        """

        m = md5.new()
        while True:
            d = fobj.read(8096)
            if not d:
                break
            m.update(d)
        return m.hexdigest()

    def register_method_args(self):
        """
        Implementing the argument getter part
        """

        return {
            'inventory': {
                'args': {
                    'flatten': {
                        'type': 'boolean',
                        'optional': True,
                        'default': True,
                        'description': "Show info in clean diffs"
                    },
                    'checksum_enabled': {
                        'type': 'boolean',
                        'optional': True,
                        'default': True,
                        'description': "Enable the checksum"
                    }
                },
                'description': "Returns information on all tracked files"
            },
            'track': {
                'args': {
                    'file_name_globs': {
                        'type': 'string',
                        'optional': False,
                        'description': "The file name to track (full path)"
                    },
                    'full_scan': {
                        'type': 'int',
                        'optional': True,
                        'default': 0,
                        'description': "The 0 is for off and 1 is for on"
                    },
                    'recursive': {
                        'type': 'int',
                        'optional': True,
                        'default': 0,
                        'description': "The 0 is for off and 1 is for on"
                    },
                    'files_only': {
                        'type': 'int',
                        'optional': True,
                        'default': 0,
                        'description': "Track only files (not dirs or links)"
                    }
                },
                'description': "Adds files to keep track of"
            },
            'untrack': {
                'args': {
                    'file_name_globs': {
                        'type': 'string',
                        'optional': False,
                        'description': "The file name to untrack (full path)"
                    }
                },
                'description': "Remove the track from specified file name"
            }
        }
Exemple #9
0
class SmartModule(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "Grabs status from SMART to see if your hard drives are ok."

    def info(self, flags="-q onecheck"):
        """
        Returns a struct of hardware information.  By default, this pulls down
        all of the devices.  If you don't care about them, set with_devices to
        False.
        """

        flags.replace(";", "")  # prevent stupidity

        cmd = sub_process.Popen("/usr/sbin/smartd %s" % flags,
                                stdout=sub_process.PIPE,
                                shell=True,
                                close_fds=True)
        data = cmd.communicate()[0]

        results = []

        for x in data.split("\n"):
            results.append(x)

        return (cmd.returncode, results)

    def grep(self, word):
        """
        grep some info from grep
        """
        results = {self.info: []}
        info_res = self.info()[1]

        if info_res:
            for res in info_res:
                if res.lower().find(word) != -1:
                    results[self.info].append(res)
        return results

    grep = func_module.findout(grep)

    def register_method_args(self):
        """
        Implementing method argument getter
        """

        return {
            'info': {
                'args': {
                    'flags': {
                        'type': 'string',
                        'optional': True,
                        'default': '-q onecheck',
                        'description': "Flags for smart command"
                    }
                },
                'description':
                "Grabs status from SMART to see if your hard drives are ok."
            }
        }
Exemple #10
0
class Service(func_module.FuncModule):

    version = "0.0.1"
    api_version = "0.0.1"
    description = "Allows for service control via func."

    def __command(self, service_name, command):

        service_name = service_name.strip() # remove useless spaces

        filename = os.path.join("/etc/init.d/",service_name)
        if os.path.exists(filename):
            return sub_process.call(["/sbin/service", service_name, command], close_fds=True, env={ 'LANG':'C' })
        else:
            raise codes.FuncException("Service not installed: %s" % service_name)

    def start(self, service_name):
        return self.__command(service_name, "start")

    def stop(self, service_name):
        return self.__command(service_name, "stop")

    def restart(self, service_name):
        return self.__command(service_name, "restart")

    def reload(self, service_name):
        return self.__command(service_name, "reload")

    def status(self, service_name):
        return self.__command(service_name, "status")

    def inventory(self):
        return {
            "running" : self.get_running(),
            "enabled" : self.get_enabled()
        }

    def grep(self,word):
        """
        Dig for some useful info in that module ...
        """
        final_dict = {self.get_running:[],
                      self.get_enabled:[]
                }
        running = self.get_running()
        enabled = self.get_enabled()

        #get enabled ones
        for e in enabled:
            if e[0].lower().find(word)!=-1:
                final_dict[self.get_enabled].append(e)

        #get running ones
        for e in running:
            if e[0].lower().find(word)!=-1:
                final_dict[self.get_running].append(e)

        return final_dict
    grep = func_module.findout(grep)


    def get_enabled(self):
        """
        Get the list of services that are enabled at the various runlevels.  Xinetd services
        only provide whether or not they are running, not specific runlevel info.
        """

        chkconfig = sub_process.Popen(["/sbin/chkconfig", "--list"], stdout=sub_process.PIPE, close_fds=True, env={ "LANG": "C" })
        data = chkconfig.communicate()[0]
        results = []
        for line in data.split("\n"):
            if line.find("0:") != -1:
                # regular services
                tokens = line.split()
                results.append((tokens[0],tokens[1:]))
            elif line.find(":") != -1 and not line.endswith(":"):
                # xinetd.d based services
                tokens = line.split()
                tokens[0] = tokens[0].replace(":","")
                results.append((tokens[0],tokens[1]))
        return results

    def get_running(self):
        """
        Get a list of which services are running, stopped, or disabled.
        """
        results = []

        # Get services
        services = self.get_enabled()

        init_return_codes = { 0: 'running', 1: 'dead', 2:'locked', 3:'stopped' }

        for service in services:
            filename = os.path.join("/etc/init.d/",service[0])
            # Run status for service
            try:
                init_exec = sub_process.Popen([filename, "status"], stdout=sub_process.PIPE, close_fds=True, env={ "LANG": "C" })
            except Exception, e:
                raise codes.FuncException("Service status error %s on initscript %s" % (e, filename))

            # Get status output
            data = init_exec.communicate()[0]

            # Wait for command to complete
            init_exec.wait()

            # Append the result, service name, return status and status output
            results.append((service[0], init_return_codes[init_exec.returncode], data))
        return results
Exemple #11
0
    def grep(self, word):
        """
        Grep some info from grep test
        especially netstat is very suitable
        for that purpose ...
        """
        results = {self.netstat: []}
        netstat_result = self.netstat()
        for res in netstat_result:
            if res.lower().find(word) != -1:
                results[self.netstat].append(res)

        return results

    grep = func_module.findout(grep)

    def __args_to_list(self, args):
        return [arg for arg in args]

    def __run_command(self, command, opts=[]):
        full_cmd = [command] + opts
        cmd = sub_process.Popen(full_cmd,
                                stdout=sub_process.PIPE,
                                close_fds=True)
        return [line for line in cmd.communicate()[0].split('\n')]

    def register_method_args(self):
        """
        Implementing method getter part
        """