Esempio n. 1
0
def config(cfgname, inisect):
    cfg = { }
    cfgpr = ConfigParser()
    try:
        cfgpr.readfp(open(cfgname))
    except IOError, e:
        raise ConfigError(str(e))
Esempio n. 2
0
 def __init__(self, name='redhat.repo'):
     ConfigParser.__init__(self)
     self.path = Path.join(self.PATH, name)
     self.manage_repos = 1
     if CFG.has_option('rhsm', 'manage_repos'):
         self.manage_repos = int(CFG.get('rhsm', 'manage_repos'))
     self.create()
Esempio n. 3
0
    def post(self, command, output_dir, vars):
        common.Template.post(self, command, output_dir, vars)
        #etc = os.path.join(vars['path'], 'etc', 'plone')
        #if not os.path.isdir(etc):
        #    os.makedirs(etc)
        cfg = os.path.join(vars['path'], 'etc', 'base.cfg')
        dst = os.path.join(vars['path'],
                           'etc', 'plone', 'plone%s.buildout.cfg' % vars['major'])
        vdst = os.path.join(vars['path'],
                           'etc', 'plone', 'plone%s.versions.cfg' % vars['major'])
        sdst = os.path.join(vars['path'],
                           'etc', 'plone', 'plone%s.sources.cfg' % vars['major'])
        ztkdst = os.path.join(vars['path'], 'etc', 'plone', 'ztk.versions.cfg')
        zaztkdst = os.path.join(vars['path'], 'etc', 'plone', 'zopeapp.versions.cfg')
        zdst = os.path.join(vars['path'],
                            'etc', 'plone', 'zope2.versions.cfg')
        os.rename(os.path.join(vars['path'], 'gitignore'),
                  os.path.join(vars['path'], '.gitignore'))
        bc = ConfigParser()
        bc.read(cfg)

        for f in (glob(os.path.join(output_dir, 'scripts/*'))
                  + glob(os.path.join(output_dir, 'etc/hudson/%s/build/*' % vars['project']))
                 ):
            os.chmod(f, 0700)
        # release KGS
        #try:
        #    open(vdst, 'w').write(
        #        urllib2.urlopen(vars['versions_url']).read()
        #    )
        #except Exception, e:
        suffix = vars['major']
        if vars['major'] > 3:
            suffix = self.name.replace('minitage.plone', '')
Esempio n. 4
0
 def __init__(self, name='redhat.repo'):
     ConfigParser.__init__(self)
     self.path = Path.join(self.PATH, name)
     self.manage_repos = 1
     if CFG.has_option('rhsm', 'manage_repos'):
         self.manage_repos = int(CFG.get('rhsm', 'manage_repos'))
     self.create()
Esempio n. 5
0
    def checkSSLvdsm(self):
        """check if vdsm is running as SSL or without it"""

        cfg = ConfigParser()
        cfg.read('/etc/vdsm/vdsm.conf')
        cfg.get('vars', 'ssl')

        return cfg.data.vars.ssl
Esempio n. 6
0
 def write(self):
     if not self.manage_repos:
         log.debug("Skipping write due to manage_repos setting: %s" %
                   self.path)
         return
     f = open(self.path, 'w')
     tidy_writer = TidyWriter(f)
     ConfigParser.write(self, tidy_writer)
     tidy_writer.close()
     f.close()
Esempio n. 7
0
    def update(self, repo):
        # Need to clear out the old section to allow unsetting options:
        # don't use remove section though, as that will reorder sections,
        # and move whitespace around (resulting in more and more whitespace
        # as time progresses).
        for (k, v) in self.items(repo.id):
            self.remove_option(repo.id, k)

        for k, v in repo.items():
            ConfigParser.set(self, repo.id, k, v)
Esempio n. 8
0
 def write(self):
     if not self.manage_repos:
         log.debug("Skipping write due to manage_repos setting: %s" %
                 self.path)
         return
     f = open(self.path, 'w')
     tidy_writer = TidyWriter(f)
     ConfigParser.write(self, tidy_writer)
     tidy_writer.close()
     f.close()
Esempio n. 9
0
    def update(self, repo):
        # Need to clear out the old section to allow unsetting options:
        # don't use remove section though, as that will reorder sections,
        # and move whitespace around (resulting in more and more whitespace
        # as time progresses).
        for (k, v) in self.items(repo.id):
            self.remove_option(repo.id, k)

        for k, v in repo.items():
            ConfigParser.set(self, repo.id, k, v)
 def parseDesktopFile(self):
     """
     Getting all necessary data from *.dektop file of the app
     """
     cmd = "rpm -qlf $(which %s)" % self.appCommand
     cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
     proc = Popen(cmd, shell=True, stdout=PIPE)
     # !HAVE TO check if the command and its desktop file exist
     if proc.wait() != 0:
         raise Exception("*.desktop file of the app not found")
     output = proc.communicate()[0].rstrip()
     self.desktopConfig = ConfigParser()
     self.desktopConfig.read(output)
Esempio n. 11
0
 def parseDesktopFile(self):
     """
     Getting all necessary data from *.dektop file of the app
     """
     cmd = 'ls -d /usr/share/applications/* | grep ".*%s.desktop"' % self.desktopFileName
     proc = Popen(cmd, shell=True, stdout=PIPE)
     # !HAVE TO check if the command and its desktop file exist
     if proc.wait() != 0:
         raise Exception("*.desktop file of the app not found")
     output = proc.communicate()[0].rstrip()
     desktopConfig = ConfigParser()
     desktopConfig.read(output)
     return desktopConfig
Esempio n. 12
0
 def test_enabling_yum_plugin_with_wrong_conf(self):
     """
     Test automatic enabling of configuration files of already plugins with wrong values in conf file.
     """
     self.init_yum_plugin_conf_files(conf_string=PKG_PLUGIN_CONF_FILE_WRONG_VALUE)
     plugin_list = YumPluginManager.enable_pkg_plugins()
     self.assertEqual(len(plugin_list), 2)
     for plugin_conf_file_name in YumPluginManager.PLUGINS:
         yum_plugin_config = ConfigParser()
         result = yum_plugin_config.read(YumPluginManager.YUM_PLUGIN_DIR + '/' + plugin_conf_file_name + '.conf')
         self.assertGreater(len(result), 0)
         is_plugin_enabled = yum_plugin_config.getint('main', 'enabled')
         self.assertEqual(is_plugin_enabled, 1)
     self.restore_yum_plugin_conf_files()
Esempio n. 13
0
    def __generate(self):
        if not os.path.exists(self.repofile):
            return []

        # Unfortuantely, we can not use the SafeConfigParser for zypper repo
        # files because the repository urls contains strings which the
        # SafeConfigParser don't like. It would crash with
        # ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '('
        if use_zypper:
            config = ConfigParser()
        else:
            config = SafeConfigParser()
        config.read(self.repofile)
        enabled_sections = [
            section for section in config.sections()
            if config.getboolean(section, "enabled")
        ]
        enabled_repos = []
        for section in enabled_sections:
            try:
                enabled_repos.append({
                    "repositoryid":
                    section,
                    "baseurl":
                    [self._format_baseurl(config.get(section, "baseurl"))]
                })
            except ImportError:
                break
        return enabled_repos
Esempio n. 14
0
 def test_enabling_yum_plugin_with_invalid_values(self):
     """
     Test automatic enabling of configuration files of already enabled plugins
     """
     self.init_plugin_conf_files(conf_string=YUM_PLUGIN_CONF_FILE_INVALID_VALUE)
     plugin_list = YumPluginManager.enable_yum_plugins()
     self.assertEqual(len(plugin_list), 2)
     for plugin_conf_file_name in YumPluginManager.YUM_PLUGINS:
         yum_plugin_config = ConfigParser()
         result = yum_plugin_config.read(YumPluginManager.DNF_PLUGIN_DIR + '/' + plugin_conf_file_name + '.conf')
         self.assertGreater(len(result), 0)
         is_plugin_enabled = yum_plugin_config.getint('main', 'enabled')
         self.assertEqual(is_plugin_enabled, 1)
     self.restore_plugin_conf_files()
Esempio n. 15
0
 def test_enabling_enabled_yum_plugin_int(self):
     """
     Test automatic enabling of configuration files of already enabled plugins
     """
     self.init_yum_plugin_conf_files(conf_string=PKG_PLUGIN_CONF_FILE_ENABLED_INT)
     plugin_list = YumPluginManager.enable_pkg_plugins()
     self.assertEqual(len(plugin_list), 0)
     for plugin_conf_file_name in YumPluginManager.PLUGINS:
         yum_plugin_config = ConfigParser()
         result = yum_plugin_config.read(YumPluginManager.YUM_PLUGIN_DIR + '/' + plugin_conf_file_name + '.conf')
         self.assertGreater(len(result), 0)
         is_plugin_enabled = yum_plugin_config.getint('main', 'enabled')
         self.assertEqual(is_plugin_enabled, 1)
     self.restore_yum_plugin_conf_files()
Esempio n. 16
0
 def test_not_enabling_disabled_yum_plugin(self):
     """
     Test not enabling (disabled in rhsm.conf) of configuration files of disabled plugins
     """
     self.init_yum_plugin_conf_files(conf_string=PKG_PLUGIN_CONF_FILE_DISABLED_BOOL)
     plugin_list = YumPluginManager.enable_pkg_plugins()
     self.assertEqual(len(plugin_list), 0)
     for plugin_conf_file_name in YumPluginManager.PLUGINS:
         yum_plugin_config = ConfigParser()
         result = yum_plugin_config.read(YumPluginManager.YUM_PLUGIN_DIR + '/' + plugin_conf_file_name + '.conf')
         self.assertGreater(len(result), 0)
         is_plugin_enabled = yum_plugin_config.getboolean('main', 'enabled')
         self.assertEqual(is_plugin_enabled, False)
     self.restore_yum_plugin_conf_files()
Esempio n. 17
0
    def __init__(self, filename):
        '''
        @param filename: absolute path to the repo file; the repo file does not need to
                         exist at the time of instantiation, the save method will write it
                         out if it doesn't
        @type  filename: string; may not be None

        @raise ValueError: if filename is missing
        '''
        if filename is None:
            raise ValueError(
                'Filename must be specified when creating a RepoFile')

        self.filename = filename
        self.parser = ConfigParser()
