예제 #1
0
    def __init__(self, db_path, tables_sql=None, foreign_keys=True):
        """
        Opens given database reference. If tables_sql list is given,
        each SQL command in the list is executed to initialize the
        database.
        """
        self.log = Logger('sqlite').default_stream
        self.db_path = db_path

        if db_path is None:
            raise SQLiteError('Database path is None')

        db_dir = os.path.dirname(db_path)
        if db_dir and not os.path.isdir(db_dir):
            try:
                os.makedirs(db_dir)
            except IOError as e:
                raise SQLiteError('Error creating directory {0}: {1}'.format(
                    db_dir, e))

        self.conn = sqlite3.Connection(self.db_path)

        c = self.cursor
        if foreign_keys:
            c.execute('PRAGMA foreign_keys=ON')
            c.fetchone()

        if tables_sql:
            for q in tables_sql:
                try:
                    c.execute(q)
                except sqlite3.OperationalError as e:
                    raise SQLiteError('Error executing SQL:\n{0}\n{1}'.format(
                        q, e))
예제 #2
0
    def __init__(self,
                 name=None,
                 description=None,
                 epilog=None,
                 debug_flag=True):
        self.name = os.path.basename(sys.argv[0])
        setproctitle('%s %s' % (self.name, ' '.join(sys.argv[1:])))
        signal.signal(signal.SIGINT, self.SIGINT)

        reload(sys)
        sys.setdefaultencoding('utf-8')

        if name is None:
            name = self.name

        # Set to True to avoid any messages from self.message to be printed
        self.silent = False

        self.logger = Logger(self.name)
        self.log = self.logger.default_stream

        self.subcommand_parser = None
        self.parser = argparse.ArgumentParser(
            prog=name,
            description=description,
            formatter_class=argparse.RawTextHelpFormatter,
            epilog=epilog,
            add_help=True,
            conflict_handler='resolve',
        )
        if debug_flag:
            self.parser.add_argument('--debug',
                                     action='store_true',
                                     help='Show debug messages')
예제 #3
0
    def __init__(self,
                 value=None,
                 input_format=DEFAULT_DATE_FORMAT,
                 firstweekday=WEEK_START_DEFAULT,
                 workdays=None,
                 workdays_per_week=WORKDAYS_PER_WEEK):

        self.__next = 0
        self.log = Logger('dates').default_stream

        day = Day(value=value, input_format=input_format)

        if firstweekday in WEEKDAY_NAMES:
            self.firstweekday = WEEKDAY_NAMES.index(firstweekday)
        else:
            try:
                self.firstweekday = int(firstweekday)
                if self.firstweekday < 0 or self.firstweekday > 6:
                    raise ValueError
            except ValueError:
                raise ValueError(
                    'Invalid first week day index: {0}'.format(firstweekday))
        wday = (day.value.isoweekday() + (7 - self.firstweekday)) % 7

        self.first = day - wday
        self.last = self.first + 6
        self.weeknumber = int(self.first.value.strftime('%U'))

        self.workdays = []
        if workdays is not None:
            if not isinstance(workdays, iterable):
                raise ValueError(
                    'Invalid workdays index list parameter: {0}'.format(
                        workdays))
            for i in workdays:
                try:
                    i = int(i)
                    if i < 0 or i > 6:
                        raise ValueError
                    self.workdays.append(self.first + i)
                except ValueError:
                    raise ValueError(
                        'Invalid workdays index list parameter: {0}'.format(
                            workdays))

        else:
            try:
                workdays_per_week = int(workdays_per_week)
                if workdays_per_week < 0 or workdays_per_week > 7:
                    raise ValueError
            except ValueError:
                raise ValueError(
                    'Invalid value for workdays_per_week: {0}'.format(
                        workdays_per_week))
            self.workdays = [
                self[i]
                for i in filter(lambda i: i <= 6, range(0, workdays_per_week))
            ]

        self.workdays.sort()
예제 #4
0
    def __init__(self, value=None, input_format=None):
        self.log = Logger('dates').default_stream

        if value is None:
            self.value = datetime.now().date()

        elif isinstance(value, Day):
            self.value = value.value

        elif isinstance(value, date):
            self.value = value

        elif isinstance(value, datetime):
            self.value = value.date()

        elif isinstance(value, time.struct_time):
            self.value = date(*value[:3])

        elif isinstance(value, str) and input_format is None and value == '':
            self.value = datetime.now().date()

        else:
            input_format = input_format is not None and input_format or DEFAULT_DATE_FORMAT
            try:
                self.value = datetime.strptime(str(value), input_format).date()
            except ValueError:
                try:
                    self.value = date(*time.localtime(int(value))[:3])
                except ValueError:
                    raise DatesError('Error parsing date: {0}'.format(value))
예제 #5
0
 def __init__(self, path=None):
     self.defaults = {}
     self.patterns = []
     self.log = Logger().default_stream
     self.path = path is not None and path or os.path.expanduser(
         '~/.ssh/config')
     self.reload()