Esempio n. 18
0
 def test_enabling_enabled_yum_plugin_bool(self):
     """
     Test automatic enabling of configuration files of already enabled plugins
     """
     self.init_yum_plugin_conf_files(conf_string=PKG_PLUGIN_CONF_FILE_ENABLED_BOOL)
     plugin_list = YumPluginManager.enable_pkg_plugins()
     self.assertEqual(len(plugin_list), 0)
     for plugin_conf_file_name in YumPluginManager.PLUGINS:
         yum_plugin_config = ConfigParser()
         result = yum_plugin_config.read(YumPluginManager.YUM_PLUGIN_DIR + '/' + plugin_conf_file_name + '.conf')
         self.assertGreater(len(result), 0)
         # The file was not modified. We have to read value with with getboolean()
         is_plugin_enabled = yum_plugin_config.getboolean('main', 'enabled')
         self.assertEqual(is_plugin_enabled, True)
     self.restore_yum_plugin_conf_files()
Esempio n. 19
0
 def _has_changed(self):
     '''
     Check if the version on disk is different from what we have loaded
     '''
     on_disk = ConfigParser()
     on_disk.read(self.path)
     return not self._configparsers_equal(on_disk)
Esempio n. 20
0
 def __init__(self, name='redhat.repo'):
     ConfigParser.__init__(self)
     # note PATH get's expanded with chroot info, etc
     self.path = Path.join(self.PATH, name)
     self.repos_dir = Path.abs(self.PATH)
     self.manage_repos = 1
     if CFG.has_option('rhsm', 'manage_repos'):
         self.manage_repos = int(CFG.get('rhsm', 'manage_repos'))
     # Simulate manage repos turned off if no yum.repos.d directory exists.
     # This indicates yum is not installed so clearly no need for us to
     # manage repos.
     if not os.path.exists(self.repos_dir):
         log.warn("%s does not exist, turning manage_repos off." %
                  self.repos_dir)
         self.manage_repos = 0
     self.create()
Esempio n. 21
0
 def __init__(self, name='redhat.repo'):
     ConfigParser.__init__(self)
     # note PATH get's expanded with chroot info, etc
     self.path = Path.join(self.PATH, name)
     self.repos_dir = Path.abs(self.PATH)
     self.manage_repos = 1
     if CFG.has_option('rhsm', 'manage_repos'):
         self.manage_repos = int(CFG.get('rhsm', 'manage_repos'))
     # Simulate manage repos turned off if no yum.repos.d directory exists.
     # This indicates yum is not installed so clearly no need for us to
     # manage repos.
     if not os.path.exists(self.repos_dir):
         log.warn("%s does not exist, turning manage_repos off." %
                 self.repos_dir)
         self.manage_repos = 0
     self.create()
Esempio n. 22
0
    def read_ini_file(self, filename):
        cp = ConfigParser()
        cp.read(filename)

        if not self.backup_base_dir:
            self.backup_base_dir = cp.get('global', 'backup_base_dir')
        if not os.path.isdir(self.backup_base_dir):
            self.logger.info('Creating backup directory %s' %
                             self.backup_base_dir)
            os.makedirs(self.backup_base_dir)

        self.logger.debug("backup directory : " + self.backup_base_dir)
        self.dbstat = BackupStat(
            os.path.join(self.backup_base_dir, 'log', 'tisbackup.sqlite'))

        for section in cp.sections():
            if (section != 'global'):
                self.logger.debug("reading backup config " + section)
                backup_item = None
                type = cp.get(section, 'type')

                backup_item = backup_drivers[type](backup_name=section,
                                                   backup_dir=os.path.join(
                                                       self.backup_base_dir,
                                                       section),
                                                   dbstat=self.dbstat,
                                                   dry_run=self.dry_run)
                backup_item.read_config(cp)
                backup_item.verbose = self.verbose

                self.backup_list.append(backup_item)
Esempio n. 23
0
    def write(self,
              path=None,
              dependencies = None,
              src_uri = None,
              description = None,
              install_method = None,
              src_type = None,
              url = None,
              revision = None,
              category = None,
              src_opts = None,
              src_md5 = None,
              python = None,
              scm_branch = None,
             ):
        """Store/Update the minibuild config
        """
        to_write = OrderedDict(
            [('dependencies', dependencies),
            ('src_uri', src_uri),
            ('install_method', install_method),
            ('src_type', src_type),
            ('revision', revision),
            ('category', category),
            ('description', description),
            ('src_md5', src_md5),
            ('url', url),
            ('src_opts', src_opts),
            ('python', python),
            ('scm_branch', scm_branch),]
        )

        # open config
        if not path:
            path = self.path
        shutil.copy2(path, path+'.sav')
        wconfig = WritableConfigParser()
        wconfig.read(path)

        for metadata in to_write:
            value = to_write[metadata]
            if isinstance(value, list):
                if len(value) < 1:
                    value = None
                else:
                    value =  ' '.join(value)
            if value is not None:
                wconfig.set('minibuild' , metadata, value)

        # write back cofig
        fic = open(path, 'w')
        wconfig.write(fic)
        fic.flush()
        fic.close()
        newline(path)

        # reload minibuild
        self.load()
Esempio n. 24
0
def config(cfgname, inisect):
    cfg = { }
    cfgpr = ConfigParser()
    try:
        cfgpr.read(cfgname)
        cfg["sleep"] = cfgpr.get(inisect, "sleep")
        cfg["cmd"] = cfgpr.get(inisect, "cmd")
        cfg["file"] = cfgpr.get(inisect, "file")
        cfg["s3mode"] = cfgpr.get(inisect, "s3mode")
        cfg["s3host"] = cfgpr.get(inisect, "s3host")
        cfg["s3user"] = cfgpr.get(inisect, "s3user")
        cfg["s3pass"] = cfgpr.get(inisect, "s3pass")
        cfg["bucket"] = cfgpr.get(inisect, "s3bucket")
        cfg["prefix"] = cfgpr.get(inisect, "prefix")
    except NoSectionError:
        # Unfortunately if the file does not exist, we end here.
        raise ConfigError("Unable to open or find section " + inisect)
    except NoOptionError, e:
        raise ConfigError(str(e))
Esempio n. 25
0
    def _apply():
        debug('Write ini settings to %s' % filename)
        debug(config)

        cfg = ConfigParser()
        cfg.read(filename)
        for section, values in config.items():
            if not cfg.has_section(section):
                if strict_sections:
                    raise Exception('No section %s in ini file %s' % (section, filename))
                else:
                    cfg.add_section(section)

            for key, val in values.items():
                cfg.set(section, key, val)

        with open(filename, 'w') as configfile:
            cfg.write(configfile)

        event(on_apply)
Esempio n. 26
0
def archive_inv(gameDir, dummyPath, game='FO3', mode=True):
	'''Apply ArchiveInvalidationInvalidated.'''
	if mode:
		if game == 'NV':
			try:
				ini = ConfigParser()
				ini.read(os.environ['USERPROFILE'] + '\\My Games\\FalloutNV\\Fallout.ini')
				ini.set('Archive', 'bInvalidateOlderFiles', '1')
				ini.set('Archive', 'SArchiveList', 'Dummy.bsa,' + ini.get('Archive', 'SArchiveList'))
				
				iniFile = open(os.environ['USERPROFILE'] + '\\My Games\\FalloutNV\\Fallout.ini', 'w')
				ini.write(iniFile)
				
				bsa = open(dummyPath, 'rb').read()
				dummy = open(gameDir + '\\Data\\Dummy.bsa', 'wb')
				dummy.write(bsa)
				dummy.close()
				
				return True
			except IOError:
				return False
Esempio n. 27
0
    def read_ini_file(self,filename):
        cp = ConfigParser()
        cp.read(filename)

        if not self.backup_base_dir:
            self.backup_base_dir = cp.get('global','backup_base_dir')
        if not os.path.isdir(self.backup_base_dir):
            self.logger.info('Creating backup directory %s' % self.backup_base_dir)
            os.makedirs(self.backup_base_dir)

        self.logger.debug("backup directory : " + self.backup_base_dir)
        self.dbstat = BackupStat(os.path.join(self.backup_base_dir,'log','tisbackup.sqlite'))

        for section in cp.sections():
            if (section != 'global'):
                self.logger.debug("reading backup config " + section)
                backup_item = None
                type = cp.get(section,'type')

                backup_item = backup_drivers[type](backup_name=section,
                                                   backup_dir=os.path.join(self.backup_base_dir,section),dbstat=self.dbstat,dry_run=self.dry_run)
                backup_item.read_config(cp)
                backup_item.verbose = self.verbose

                self.backup_list.append(backup_item)
Esempio n. 28
0
    def __init__(self, filename):
        """
        @param filename: absolute path to the repo file; the repo file does not need to
                         exist at the time of instantiation, the save method will write it
                         out if it doesn't
        @type  filename: string; may not be None

        @raise ValueError: if filename is missing
        """
        if filename is None:
            raise ValueError("Filename must be specified when creating a RepoFile")

        self.filename = filename
        self.parser = ConfigParser()
Esempio n. 29
0
def _LoadActorDefs(filename):
    """Load actor definitions from Config/ActorDef/<filename>.ini.
    
    Instantiate an Actor from a definition with Actor.Create(<name>)
    
    If called a second time, it will reload the file, so the definitions
    will be updated, but any existing Actors that were created from them
    remain the same. 
    """
    path_try = os.path.join("Config", "ActorDef", filename + ".ini")
    if not (os.path.exists(path_try)):
        raise IOError, "Couldn't find " + path_try
    if not hasattr(Actor, "_defs"):
        Actor._defs = {}
    config = ConfigParser()
    config.read(path_try)
    for section in config.sections():
        definition = {}
        for item in config.items(section):
            definition[item[0]] = item[1]
        if 'class' not in definition:
            definition["class"] = "Actor"
        Actor._defs[section] = definition
Esempio n. 30
0
def _LoadLevelDef(filename):
    """Load level definitions from Config/Level/<filename>.ini.
    
    Call LoadLevel(<name>) to actually load all the Actors described in
    the file. 
    
    If called a second time, it will reload the file, so the definitions
    will be updated, but the existing world won't be affected. 
    """
    path_try = os.path.join("Config", "Level", filename + ".ini")
    if not (os.path.exists(path_try)):
        raise IOError, "Couldn't find " + path_try
    
    if not hasattr(angel, "_levels"):
        angel._levels = {}
    angel._levels[filename] = {}
    config = ConfigParser()
    config.read(path_try)
    for section in config.sections():
        actor = {}
        for item in config.items(section):
            actor[item[0]] = item[1]
        angel._levels[filename][section] = actor
Esempio n. 31
0
    def __init__(self, appName, critical=None, shortcut='<Control><Q>',
                 quitButton=None, timeout=10, forceKill=True,
                 parameters='', clean_dirs=None, polkit=False):
        """
        Initialize object App
        appName     command to run the app
        critical    what's the function we check? {start,quit}
        shortcut    default quit shortcut
        timeout     timeout for starting and shuting down the app
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start?
                    (only for startViaCommand)
        """
        self.appCommand = appName.lower()
        self.shortcut = shortcut
        self.timeout = timeout
        self.forceKill = forceKill
        self.critical = critical
        self.quitButton = quitButton
        # the result remains false until the correct result is verified
        self.result = False
        self.updateCorePattern()
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.polkit = polkit
        self.polkitPass = '******'
        self.clean_dirs = clean_dirs or []

        """
            Getting all necessary data from *.desktop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % appName
        #cmd2 = "grep %s.desktop" % self.appCommand
        #is it enough to search for .desktop?; vhumpa: no
        cmd += '|grep "^/usr/share/applications/.*\%s.desktop$"' % appName
        logging.debug("cmd = %s", cmd)
        proc = Popen(cmd, shell=True, stdout=PIPE)
        #have to check if the command and its desktop file exist
        #raise Exception, "*.desktop file of the app not found"
        #print("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        logging.debug("output = %s", output)
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)
Esempio n. 32
0
    def startService(self):
        cfgpr = ConfigParser()

        # TODO: config location from argparse or something
        cfgpr.read('config/config.ini')
        ip = cfgpr.get('main', 'ip')
        port = cfgpr.getint('main', 'port')
        tag = cfgpr.get('main', 'tag')
        password = cfgpr.get('main', 'password')

        server_data = {
                'ip': ip,
                'port': port,
                'tag': tag, # TODO: what is this:
                'secret': password, # TODO: refactor how this kind of data is passed and stored in factory
                }
        factory = getClientRconFactory(server_data)
        client  = TCPClient(server_data["ip"], server_data["port"], factory)
        client.setServiceParent(self)
        self.server["factory"] = factory
        MultiService.startService(self)
Esempio n. 33
0
from libtisbackup.common import *
import time
from flask import request, Flask, session, g, appcontext_pushed, redirect, url_for, abort, render_template, flash, jsonify, Response
from urlparse import urlparse
import json
import glob
import time

from config import huey
from tasks import run_export_backup, get_task, set_task

from tisbackup import tis_backup
import logging
import re

cp = ConfigParser()
cp.read("/etc/tis/tisbackup_gui.ini")

CONFIG = cp.get('general', 'config_tisbackup').split(",")
SECTIONS = cp.get('general', 'sections')
ADMIN_EMAIL = cp.get('general', 'ADMIN_EMAIL')

tisbackup_config_file = CONFIG[0]
config_number = 0

cp = ConfigParser()
cp.read(tisbackup_config_file)
backup_base_dir = cp.get('global', 'backup_base_dir')
dbstat = BackupStat(os.path.join(backup_base_dir, 'log', 'tisbackup.sqlite'))
mindate = None
error = None
Esempio n. 34
0
class RepoFile(object):
    """
    Represents a .repo file, including operations to manipulate its repositories and
    CRUD operations on the file itself.
    """

    # Be careful when changing the spacing below, the parser takes issue when the comment
    # indicator isn't in the first column. The blank line at the end is fine though.
    FILE_HEADER = """#
# Pulp Repositories
# Managed by Pulp client
#