예제 #6
0
    def __init__(self, config, name, **kwargs):
        self.log = Logger().default_stream
        self.name = name
        self.description = name
        self.connect_command = DEFAULT_CONNECT_COMMAND
        self.command_separator = DEFAULT_COMMAND_SEPARATOR
        self.update_commands = []
        self.servers = []

        for k in ('description', 'command_separator'):
            if k in kwargs:
                setattr(self, k, kwargs[k])

        if 'connect' in kwargs:
            self.connect_command = kwargs['connect']

        if 'commands' in kwargs:
            self.update_commands = kwargs['commands']

        if 'servers' in kwargs:
            names = kwargs['servers']
            if not isinstance(names, list):
                names = [names]

            for name in names:
                self.servers.append(Server(self, name))

        self.modified = False
예제 #7
0
파일: agent.py 프로젝트: pombreda/seine
    def __init__(self, oid):
        self.log = Logger('snmp').default_stream
        self.oid = self.__format_oid__(oid)
        self.oid_string = self.__format_oid_string__(oid)

        self._parent = None
        self._next = None
예제 #8
0
    def __init__(self, user_keys, path):
        self.log = Logger().default_stream
        self.user_keys = user_keys

        self.path = os.path.realpath(path)
        self.available = os.access(path, os.R_OK) and True or False

        self.autoload = False
        self.update({ 'bits': None, 'fingerprint': None, 'path': None, 'algorithm': None, })

        public_key = '%s.pub' % self.path
        if not os.path.isfile(public_key):
            self.available = False
            return

        cmd = ( 'ssh-keygen', '-l', '-f',  public_key )
        p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        (stdout, stderr) = p.communicate()
        l = stdout.split('\n')[0].rstrip()

        if p.returncode != 0:
            raise SSHKeyError('ERROR parsing public key: %s' % public_key)

        m = RE_KEYINFO.match(l)
        if not m:
            raise SSHKeyError('Unsupported public key output: %s' % l)

        for k, v in m.groupdict().items():
            if k == 'path':
                k = 'public_key_path'
            self[k] = v
예제 #9
0
 def __init__(self, name):
     super(threading.Thread, self).__init__()
     self.log = Logger(name).default_stream
     self.status = 'not running'
     self.setDaemon(True)
     self.setName(name)
     self._stop_event = threading.Event()
예제 #10
0
    def __init__(self, path):
        self.operating_systems = []
        self.servers = []
        self.path = path
        self.log = Logger().default_stream

        if os.path.isfile(self.path):
            self.load()
예제 #11
0
    def __init__(self, runner, show_colors=False):
        self.log = Logger().default_stream
        self.runner = runner
        self.show_colors = show_colors

        self.results = {
            'contacted': self.resultset_loader(self, 'contacted'),
            'dark': self.resultset_loader(self, 'dark'),
        }
예제 #12
0
    def __init__(self,flags=[]):
        self.log = Logger('filesystems').default_stream

        if isinstance(flags, list):
            for k in flags: 
                self.set(k)
        
        if isinstance(flags, dict):
            for k, v in flags.items():
                self.set(k, v)
예제 #13
0
 def __init__(self,
              mountpoints,
              device,
              mountpoint,
              filesystem,
              flags=None):
     self.log = Logger('filesystems').default_stream
     self.mountpoints = mountpoints
     self.device = device
     self.mountpoint = mountpoint
     self.filesystem = filesystem
     self.flags = FileSystemFlags(flags=flags if flags is not None else {})
     self.usage = {}
예제 #14
0
    def __init__(self,value=None, input_format=DEFAULT_DATE_FORMAT,
                firstweekday=WEEK_START_DEFAULT):
        self.__next = 0
        self.log = Logger('dates').default_stream

        self.first = Day(Day(value=value, input_format=input_format).value.replace(day=1))
        self.days = calendar.monthrange(self.first.value.year,self.first.value.month)[1]
        self.last  = self.first+(self.days-1)

        self.firstweekday = firstweekday
        self.weeks = []
        week = Week(self.first, None, firstweekday=self.firstweekday)
        while week.first <= self.last:
            self.weeks.append(week)
            week+=1
예제 #15
0
파일: agent.py 프로젝트: pombreda/seine
    def __init__(self, oid, reload_interval=60):
        Script.__init__(self)
        self.log = Logger('snmp').default_stream

        self.reload_interval = reload_interval
        self.last_reload = None

        self.add_argument('-g', '--get', help='SNMP GET request')
        self.add_argument('-n', '--next', help='SNMP GET request')
        self.add_argument('-t',
                          '--tree',
                          action='store_true',
                          help='Show OID tree')

        self.tree = Tree(oid)
예제 #16
0
    def __init__(self,
                 src,
                 dst,
                 flags=DEFAULT_RSYNC_FLAGS,
                 output_format=DEFAULT_OUTPUT_FORMAT):
        self.log = Logger('rsync').default_stream
        self.src = src
        self.dst = dst
        self.flags = flags
        self.output_format = output_format

        cmd = CommandPathCache().which('rsync')
        if cmd is None:
            raise RsyncError('No such command: rsync')
        self.command = [cmd] + flags + [
            self.output_format, '{0}'.format(src), '{0}'.format(dst)
        ]