"""

    def __init__(self, filename):
        """
        @param filename: absolute path to the repo file; the repo file does not need to
                         exist at the time of instantiation, the save method will write it
                         out if it doesn't
        @type  filename: string; may not be None

        @raise ValueError: if filename is missing
        """
        if filename is None:
            raise ValueError("Filename must be specified when creating a RepoFile")

        self.filename = filename
        self.parser = ConfigParser()

    # -- file manipulation ------------------------------------------------------------

    def delete(self):
        """
        If the repo file exists, it will be deleted. If not, this method does nothing.

        @raise Exception: if there is an error during the delete
        """
        if os.path.exists(self.filename):
            os.unlink(self.filename)

    def load(self, allow_missing=True):
        """
        Loads the repo file.

        @param allow_missing: if True, this call will not throw an error if the file cannot
                              be found; defaults to True
        @type  allow_missing: bool

        @raise Exception: if there is an error during the read
        """
        if allow_missing and not os.path.exists(self.filename):
            return

        r = Reader(self.filename)
        self.parser.readfp(r)

    def save(self):
        """
        Saves the current repositories to the repo file.

        @raise Exception: if there is an error during the write
        """
        # If the file doesn't exist, initialize with Pulp header
        first_write = not os.path.exists(self.filename)

        f = open(self.filename, "w")

        if first_write:
            f.write(RepoFile.FILE_HEADER)

        # Write the contents of the parser
        self.parser.write(f)

        f.close()

    # -- contents manipulation ------------------------------------------------------------

    def add_repo(self, repo):
        """
        Adds a new repo to this object, however the file is not saved.

        This is not saved as an object reference, so future changes to the passed in
        repo will not be captured in this RepoFile instance. If changes are made to
        the original Repo object, it must be passed into the RepoFile instance through
        update_repo in order for the changes to be captured.

        @param repo: repo to add; may not be None
        @type  repo: L{Repo}
        """
        self.parser.add_section(repo.id)
        self._repo_to_parser(repo)

    def remove_repo_by_name(self, repo_name):
        """
        Removes the repo with the given name. If the repo does not exist, this
        method does nothing.

        @param repo: identifies the repo to remove
        @type  repo: string
        """
        return self.parser.remove_section(repo_name)

    def update_repo(self, repo):
        """
        Updates the underlying store with the latest contents of a repo. The repo
        passed to this method must have been created prior to this call.

        The repo is not saved as an object reference. Instead, the values are captured
        to the underlying store at the point in time this is called.

        @param repo: repo instance containing updated values to store; cannot be None
        @type  repo: L{Repo}
        """
        self._repo_to_parser(repo)

    def get_repo(self, repo_id):
        """
        Loads a repo by repo ID. If the repo does not exist, returns None.

        @param repo_id: id of the repo to retrieve
        @type  repo_id: string

        @return: repo instance if one exists; None otherwise
        @rtype:  L{Repo}
        """
        if self.parser.has_section(repo_id):
            repo = self._parser_to_repo(repo_id)
            return repo
        else:
            return None

    def all_repos(self):
        """
        Returns a list of all repos in the store.

        @return: list of repo instances; empty list if there are none
        @rtype:  list of L{Repo}
        """
        repos = []
        for repo_name in self.parser.sections():
            repo = self._parser_to_repo(repo_name)
            repos.append(repo)

        return repos

    def _repo_to_parser(self, repo):
        """
        Adds the contents of the repo to the underlying store. This call assumes
        the parser section has already been created.

        @param repo: repo instance to update in the parser; cannot be None
        @type  repo: L{Repo}
        """
        for k, v in repo.items():
            if v:
                self.parser.set(repo.id, k, v)
            else:
                self.parser.remove_option(repo.id, k)

    def _parser_to_repo(self, repo_name):
        """
        Utility for converting the config parser section into a repo object.

        @param repo_name: name of the repo being retrieved from the store
        @type  repo_name: string

        @return: repo instance populated from the section data
        @rtype:  L{Repo}
        """
        repo = Repo(repo_name)
        for key, value in self.parser.items(repo_name):
            repo[key] = value

        return repo
Esempio n. 35
0
    def enable_yum_plugins(cls):
        """
        This function tries to enable yum plugins: subscription-manager and product-id.
        It takes no action, when automatic enabling of yum plugins is disabled in rhsm.conf.
        :return: It returns list of enabled plugins
        """

        # When user doesn't want to automatically enable yum plugins, then return empty list
        if cls.is_auto_enable_enabled() is False:
            log.info(
                'The rhsm.auto_enable_yum_plugins is disabled. Skipping the enablement of yum plugins.'
            )
            return []

        log.debug('The rhsm.auto_enable_yum_plugins is enabled')

        # List of successfully enabled plugins
        enabled_yum_plugins = []
        plugin_dir = ""
        if version.use_dnf:
            plugin_dir = cls.DNF_PLUGIN_DIR
        else:
            plugin_dir = cls.YUM_PLUGIN_DIR

        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for yum_plugin_name in cls.YUM_PLUGINS:
            yum_plugin_file_name = plugin_dir + '/' + yum_plugin_name + '.conf'
            yum_plugin_config = ConfigParser()
            try:
                result = yum_plugin_config.read(yum_plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading yum plugin config file '%s': %s. Skipping this file."
                    % (yum_plugin_file_name, err))
                continue

            if len(result) == 0:
                log.info(
                    'Configuration file of yum plugin: "%s" cannot be read' %
                    yum_plugin_file_name)
                continue

            is_plugin_enabled = False
            if not yum_plugin_config.has_section('main'):
                log.warn(
                    'Configuration file of yum plugin: "%s" does not include main section. Adding main section.'
                    % yum_plugin_file_name)
                yum_plugin_config.add_section('main')
            elif yum_plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = yum_plugin_config.getint(
                        'main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = yum_plugin_config.getboolean(
                            'main', 'enabled')
                    except ValueError:
                        log.warn(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)"
                            % yum_plugin_file_name)

            if is_plugin_enabled == cls.YUM_PLUGIN_ENABLED:
                log.debug('Yum plugin: "%s" already enabled. Nothing to do.' %
                          yum_plugin_file_name)
            else:
                log.warn('Enabling yum plugin: "%s".' % yum_plugin_file_name)
                # Change content of plugin configuration file and enable this plugin.
                with open(yum_plugin_file_name, 'w') as cfg_file:
                    yum_plugin_config.set('main', 'enabled',
                                          cls.YUM_PLUGIN_ENABLED)
                    yum_plugin_config.write(cfg_file)
                enabled_yum_plugins.append(yum_plugin_file_name)

        return enabled_yum_plugins
Esempio n. 36
0
    def _enable_plugins(cls, pkg_mgr_name, plugin_dir):
        """
        This class method tries to enable plugins for DNF or YUM
        :param pkg_mgr_name: It can be "dnf" or "yum"
        :type pkg_mgr_name: str
        :param plugin_dir: Directory with configuration files for (dnf/yum) plugins
        :type plugin_dir: str
        :return:
        """
        # List of successfully enabled plugins
        enabled_lugins = []
        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for plugin_name in cls.PLUGINS:
            plugin_file_name = plugin_dir + '/' + plugin_name + '.conf'
            plugin_config = ConfigParser()
            try:
                result = plugin_config.read(plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading %s plugin config file '%s': %s. Skipping this file."
                    % (pkg_mgr_name, plugin_file_name, err))
                continue

            if len(result) == 0:
                log.info(
                    'Configuration file of %s plugin: "%s" cannot be read' %
                    (pkg_mgr_name, plugin_file_name))
                continue

            is_plugin_enabled = False
            if not plugin_config.has_section('main'):
                log.warning(
                    'Configuration file of %s plugin: "%s" does not include main section. Adding main section.'
                    % (pkg_mgr_name, plugin_file_name))
                plugin_config.add_section('main')
            elif plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = plugin_config.getint('main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = plugin_config.getboolean(
                            'main', 'enabled')
                    except ValueError:
                        log.warning(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)"
                            % plugin_file_name)

            if is_plugin_enabled == cls.PLUGIN_ENABLED:
                log.debug('%s plugin: "%s" already enabled. Nothing to do.' %
                          (pkg_mgr_name, plugin_file_name))
            else:
                log.warning('Enabling %s plugin: "%s".' %
                            (pkg_mgr_name, plugin_file_name))
                # Change content of plugin configuration file and enable this plugin.
                with open(plugin_file_name, 'w') as cfg_file:
                    plugin_config.set('main', 'enabled', cls.PLUGIN_ENABLED)
                    plugin_config.write(cfg_file)
                enabled_lugins.append(plugin_file_name)

        return enabled_lugins
Esempio n. 37
0
def main():
    (options, args) = parser.parse_args()

    if len(args) != 1:
        print "ERROR : You must provide one action to perform"
        parser.print_usage()
        sys.exit(2)

    backup_start_date = datetime.datetime.now().strftime('%Y%m%d-%Hh%Mm%S')

    # options
    action = args[0]
    if action == "listdrivers":
        for t in backup_drivers:
            print backup_drivers[t].get_help()
        sys.exit(0)

    config_file = options.config
    dry_run = options.dry_run
    verbose = options.verbose

    loglevel = options.loglevel

    # setup Logger
    logger = logging.getLogger('tisbackup')
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(hdlr)

    # set loglevel
    if loglevel in ('debug', 'warning', 'info', 'error', 'critical'):
        numeric_level = getattr(logging, loglevel.upper(), None)
        if not isinstance(numeric_level, int):
            raise ValueError('Invalid log level: %s' % loglevel)
        logger.setLevel(numeric_level)

    # Config file
    if not os.path.isfile(config_file):
        logger.error("Error : could not find file : " + config_file +
                     ", please check the path")
    logger.info("Using " + config_file + " config file")

    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = options.backup_base_dir or cp.get(
        'global', 'backup_base_dir')
    log_dir = os.path.join(backup_base_dir, 'log')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # if we run the nagios check, we don't create log file, everything is piped to stdout
    if action != 'checknagios':
        hdlr = logging.FileHandler(
            os.path.join(log_dir, 'tisbackup_%s.log' % (backup_start_date)))
        hdlr.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
        logger.addHandler(hdlr)

    # Main
    backup = tis_backup(dry_run=dry_run,
                        verbose=verbose,
                        backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = options.sections.split(',') if options.sections else []

    all_sections = [
        backup_item.backup_name for backup_item in backup.backup_list
    ]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    if dry_run:
        logger.warning(
            "WARNING : DRY RUN, nothing will be done, just printing on screen..."
        )

    if action == "backup":
        backup.process_backup(backup_sections)
    elif action == "exportbackup":
        if not options.exportdir:
            raise Exception(
                'No export directory supplied dor exportbackup action')
        backup.export_backups(backup_sections, options.exportdir)
    elif action == "cleanup":
        backup.cleanup_backup_section(backup_sections)
    elif action == "checknagios":
        backup.checknagios(backup_sections)
    elif action == "dumpstat":
        for s in backup_sections:
            backup.dbstat.last_backups(s, count=options.statscount)
    elif action == "retryfailed":
        backup.retry_failed_backups()
    elif action == "register_existing":
        backup.register_existingbackups(backup_sections)

    else:
        logger.error('Unhandled action "%s", quitting...', action)
        sys.exit(1)
Esempio n. 38
0
class RepoFile(object):
    '''
    Represents a .repo file, including operations to manipulate its repositories and
    CRUD operations on the file itself.
    '''

    # Be careful when changing the spacing below, the parser takes issue when the comment
    # indicator isn't in the first column. The blank line at the end is fine though.
    FILE_HEADER = '''#
# Pulp Repositories
# Managed by Pulp client
#

'''

    def __init__(self, filename):
        '''
        @param filename: absolute path to the repo file; the repo file does not need to
                         exist at the time of instantiation, the save method will write it
                         out if it doesn't
        @type  filename: string; may not be None

        @raise ValueError: if filename is missing
        '''
        if filename is None:
            raise ValueError(
                'Filename must be specified when creating a RepoFile')

        self.filename = filename
        self.parser = ConfigParser()

    # -- file manipulation ------------------------------------------------------------

    def delete(self):
        '''
        If the repo file exists, it will be deleted. If not, this method does nothing.

        @raise Exception: if there is an error during the delete
        '''
        if os.path.exists(self.filename):
            os.unlink(self.filename)

    def load(self, allow_missing=True):
        '''
        Loads the repo file.

        @param allow_missing: if True, this call will not throw an error if the file cannot
                              be found; defaults to True
        @type  allow_missing: bool

        @raise Exception: if there is an error during the read
        '''
        if allow_missing and not os.path.exists(self.filename):
            return

        r = Reader(self.filename)
        self.parser.readfp(r)

    def save(self):
        '''
        Saves the current repositories to the repo file.

        @raise Exception: if there is an error during the write
        '''
        # If the file doesn't exist, initialize with Pulp header
        first_write = not os.path.exists(self.filename)

        f = open(self.filename, 'w')

        if first_write:
            f.write(RepoFile.FILE_HEADER)

        # Write the contents of the parser
        self.parser.write(f)

        f.close()

    # -- contents manipulation ------------------------------------------------------------

    def add_repo(self, repo):
        '''
        Adds a new repo to this object, however the file is not saved.

        This is not saved as an object reference, so future changes to the passed in
        repo will not be captured in this RepoFile instance. If changes are made to
        the original Repo object, it must be passed into the RepoFile instance through
        update_repo in order for the changes to be captured.

        @param repo: repo to add; may not be None
        @type  repo: L{Repo}
        '''
        self.parser.add_section(repo.id)
        self._repo_to_parser(repo)

    def remove_repo_by_name(self, repo_name):
        '''
        Removes the repo with the given name. If the repo does not exist, this
        method does nothing.

        @param repo: identifies the repo to remove
        @type  repo: string
        '''
        return self.parser.remove_section(repo_name)

    def update_repo(self, repo):
        '''
        Updates the underlying store with the latest contents of a repo. The repo
        passed to this method must have been created prior to this call.

        The repo is not saved as an object reference. Instead, the values are captured
        to the underlying store at the point in time this is called.

        @param repo: repo instance containing updated values to store; cannot be None
        @type  repo: L{Repo}
        '''
        self._repo_to_parser(repo)

    def get_repo(self, repo_id):
        '''
        Loads a repo by repo ID. If the repo does not exist, returns None.

        @param repo_id: id of the repo to retrieve
        @type  repo_id: string

        @return: repo instance if one exists; None otherwise
        @rtype:  L{Repo}
        '''
        if self.parser.has_section(repo_id):
            repo = self._parser_to_repo(repo_id)
            return repo
        else:
            return None

    def all_repos(self):
        '''
        Returns a list of all repos in the store.

        @return: list of repo instances; empty list if there are none
        @rtype:  list of L{Repo}
        '''
        repos = []
        for repo_name in self.parser.sections():
            repo = self._parser_to_repo(repo_name)
            repos.append(repo)

        return repos

    def _repo_to_parser(self, repo):
        '''
        Adds the contents of the repo to the underlying store. This call assumes
        the parser section has already been created.

        @param repo: repo instance to update in the parser; cannot be None
        @type  repo: L{Repo}
        '''
        for k, v in repo.items():
            if v:
                self.parser.set(repo.id, k, v)
            else:
                self.parser.remove_option(repo.id, k)

    def _parser_to_repo(self, repo_name):
        '''
        Utility for converting the config parser section into a repo object.

        @param repo_name: name of the repo being retrieved from the store
        @type  repo_name: string

        @return: repo instance populated from the section data
        @rtype:  L{Repo}
        '''
        repo = Repo(repo_name)
        for key, value in self.parser.items(repo_name):
            repo[key] = value

        return repo
Esempio n. 39
0
def main():
    (options,args)=parser.parse_args()

    if len(args) != 1:
        print "ERROR : You must provide one action to perform"
        parser.print_usage()
        sys.exit(2)

    backup_start_date = datetime.datetime.now().strftime('%Y%m%d-%Hh%Mm%S')

    # options
    action = args[0]
    if action == "listdrivers":
        for t in backup_drivers:
            print backup_drivers[t].get_help()
        sys.exit(0)

    config_file =options.config
    dry_run = options.dry_run
    verbose = options.verbose

    loglevel = options.loglevel

    # setup Logger
    logger = logging.getLogger('tisbackup')
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(hdlr)

    # set loglevel
    if loglevel in ('debug','warning','info','error','critical'):
        numeric_level = getattr(logging, loglevel.upper(), None)
        if not isinstance(numeric_level, int):
            raise ValueError('Invalid log level: %s' % loglevel)
        logger.setLevel(numeric_level)

    # Config file
    if not os.path.isfile(config_file):
        logger.error("Error : could not find file : " + config_file + ", please check the path")
    logger.info("Using " + config_file + " config file")

    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = options.backup_base_dir or cp.get('global','backup_base_dir')
    log_dir = os.path.join(backup_base_dir,'log')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # if we run the nagios check, we don't create log file, everything is piped to stdout
    if action!='checknagios':
        hdlr = logging.FileHandler(os.path.join(log_dir,'tisbackup_%s.log' % (backup_start_date)))
        hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
        logger.addHandler(hdlr)

    # Main
    backup = tis_backup(dry_run=dry_run,verbose=verbose,backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = options.sections.split(',') if options.sections else []

    all_sections = [backup_item.backup_name for backup_item in backup.backup_list]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    if dry_run:
        logger.warning("WARNING : DRY RUN, nothing will be done, just printing on screen...")

    if action == "backup":
        backup.process_backup(backup_sections)
    elif action == "exportbackup":
        if not options.exportdir:
            raise Exception('No export directory supplied dor exportbackup action')
        backup.export_backups(backup_sections,options.exportdir)
    elif action == "cleanup":
        backup.cleanup_backup_section(backup_sections)
    elif action == "checknagios":
        backup.checknagios(backup_sections)
    elif action == "dumpstat":
        for s in backup_sections:
            backup.dbstat.last_backups(s,count=options.statscount)
    elif action == "retryfailed":
        backup.retry_failed_backups()
    elif action == "register_existing":
        backup.register_existingbackups(backup_sections)


    else:
        logger.error('Unhandled action "%s", quitting...',action)
        sys.exit(1)
Esempio n. 40
0
 def read(self):
     ConfigParser.read(self, self.path)
Esempio n. 41
0
class App():
    """
    Does all basic events with app
    """
    def __init__(self, appName, critical=None, shortcut='<Control><Q>',
                 quitButton=None, timeout=10, forceKill=True,
                 parameters='', clean_dirs=None, polkit=False):
        """
        Initialize object App
        appName     command to run the app
        critical    what's the function we check? {start,quit}
        shortcut    default quit shortcut
        timeout     timeout for starting and shuting down the app
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start?
                    (only for startViaCommand)
        """
        self.appCommand = appName.lower()
        self.shortcut = shortcut
        self.timeout = timeout
        self.forceKill = forceKill
        self.critical = critical
        self.quitButton = quitButton
        # the result remains false until the correct result is verified
        self.result = False
        self.updateCorePattern()
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.polkit = polkit
        self.polkitPass = '******'
        self.clean_dirs = clean_dirs or []

        """
            Getting all necessary data from *.desktop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % appName
        #cmd2 = "grep %s.desktop" % self.appCommand
        #is it enough to search for .desktop?; vhumpa: no
        cmd += '|grep "^/usr/share/applications/.*\%s.desktop$"' % appName
        logging.debug("cmd = %s", cmd)
        proc = Popen(cmd, shell=True, stdout=PIPE)
        #have to check if the command and its desktop file exist
        #raise Exception, "*.desktop file of the app not found"
        #print("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        logging.debug("output = %s", output)
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)

    def end(self):
        """
        Ends the test with correct return value
        """
        if self.result:
            #print "PASS"
            sys.exit(0)
        else:
            sys.exit("FAIL")

    def updateResult(self, result):
        self.result = result

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def getCategories(self):
        return self.desktopConfig.get('Desktop Entry', 'categories')

    def getMenuGroups(self):
        """
        Convert group list to the one correct menu group
        """
        groupsList = self.getCategories().split(';')
        groupsList.reverse()
        groupConversionDict = {
            'Accessibility': 'Universal Access',
            'System': 'System Tools',
            'Development': 'Programming',
            'Network': 'Internet',
            'Office': 'Office',
            'Graphics': 'Graphics',
            'Game': 'Games',
            'Education': 'Education',
            'Utility': 'Accessories',
            'AudioVideo': 'Sound &amp; Video'
        }

        for i in groupsList:
            if i in groupConversionDict:
                return groupConversionDict[i]

    def isRunning(self):
        """
        Is the app running?
        """
        #print "*** Checking if '%s' is running" % self.internCommand
        app = root

        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.internCommand:
                app = i
                break

        if app.isChild(roleName='frame', recursive=False):
            #print "*** The app '%s' is running" % self.internCommand
            return True
        else:
            #print "*** The app '%s' is not running" % self.internCommand
            return False

    def kill(self):
        """
        Kill the app via 'killall'
        """
        #print "*** Killing all '%s' instances" % self.appCommand
        #return Popen("killall " + self.appCommand, shell = True).wait()
        return Popen("pkill -u `whoami` -9 " + self.appCommand,
                     shell=True).wait()

    def updateCorePattern(self):
        """
        Update string in /proc/sys/kernel/core_pattern to catch
        possible return code
        """
        #Popen("sudo rm -rf /tmp/cores", shell = True).wait()
        #Popen("mkdir /tmp/cores", shell = True).wait()
        #Popen("chmod a+rwx /tmp/cores", shell = True).wait()
        #Popen("echo \"/tmp/cores/core.%e.%s.%p\" \
        #       | sudo tee /proc/sys/kernel/core_pattern", shell = True).wait()
        pass

    def existsCoreDump(self):
        """
        Check if there is core dump created
        """
        #dirPath = "/tmp/cores/"
        #files = os.listdir(dirPath)
        #regexp = "core\.%s\.[0-9]{1,3}\.[0-9]*" % self.appCommand
        #for f in files:
        #    if re.match(regexp, f):
        #        return int(f.split(".")[2])
        return 0

    def startViaMenu(self):
        """
        Start the app via Gnome Shell menu
        """
        internCritical = (self.critical == 'start')

        #check if the app is running
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            if self.isRunning():
                if internCritical:
                    self.updateResult(False)
                #print "!!! The app is running but it shouldn't be"
                return False
            else:
                #print "*** The app has been killed succesfully"
                pass

        try:
            #panel button Activities
            gnomeShell = root.application('gnome-shell')
            activities = gnomeShell.child(name='Activities', roleName='label')
            activities.click()
            sleep(6)  # time for overview to appear

            #menu Applications
            x, y = getDashIconPosition('Show Applications')
            absoluteMotion(x, y)
            sleep(1)
            click(x, y)
            sleep(4)  # time for all the oversized app icons to appear

            #submenu that contains the app
            submenu = gnomeShell.child(name=self.getMenuGroups(),
                                       roleName='list item')
            submenu.click()
            sleep(4)

            #the app itself
            app = gnomeShell.child(name=self.getName(), roleName='label')
            app.click()

            #if there is a polkit
            if self.polkit:
                sleep(3)
                typeText(self.polkitPass)
                keyCombo('<Enter>')

            sleep(self.timeout)

            if self.isRunning():
                #print "*** The app started successfully"
                if internCritical:
                    self.updateResult(True)
                return True
            else:
                #print "!!! The app is not running but it should be"
                if internCritical:
                    self.updateResult(False)
                return False
        except SearchError:
            #print "!!! Lookup error while passing the path"
            if internCritical:
                self.updateResult(False)
            return False

    def startViaCommand(self):
        """
        Start the app via command
        """
        internCritical = (self.critical == 'start')
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            if self.isRunning():
                if internCritical:
                    self.updateResult(False)
                #print "!!! The app is running but it shouldn't be"
                return False
            else:
                pass
                #print "*** The app has been killed succesfully"

        returnValue = 0
        command = "%s %s &" % (self.appCommand, self.parameters)
        import os
        os.system(command)
        returnValue = 1
        #returnValue = utilsRun(command, timeout = 1, dumb = True)

        #if there is a polkit
        if self.polkit:
            sleep(3)
            typeText(self.polkitPass)
            keyCombo('<Enter>')

        start_time = 0
        while start_time < self.timeout:
            if self.isRunning():
                break
            sleep(0.5)
            start_time += 0.5

        #check the returned values
        if returnValue is None:
            if internCritical:
                self.updateResult(False)
            #print "!!! The app command could not be found"
            return False
        else:
            if self.isRunning():
                if internCritical:
                    self.updateResult(True)
                #print "*** The app started successfully"
                return True
            else:
                if internCritical:
                    self.updateResult(False)
                    #print "!!! The app did not started despite " \
                    #        + "the fact that the command was found"
                return False

    def closeViaShortcut(self):
        """
        Close the app via shortcut
        """
        internCritical = (self.critical == 'quit')

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            #print "!!! The app does not seem to be running"
            return False

        keyCombo(self.shortcut)
        sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            #print "!!! The app is running but it shouldn't be"
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                # print "!!! The app closed with core dump created. Signal %d"\
                #        % self.existsCoreDump()
                return False
            if internCritical:
                self.updateResult(True)
            #print "*** The app was successfully closed"
            return True

    def closeViaMenu(self):
        """
        Close app via menu button
        """
        internCritical = (self.critical == 'quit')

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            #print "!!! The app does not seem to be running"
            return False

        #bind to the right app
        app = root
        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.internCommand:
                app = i
                break
        app = app  # variable app is not used FIXME

        #try to bind the menu and the button
        try:
            firstSubmenu = self.getMenuNth(0)
            firstSubmenu.click()
            length = len(firstSubmenu.children)
            closeButton = firstSubmenu.children[length - 1]
            if self.quitButton is None:
                while re.search('(Close|Quit|Exit)', closeButton.name) is None:
                    length = length - 1
                    closeButton = firstSubmenu.children[length]
                    if length < 0:
                        if internCritical:
                            self.update(False)
                        #print "!!! The app quit button coldn't be found"
                        return False
            else:
                closeButton = firstSubmenu.child(self.quitButton)
        except SearchError:
            if internCritical:
                self.updateResult(False)
            #print "!!! The app menu bar or the quit button could'n be found"
            if self.forceKill:
                self.kill()
            return False

        sleep(2)  # timeout until menu appear
        #print "*** Trying to click to '%s'" % closeButton
        closeButton.click()
        sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            #print "!!! The app is running but it shouldn't be"
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                # print "!! The app closed with core dump created. Signal %d" \
                # % self.existsCoreDump()
                return False
            if internCritical:
                self.updateResult(True)
            #print "*** The app was successfully closed"
            return True

    def getMenuNamed(self, menuName):
        """
        Return submenu with name specified with 'menuName'
        """
        #bind to the right app
        app = root
        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.internCommand:
                app = i
                break

        #try to bind the menu and the button
        try:
            appMenu = app.child(roleName='menu bar')
            return appMenu.child(name=menuName)
        except:
            return None

    def getMenuNth(self, nth):
        """
        Return nth submenu
        """
        #bind to the right app
        app = root
        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.internCommand:
                app = i
                break

        #try to bind the menu and the button
        try:
            appMenu = app.child(roleName='menu bar')
            return appMenu.children[nth]
        except:
            return None

    def getGnomePanelMenu(self):
        """
        Return object of gnome-panel menu of the app
        """
        try:
            app = root.application('gnome-shell')
            menu = app.child(roleName='menu')
            return menu.child(self.getName(), roleName='label')
        except:
            raise Exception("Gnome-panel menu of the app could not be found!")

    def openGnomePanelMenu(self):
        """
        Click to the gnome-panel menu
        """
        menu = self.getGnomePanelMenu()
        if menu is not None:
            menu.click()
        else:
            raise Exception("Gnome-panel menu of the app could not be found!")

    def getGnomePanelMenuItems(self):
        """
        Return a list of objects in gnome-panel app menu
        """
        quitButton = self.getGnomePanelQuit()
        if quitButton is None:
            return []
        else:
            return quitButton.get_parent().children

    def getGnomePanelQuit(self):
        """
        Return object of Quit button in gnome-panel menu
        It's the only way how to find out the gnome-panel menu...
        """
        try:
            return root.application('gnome-shell').child('Quit')
        except:
            raise Exception("Quit menu item at gnome-panel menu" +
                            " could not be found!")

    def closeViaGnomePanel(self):
        """
        Close the app via menu at gnome-panel
        """
        internCritical = (self.critical == 'quit')

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            #print "!!! The app does not seem to be running"
            return False

        self.openGnomePanelMenu()
        closeButton = self.getGnomePanelQuit()

        sleep(2)  # timeout until menu appear
        #print "*** Trying to click to '%s'" % closeButton
        closeButton.click()
        sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            #print "!!! The app is running but it shouldn't be"
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                # print "!!! The app closed with core dumps. Signal %d" % \
                #        self.existsCoreDump()
                return False
            if internCritical:
                self.updateResult(True)
            #print "*** The app was successfully closed"
            return True
Esempio n. 42
0
def read_config():
    config_file = CONFIG[config_number]
    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = cp.get('global', 'backup_base_dir')
    backup = tis_backup(backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = SECTIONS or []

    all_sections = [
        backup_item.backup_name for backup_item in backup.backup_list
    ]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    result = []
    if not backup_sections:
        sections = [
            backup_item.backup_name for backup_item in backup.backup_list
        ]

    for backup_item in backup.backup_list:
        if backup_item.backup_name in backup_sections:
            b = {}
            for attrib_name in backup_item.required_params + backup_item.optional_params:
                if hasattr(backup_item, attrib_name):
                    b[attrib_name] = getattr(backup_item, attrib_name)
            result.append(b)

    backup_dict = {}
    backup_dict['rsync_ssh_list'] = []
    backup_dict['rsync_btrfs_list'] = []
    backup_dict['rsync_list'] = []
    backup_dict['null_list'] = []
    backup_dict['pgsql_list'] = []
    backup_dict['mysql_list'] = []
    backup_dict['sqlserver_list'] = []
    backup_dict['xva_list'] = []
    backup_dict['metadata_list'] = []
    backup_dict['switch_list'] = []
    backup_dict['oracle_list'] = []
    backup_dict['samba_list'] = []
    for row in result:
        backup_name = row['backup_name']
        server_name = row['server_name']
        backup_type = row['type']
        if backup_type == "xcp-dump-metadata":
            backup_dict['metadata_list'].append(
                [server_name, backup_name, backup_type, ""])
        if backup_type == "rsync+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_ssh_list'].append(
                [server_name, backup_name, backup_type, remote_dir])
        if backup_type == "rsync+btrfs+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_btrfs_list'].append(
                [server_name, backup_name, backup_type, remote_dir])
        if backup_type == "rsync":
            remote_dir = row['remote_dir']
            backup_dict['rsync_list'].append(
                [server_name, backup_name, backup_type, remote_dir])
        if backup_type == "null":
            backup_dict['null_list'].append(
                [server_name, backup_name, backup_type, ""])
            if backup_type == "pgsql+ssh":
                db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
                backup_dict['pgsql_list'].append(
                    [server_name, backup_name, backup_type, db_name])
            if backup_type == "mysql+ssh":
                db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
                backup_dict['mysql_list'].append(
                    [server_name, backup_name, backup_type, db_name])
        if backup_type == "sqlserver+ssh":
            db_name = row['db_name']
            backup_dict['sqlserver_list'].append(
                [server_name, backup_name, backup_type, db_name])
        if backup_type == "oracle+ssh":
            db_name = row['db_name']
            backup_dict['oracle_list'].append(
                [server_name, backup_name, backup_type, db_name])
        if backup_type == "xen-xva":
            backup_dict['xva_list'].append(
                [server_name, backup_name, backup_type, ""])
        if backup_type == "switch":
            backup_dict['switch_list'].append(
                [server_name, backup_name, backup_type, ""])
        if backup_type == "samba4":
            backup_dict['samba_list'].append(
                [server_name, backup_name, backup_type, ""])
    return backup_dict
    def __build_yum_config(self, repoid):
        """
        Builds the YUM config that will be used for YUM initialization.

        @param repoid   The ID of repository to be analyzed.

        @return The path to generated YUM config file.
        """
        config_path = temporaries.create_temporary_file("yum.conf")
        config = ConfigParser()
        # FIXME: This config was get from my Ubuntu default yum config, maybe
        # we should somehow modify it.
        config.add_section("main")
        cache_path = temporaries.create_temporary_directory("yum.cache")
        config.set("main", "cachedir", cache_path)
        config.set("main", "keepcache", "1")
        config.set("main", "debuglevel", "2")
        log_path = temporaries.create_temporary_file("yum.log")
        config.set("main", "logfile", log_path)
        # FIXME: Is this a reason why ARM RPMs are ignored?
        config.set("main", "exactarch", "1")
        config.set("main", "obsoletes", "1")

        config.add_section(repoid)
        config.set(repoid, "name", "Analyzed repository")
        config.set(repoid, "baseurl",
                   "file://{0}".format(self.repository_path))

        with open(config_path, "w") as config_file:
            config.write(config_file)
            config_file.close()

        return config_path