예제 #17
0
    def __init__(self, db_path, tables_sql=None, foreign_keys=True):
        """
        Opens given database reference. If tables_sql list is given,
        each SQL command in the list is executed to initialize the
        database.
        """
        self.log = Logger('sqlite').default_stream
        self.db_path = db_path

        if db_path is None:
            raise SQLiteError('Database path is None')
        db_dir = os.path.dirname(db_path)
        if not os.path.isdir(db_dir):
            try:
                os.makedirs(db_dir)
            except IOError, (ecode, emsg):
                raise SQLiteError('Error creating directory %s: %s' %
                                  (db_dir, emsg))
예제 #18
0
    def __init__(self, user_keys, path):
        self.log = Logger().default_stream
        self.user_keys = user_keys

        self.path = os.path.realpath(path)
        self.available = os.access(path, os.R_OK) and True or False

        self.autoload = False
        self.update({
            'bits': None,
            'fingerprint': None,
            'path': None,
            'algorithm': None
        })

        public_key = '{}.pub'.format(self.path)
        if not os.path.isfile(public_key):
            self.available = False
            return

        cmd = ('ssh-keygen', '-l', '-f', public_key)
        p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        (stdout, stderr) = [str(x, 'utf-8') for x in p.communicate()]
        line = stdout.split('\n')[0].rstrip()

        if p.returncode != 0:
            raise SSHKeyError(
                'ERROR parsing public key: {}'.format(public_key))

        data = parse_public_key_line_pattern(line)
        if not data:
            raise SSHKeyError('Unsupported public key output: {}'.format(line))

        for k, v in data.items():
            if k == 'path':
                k = 'public_key_path'
            self[k] = v
예제 #19
0
 def __init__(self, path=DEFAULT_KNOWN_HOSTS, fingerprint_hash=None):
     self.log = Logger().default_stream
     self.path = path
     self.fingerprint_hash = fingerprint_hash
     self.load()
예제 #20
0
 def __init__(self, resultset, name):
     self.log = Logger().default_stream
     self.resultset = resultset
     self.name = name
     self.ansible_facts = {}
예제 #21
0
from systematic.log import Logger

from ansible import __version__ as ansible_version
from ansible.constants import DEFAULT_MODULE_NAME, DEFAULT_MODULE_PATH, DEFAULT_MODULE_ARGS, \
                              DEFAULT_TIMEOUT, DEFAULT_HOST_LIST, DEFAULT_PRIVATE_KEY_FILE, \
                              DEFAULT_FORKS, DEFAULT_REMOTE_PORT, DEFAULT_PATTERN, \
                              DEFAULT_SUDO_USER, DEFAULT_HOST_LIST, active_user

from ansible.errors import AnsibleError
from ansible.inventory import Inventory

from ansiblereporter import RunnerError
from ansiblereporter import __version__ as ansible_reporter_version
from ansiblereporter.result import PlaybookRunner, AnsibleRunner

logger = Logger().default_stream


def create_directory(directory):
    """Create directory

    Wrapper to attempt creating directory unless it exists.

    Raises RunnerError if any errors happen.
    """
    if os.path.isdir(directory):
        logger.debug('directory already exists: %s' % directory)
        return

    try:
        os.makedirs(directory)
예제 #22
0
 def __init__(self, authorized_keys=DEFAULT_AUTHORIZED_KEYS):
     self.log = Logger().default_stream
     self.__parse_user_keyfiles()
     self.authorized_keys = AuthorizedKeys(authorized_keys)
예제 #23
0
 def __init__(self, path=DEFAULT_AUTHORIZED_KEYS, fingerprint_hash=None):
     self.log = Logger().default_stream
     self.path = path
     self.fingerprint_hash = fingerprint_hash
     self.load()
예제 #24
0
 def __init__(self, *args, **kwargs):
     self.log = Logger().default_stream
     try:
         AnsibleInventory.__init__(self, *args, **kwargs)
     except AnsibleError, emsg:
         raise InventoryError(emsg)
예제 #25
0
 def __init__(self, *args, **kwargs):
     dict.__init__(self, *args, **kwargs)
     self.log = Logger().default_stream
예제 #26
0
 def __init__(self, verbose=False):
     callbacks.PlaybookCallbacks.__init__(self, verbose)
     self.log = Logger().default_stream
예제 #27
0
 def __init__(self, osgroup, name, description=None):
     self.log = Logger().default_stream
     self.osgroup = osgroup
     self.name = name
     self.description = description
예제 #28
0
 def __init__(self, device, mountpoint, filesystem, flags={}):
     self.log = Logger('filesystems').default_stream
     self.device = device
     self.mountpoint = mountpoint
     self.filesystem = filesystem
     self.flags = FileSystemFlags(flags=flags)
예제 #29
0
 def __init__(self, stats, verbose=None):
     callbacks.PlaybookRunnerCallbacks.__init__(self, stats, verbose)
     self.log = Logger().default_stream
예제 #30
0
 def __init__(self, path=DEFAULT_AUTHORIZED_KEYS):
     self.log = Logger().default_stream
     self.path = path
     self.load()