Esempio n. 44
0
import time 
from flask import request, Flask,  session, g, appcontext_pushed, redirect, url_for, abort, render_template, flash, jsonify, Response
from urlparse import urlparse
import json
import glob
import time

from config import huey 
from tasks import run_export_backup, get_task, set_task

from tisbackup import tis_backup
import logging
import re


cp = ConfigParser()
cp.read("/etc/tis/tisbackup_gui.ini")

CONFIG = cp.get('general','config_tisbackup').split(",")
SECTIONS = cp.get('general','sections')
ADMIN_EMAIL = cp.get('general','ADMIN_EMAIL')

tisbackup_config_file= CONFIG[0]
config_number=0


cp = ConfigParser()
cp.read(tisbackup_config_file)
backup_base_dir = cp.get('global','backup_base_dir')
dbstat = BackupStat(os.path.join(backup_base_dir,'log','tisbackup.sqlite'))
mindate = None
Esempio n. 45
0
def read_config():
    config_file = CONFIG[config_number]
    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = cp.get('global','backup_base_dir')
    backup = tis_backup(backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = SECTIONS or []

    all_sections = [backup_item.backup_name for backup_item in backup.backup_list]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    result = []
    if not backup_sections:
        sections = [backup_item.backup_name for backup_item in backup.backup_list]

    for backup_item in backup.backup_list:
        if backup_item.backup_name in backup_sections:
            b = {}
            for attrib_name in backup_item.required_params+backup_item.optional_params:
                if hasattr(backup_item,attrib_name):
                    b[attrib_name] = getattr(backup_item,attrib_name)
            result.append(b)

    backup_dict = {}
    backup_dict['rsync_ssh_list'] = []
    backup_dict['rsync_btrfs_list'] = []
    backup_dict['rsync_list'] = []
    backup_dict['null_list'] = []
    backup_dict['pgsql_list'] = []
    backup_dict['mysql_list'] = []
    backup_dict['sqlserver_list'] = []
    backup_dict['xva_list'] = []
    backup_dict['metadata_list'] = []
    backup_dict['switch_list'] = []
    backup_dict['oracle_list'] = []
    for row in result:
        backup_name = row['backup_name']
        server_name = row['server_name']
        backup_type = row['type']
        if backup_type == "xcp-dump-metadata":
            backup_dict['metadata_list'].append([server_name, backup_name, backup_type, ""])
        if backup_type == "rsync+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_ssh_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "rsync+btrfs+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_btrfs_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "rsync":
            remote_dir = row['remote_dir']
            backup_dict['rsync_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "null":
            backup_dict['null_list'].append([server_name, backup_name, backup_type, ""])
	if backup_type == "pgsql+ssh":
	    db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
	    backup_dict['pgsql_list'].append([server_name, backup_name, backup_type, db_name])
	if backup_type == "mysql+ssh":
	    db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
	    backup_dict['mysql_list'].append([server_name, backup_name, backup_type, db_name])
        if backup_type == "sqlserver+ssh":
            db_name = row['db_name']
            backup_dict['sqlserver_list'].append([server_name, backup_name, backup_type, db_name])
        if backup_type == "oracle+ssh":
	    db_name = row['db_name']
	    backup_dict['oracle_list'].append([server_name, backup_name, backup_type, db_name])	    
        if backup_type == "xen-xva":
            backup_dict['xva_list'].append([server_name, backup_name, backup_type, ""])
        if backup_type == "switch":
            backup_dict['switch_list'].append([server_name, backup_name, backup_type, ""])
    return backup_dict
Esempio n. 46
0
import datetime
import xlrd
from xls import *
from vt import *
from iniparse import ConfigParser
import sys
#ayarlar
ayar = ConfigParser()
ayardos = '.\exnet\DATA\default.ini'
ayardosyol = '.\\exnet\\DATA\\'
if len(sys.argv) > 1:
    ayardos = sys.argv[1]
ayar.read(ayardos)
dosya = ayar.get("excel", "dosya")
sayfa = ayar.get("excel", "sayfa")
fisler = ayar.get("excel", "fisler")
fisler = fisler.split("@")
form = xls()
#komut satirindan yukleme yapmak icin
#form nesnesine ilgili sayfa yukleniyor.
form.sayfa(ayardosyol + dosya, sayfa)

for fis in fisler:
    print fis
    merkezhc = ayar.get(fis, "merkez")
    merkez = form.deger(merkezhc)
    tarihhc = ayar.get(fis, "tarih")
    tarih = form.degertarih(tarihhc)
    islemhc = ayar.get(fis, "islem")
    islem = form.deger(islemhc)
    urtkodhc = ayar.get(fis, "urtkod")
class App(object):
    """
    This class does all basic events with the app
    """
    def __init__(self,
                 appName,
                 desktopFileName=None,
                 shortcut='<Control><Q>',
                 a11yAppName=None,
                 forceKill=True,
                 parameters='',
                 recordVideo=False):
        """
        Initialize object App
        appName     command to run the app
        shortcut    default quit shortcut
        a11yAppName app's a11y name is different than binary
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start? (only for startViaCommand)
        recordVideo start gnome-shell recording while running the app
        """
        self.appCommand = appName
        self.shortcut = shortcut
        self.forceKill = forceKill
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.a11yAppName = a11yAppName
        self.recordVideo = recordVideo
        self.pid = None
        if desktopFileName is None:
            desktopFileName = self.appCommand
        self.desktopFileName = desktopFileName
        # a way of overcoming overview autospawn when mouse in 1,1 from start
        pressKey('Esc')
        absoluteMotion(100, 100, 2)

        # attempt to make a recording of the test
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

    def isRunning(self):
        """
        Is the app running?
        """
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand

        # Trap weird bus errors
        for attempt in xrange(0, 30):
            sleep(1)
            try:
                return self.a11yAppName in [
                    x.name for x in root.applications()
                ]
            except GLib.GError:
                continue
        raise Exception("10 at-spi errors, seems that bus is blocked")

    def getDashIconPosition(name):
        """Get a position of miniature on Overview"""
        over = root.application('gnome-shell').child(name='Overview')
        button = over[2].child(name=name)
        (x, y) = button.position
        (a, b) = button.size
        return (x + a / 2, y + b / 2)

    def parseDesktopFile(self):
        """
        Getting all necessary data from *.dektop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % self.appCommand
        cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
        proc = Popen(cmd, shell=True, stdout=PIPE)
        # !HAVE TO check if the command and its desktop file exist
        if proc.wait() != 0:
            raise Exception("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)

    def kill(self):
        """
        Kill the app via 'killall'
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

        try:
            self.process.kill()
        except:
            # Fall back to killall
            Popen("killall " + self.appCommand, shell=True).wait()

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def startViaCommand(self):
        """
        Start the app via command
        """
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            assert not self.isRunning(), "Application cannot be stopped"

        self.process = Popen(self.appCommand.split() + self.parameters.split(),
                             stdout=PIPE,
                             stderr=PIPE,
                             bufsize=0)
        self.pid = self.process.pid

        assert self.isRunning(), "Application failed to start"
        return root.application(self.a11yAppName)

    def startViaMenu(self, throughCategories=False):
        self.parseDesktopFile()
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            assert not self.isRunning(), "Application cannot be stopped"
        try:
            gnomeShell = root.application('gnome-shell')
            pressKey('Super_L')
            sleep(6)
            if throughCategories:
                # menu Applications
                x, y = getDashIconPosition('Show Applications')
                absoluteMotion(x, y)
                time.sleep(1)
                click(x, y)
                time.sleep(4)  # time for all the oversized app icons to appear

                # submenu that contains the app
                submenu = gnomeShell.child(name=self.getMenuGroups(),
                                           roleName='list item')
                submenu.click()
                time.sleep(4)

                # the app itself
                app = gnomeShell.child(name=self.getName(), roleName='label')
                app.click()
            else:
                typeText(self.getName())
                sleep(2)
                pressKey('Enter')

            assert self.isRunning(), "Application failed to start"
        except SearchError:
            print("!!! Lookup error while passing the path")

        return root.application(self.a11yAppName)

    def closeViaShortcut(self):
        """
        Close the app via shortcut
        """
        if not self.isRunning():
            raise Exception("App is not running")

        keyCombo(self.shortcut)
        assert not self.isRunning(), "Application cannot be stopped"
class App(object):

    """
    Does all basic events with app
    """

    def __init__(
        self, appName, critical=None, shortcut='<Control><Q>', desktopFileName=None, a11yAppName=None, quitButton=None, timeout=5,
            forceKill=True, parameters='', polkit=False, recordVideo=True):
        """
        Initialize object App
        appName     command to run the app
        critical    what's the function we check? {start,quit}
        shortcut    default quit shortcut
        timeout     timeout for starting and shuting down the app
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start? (only for startViaCommand)
        desktopFileName = name of the desktop file if other than appName (without .desktop extension)
        """
        self.appCommand = appName
        self.shortcut = shortcut
        self.timeout = timeout
        self.forceKill = forceKill
        self.critical = critical
        self.quitButton = quitButton
        # the result remains false until the correct result is verified
        self.result = False
        self.updateCorePattern()
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.polkit = polkit
        self.polkitPass = '******'
        self.a11yAppName = a11yAppName
        self.recordVideo = recordVideo

        if desktopFileName is None:
            desktopFileName = self.appCommand
        self.desktopFileName = desktopFileName

        # a way of overcoming overview autospawn when mouse in 1,1 from start
        pressKey('Esc')
        absoluteMotion(100, 100, 2)
        # attempt to make a recording of the test
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

    def parseDesktopFile(self):
        """
        Getting all necessary data from *.dektop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % self.appCommand
        cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
        proc = Popen(cmd, shell=True, stdout=PIPE)
        # !HAVE TO check if the command and its desktop file exist
        if proc.wait() != 0:
            raise Exception("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)

    def end(self):
        """
        Ends the test with correct return value
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')
        time.sleep(2)
        if not isProcessRunning('gnome-shell') or isProcessRunning('gnome-shell --mode=gdm'):
            print ("Error: gnome-shell/Xorg crashed during or after the test!")
            self.result = False

        if self.result:
            print("PASS")
            sys.exit(0)
        else:
            print("FAIL")
            sys.exit(1)

    def updateResult(self, result):
        self.result = result

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def getExec(self):
        try:
            return (
                self.desktopConfig.get(
                    'Desktop Entry',
                    'exec').split()[0].split('/')[-1]
            )
        except ConfigParser.NoOptionError:
            return self.getName()

    def getCategories(self):
        return self.desktopConfig.get('Desktop Entry', 'categories')

    def getMenuGroups(self):
        """
        Convert group list to the one correct menu group
        """
        groupsList = self.getCategories().split(';')
        groupsList.reverse()
        groupConversionDict = {
            'Accessibility': 'Universal Access',
            'System': 'System Tools',
            'Development': 'Programming',
            'Network': 'Internet',
            'Office': 'Office',
            'Graphics': 'Graphics',
            'Game': 'Games',
            'Education': 'Education',
            'Utility': 'Accessories',
            'AudioVideo': 'Sound &amp; Video'
        }
        for i in groupsList:
            if i in groupConversionDict:
                return groupConversionDict[i]

    def isRunning(self):
        """
        Is the app running?
        """
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand

        def getApp():
            try:
                #from dogtail.tree import root
                apps = root.applications()
            except:
                traceback.print_exc(file=sys.stdout)
                time.sleep(4)
                #from dogtail.tree import root
                try:
                    app = root.application(self.a11yAppName)
                    return app
                except SearchError:
                    return None

            for i in apps:
                if i.name.lower() == self.a11yAppName:
                    return i
            return None

        print("*** Checking if '%s' is running" % self.a11yAppName)
        try:  # should the a11y app reload due to start screen (i.e. gimp)
            app = getApp()
        except:
            time.sleep(5)
            app = getApp()
        if app is None or len(app) == 0:
            print("*** The app '%s' is not running" % self.a11yAppName)
            return False
        else:
            print("*** The app '%s' is running" % self.a11yAppName)
            return True

    def kill(self):
        """
        Kill the app via 'killall'
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')
        print("*** Killing all '%s' instances" % self.appCommand)
        return Popen("pkill " + self.appCommand, shell=True).wait()

    def updateCorePattern(self):
        """
        Update string in /proc/sys/kernel/core_pattern to catch
        possible return code
        """
        Popen("sudo rm -rf /tmp/cores", shell=True).wait()
        Popen("mkdir /tmp/cores", shell=True).wait()
        Popen("chmod a+rwx /tmp/cores", shell=True).wait()
        Popen(
            "echo \"/tmp/cores/core.%e.%s.%p\" | sudo tee /proc/sys/kernel/core_pattern",
            shell=True).wait()

    def existsCoreDump(self):
        """
        Check if there is core dump created
        """
        dirPath = "/tmp/cores/"
        files = os.listdir(dirPath)
        regexp = "core\.%s\.[0-9]{1,3}\.[0-9]*" % self.appCommand
        for f in files:
            if re.match(regexp, f):
                return int(f.split(".")[2])
        return 0

    def startViaMenu(self, throughCategories=False):
        """
        Start the app via Gnome Shell menu
        """
        internCritical = (self.critical == 'start')

        self.parseDesktopFile()

        # check if the app is running
        if self.forceKill and self.isRunning():
            self.kill()
            time.sleep(2)
            if self.isRunning():
                if internCritical:
                    self.updateResult(False)
                print("!!! The app is running but it shouldn't be")
                return False
            else:
                print("*** The app has been killed succesfully")

        try:
            # panel button Activities
            gnomeShell = root.application('gnome-shell')
            pressKey('Super_L')
            time.sleep(6)  # time for overview to appear

            if throughCategories:
                # menu Applications
                x, y = getDashIconPosition('Show Applications')
                absoluteMotion(x, y)
                time.sleep(1)
                click(x, y)
                time.sleep(4)  # time for all the oversized app icons to appear

                # submenu that contains the app
                submenu = gnomeShell.child(
                    name=self.getMenuGroups(), roleName='list item')
                submenu.click()
                time.sleep(4)

                # the app itself
                app = gnomeShell.child(
                    name=self.getName(), roleName='label')
                app.click()
            else:
                typeText(self.getName())
                time.sleep(2)
                pressKey('Enter')

            # if there is a polkit
            if self.polkit:
                time.sleep(3)
                typeText(self.polkitPass)
                keyCombo('<Enter>')

            time.sleep(self.timeout)

            if self.isRunning():
                print("*** The app started successfully")
                if internCritical:
                    self.updateResult(True)
                return True
            else:
                print("!!! The app is not running but it should be")
                if internCritical:
                    self.updateResult(False)
                return False
        except SearchError:
            print("!!! Lookup error while passing the path")
            if internCritical:
                self.updateResult(False)
            return False

    def startViaCommand(self):
        """
        Start the app via command
        """
        internCritical = (self.critical == 'start')
        if self.forceKill and self.isRunning():
            self.kill()
            time.sleep(2)
            if self.isRunning():
                if internCritical:
                    self.updateResult(False)
                print("!!! The app is running but it shouldn't be")
                return False
            else:
                print("*** The app has been killed succesfully")

        returnValue = 0
        command = "%s %s" % (self.appCommand, self.parameters)
        returnValue = utilsRun(command, timeout=10, dumb=True)

        # if there is a polkit
        if self.polkit:
            time.sleep(3)
            typeText(self.polkitPass)
            keyCombo('<Enter>')

        time.sleep(self.timeout)

        # check the returned values
        if returnValue is None:
            if internCritical:
                self.updateResult(False)
            print("!!! The app command could not be found")
            return False
        else:
            if self.isRunning():
                if internCritical:
                    self.updateResult(True)
                print("*** The app started successfully")
                return True
            else:
                if internCritical:
                    self.updateResult(False)
                print("!!! The app did not started despite the fact that the command was found")
                return False

    def closeViaShortcut(self):
        """
        Close the app via shortcut
        """
        internCritical = (self.critical == 'quit')

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            print("!!! The app does not seem to be running")
            return False

        keyCombo(self.shortcut)
        time.sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            print("!!! The app is running but it shouldn't be")
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                print("!!! The app closed with core dump created. Signal %d" % self.existsCoreDump())
                return False
            if internCritical:
                self.updateResult(True)
            print("*** The app was successfully closed")
            return True

    def closeViaMenu(self):
        """
        Close app via menu button
        """
        internCritical = (self.critical == 'quit')

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            print("!!! The app does not seem to be running")
            return False

        # try to bind the menu and the button
        try:
            firstSubmenu = self.getMenuNth(0)
            firstSubmenu.click()
            length = len(firstSubmenu.children)
            closeButton = firstSubmenu.children[length - 1]
            if self.quitButton is None:
                while re.search('(Close|Quit|Exit)', closeButton.name) is None:
                    length = length - 1
                    closeButton = firstSubmenu.children[length]
                    if length < 0:
                        if internCritical:
                            self.updateResult(False)
                        print("!!! The app quit button coldn't be found")
                        return False
            else:
                closeButton = firstSubmenu.child(self.quitButton)
        except SearchError:
            if internCritical:
                self.updateResult(False)
            print("!!! The app menu bar or the quit button could'n be found")
            if self.forceKill:
                self.kill()
            return False

        time.sleep(2)  # timeout until menu appear
        print("*** Trying to click to '%s'" % closeButton)
        closeButton.click()
        time.sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            print("!!! The app is running but it shouldn't be")
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                print("!!! The app closed with core dump created. Signal %d" % self.existsCoreDump())
                return False
            if internCritical:
                self.updateResult(True)
            print("*** The app was successfully closed")
            return True

    def getMenuNamed(self, menuName):
        """
        Return submenu with name specified with 'menuName'
        """
        # bind to the right app
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand
        app = root
        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.a11yAppName:
                app = i
                break

        # try to bind the menu and the button
        try:
            appMenu = app.child(roleName='menu bar')
            return appMenu.child(name=menuName)
        except:
            return None

    def getMenuNth(self, nth):
        """
        Return nth submenu
        """
        # bind to the right app
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand
        app = root
        apps = root.applications()
        for i in apps:
            if i.name.lower() == self.a11yAppName:
                app = i
                break

        # try to bind the menu and the button
        try:
            appMenu = app.child(roleName='menu bar')
            return appMenu.children[nth]
        except:
            return None

    def closeViaGnomePanel(self):
        """
        Close the app via menu at gnome-panel
        """
        internCritical = (self.critical == 'quit')

        self.parseDesktopFile()

        if not self.isRunning():
            if internCritical:
                self.updateResult(False)
            print("!!! The app does not seem to be running")
            return False

        print("*** Trying to click to '%s -> Quit'" % self.getName())
        shell = GnomeShell()
        shell.clickApplicationMenuItem(self.getName(), 'Quit')

        time.sleep(self.timeout)

        if self.isRunning():
            if self.forceKill:
                self.kill()
            if internCritical:
                self.updateResult(False)
            print("!!! The app is running but it shouldn't be")
            return False
        else:
            if self.existsCoreDump() != 0:
                if internCritical:
                    self.updateResult(False)
                print("!!! The app closed with core dump created. Signal %d" % self.existsCoreDump())
                return False
            if internCritical:
                self.updateResult(True)
            print("*** The app was successfully closed")
            return True
class App(object):
    """
    This class does all basic events with the app
    """
    def __init__(
        self, appName, desktopFileName = None, shortcut='<Control><Q>', a11yAppName=None,
            forceKill=True, parameters='', recordVideo=False):
        """
        Initialize object App
        appName     command to run the app
        shortcut    default quit shortcut
        a11yAppName app's a11y name is different than binary
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start? (only for startViaCommand)
        recordVideo start gnome-shell recording while running the app
        """
        self.appCommand = appName
        self.shortcut = shortcut
        self.forceKill = forceKill
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.a11yAppName = a11yAppName
        self.recordVideo = recordVideo
        self.pid = None
        if desktopFileName is None:
            desktopFileName = self.appCommand
        self.desktopFileName = desktopFileName
        # a way of overcoming overview autospawn when mouse in 1,1 from start
        pressKey('Esc')
        absoluteMotion(100, 100, 2)

        # attempt to make a recording of the test
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

    def isRunning(self):
        """
        Is the app running?
        """
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand

        # Trap weird bus errors
        for attempt in xrange(0, 30):
            sleep(1)
            try:
                return self.a11yAppName in [x.name for x in root.applications()]
            except GLib.GError:
                continue
        raise Exception("10 at-spi errors, seems that bus is blocked")

    def getDashIconPosition(name):
        """Get a position of miniature on Overview"""
        over = root.application('gnome-shell').child(name='Overview')
        button = over[2].child(name=name)
        (x, y) = button.position
        (a, b) = button.size
        return (x + a / 2, y + b / 2)
    
    def parseDesktopFile(self):
        """
        Getting all necessary data from *.dektop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % self.appCommand
        cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
        proc = Popen(cmd, shell=True, stdout=PIPE)
        # !HAVE TO check if the command and its desktop file exist
        if proc.wait() != 0:
            raise Exception("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)
    
    def kill(self):
        """
        Kill the app via 'killall'
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

        try:
            self.process.kill()
        except:
            # Fall back to killall
            Popen("killall " + self.appCommand, shell=True).wait()

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def startViaCommand(self):
        """
        Start the app via command
        """
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            assert not self.isRunning(), "Application cannot be stopped"

        self.process = Popen(self.appCommand.split() + self.parameters.split(),
                             stdout=PIPE, stderr=PIPE, bufsize=0)
        self.pid = self.process.pid

        assert self.isRunning(), "Application failed to start"
        return root.application(self.a11yAppName)

    def startViaMenu(self, throughCategories = False):
        self.parseDesktopFile()
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            assert not self.isRunning(), "Application cannot be stopped"
        try:
            gnomeShell = root.application('gnome-shell')
            pressKey('Super_L')
            sleep(6)
            if throughCategories:
                # menu Applications
                x, y = getDashIconPosition('Show Applications')
                absoluteMotion(x, y)
                time.sleep(1)
                click(x, y)
                time.sleep(4) # time for all the oversized app icons to appear

                # submenu that contains the app
                submenu = gnomeShell.child(
                    name=self.getMenuGroups(), roleName='list item')
                submenu.click()
                time.sleep(4)

                # the app itself
                app = gnomeShell.child(
                    name=self.getName(), roleName='label')
                app.click()
            else:
                typeText(self.getName())
                sleep(2)
                pressKey('Enter')

            assert self.isRunning(), "Application failed to start"
        except SearchError:
            print("!!! Lookup error while passing the path")
        
        return root.application(self.a11yAppName)



    def closeViaShortcut(self):
        """
        Close the app via shortcut
        """
        if not self.isRunning():
            raise Exception("App is not running")

        keyCombo(self.shortcut)
        assert not self.isRunning(), "Application cannot be stopped"
Esempio n. 50
0
import datetime
import xlrd
from xls import *
from vt import *
from iniparse import ConfigParser
import sys
import platform

#ayarlarin yuklenmesi
ayar=ConfigParser()
yol='.\etoku\DATA\\'
if platform.system()=='Linux':
	yol="etoku/DATA/"

ayardos='bal.ini'
if len(sys.argv) > 1:
	ayardos=sys.argv[1]
	
ayar.read(yol+ayardos)
print "-->",yol+ayardos
dosya=yol+ayar.get("excel","dosya")	
sayfa=ayar.get("excel","sayfa")	
yon=ayar.get("excel","yon")	
if len(sys.argv) > 2:
	sayfa=sys.argv[2]
if len(sys.argv) > 3:
	konsdos=sys.argv[3]
	dosya=yol+konsdos
form=xls()
#sayfanin yuklenmesi
form.sayfa(dosya,sayfa)
Esempio n. 51
0
 def read(self):
     ConfigParser.read(self, self.path)