~ivoks/charms/trusty/neutron-gateway/mtu-vlan

« back to all changes in this revision

Viewing changes to tests/charmhelpers/contrib/amulet/utils.py

  • Committer: Corey Bryant
  • Date: 2014-07-09 19:25:29 UTC
  • mto: This revision was merged to the branch mainline in revision 54.
  • Revision ID: corey.bryant@canonical.com-20140709192529-c2azv58whgj6dnmd
Sync with charm-helpers

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import ConfigParser
 
2
import io
 
3
import logging
 
4
import re
 
5
import sys
 
6
from time import sleep
 
7
 
 
8
 
 
9
class AmuletUtils(object):
 
10
    """This class provides common utility functions that are used by Amulet
 
11
       tests."""
 
12
 
 
13
    def __init__(self, log_level=logging.ERROR):
 
14
        self.log = self.get_logger(level=log_level)
 
15
 
 
16
    def get_logger(self, name="amulet-logger", level=logging.DEBUG):
 
17
        """Get a logger object that will log to stdout."""
 
18
        log = logging
 
19
        logger = log.getLogger(name)
 
20
        fmt = \
 
21
            log.Formatter("%(asctime)s %(funcName)s %(levelname)s: %(message)s")
 
22
 
 
23
        handler = log.StreamHandler(stream=sys.stdout)
 
24
        handler.setLevel(level)
 
25
        handler.setFormatter(fmt)
 
26
 
 
27
        logger.addHandler(handler)
 
28
        logger.setLevel(level)
 
29
 
 
30
        return logger
 
31
 
 
32
    def valid_ip(self, ip):
 
33
        if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
 
34
            return True
 
35
        else:
 
36
            return False
 
37
 
 
38
    def valid_url(self, url):
 
39
        p = re.compile(
 
40
            r'^(?:http|ftp)s?://'
 
41
            r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # flake8: noqa
 
42
            r'localhost|'
 
43
            r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
 
44
            r'(?::\d+)?'
 
45
            r'(?:/?|[/?]\S+)$',
 
46
            re.IGNORECASE)
 
47
        if p.match(url):
 
48
            return True
 
49
        else:
 
50
            return False
 
51
 
 
52
    def validate_services(self, commands):
 
53
        """Verify the specified services are running on the corresponding
 
54
           service units."""
 
55
        for k, v in commands.iteritems():
 
56
            for cmd in v:
 
57
                output, code = k.run(cmd)
 
58
                if code != 0:
 
59
                    return "command `{}` returned {}".format(cmd, str(code))
 
60
        return None
 
61
 
 
62
    def _get_config(self, unit, filename):
 
63
        """Get a ConfigParser object for parsing a unit's config file."""
 
64
        file_contents = unit.file_contents(filename)
 
65
        config = ConfigParser.ConfigParser()
 
66
        config.readfp(io.StringIO(file_contents))
 
67
        return config
 
68
 
 
69
    def validate_config_data(self, sentry_unit, config_file, section, expected):
 
70
        """Verify that the specified section of the config file contains
 
71
           the expected option key:value pairs."""
 
72
        config = self._get_config(sentry_unit, config_file)
 
73
 
 
74
        if section != 'DEFAULT' and not config.has_section(section):
 
75
            return "section [{}] does not exist".format(section)
 
76
 
 
77
        for k in expected.keys():
 
78
            if not config.has_option(section, k):
 
79
                return "section [{}] is missing option {}".format(section, k)
 
80
            if config.get(section, k) != expected[k]:
 
81
                return "section [{}] {}:{} != expected {}:{}".format(section,
 
82
                       k, config.get(section, k), k, expected[k])
 
83
        return None
 
84
 
 
85
    def _validate_dict_data(self, expected, actual):
 
86
        """Compare expected dictionary data vs actual dictionary data.
 
87
           The values in the 'expected' dictionary can be strings, bools, ints,
 
88
           longs, or can be a function that evaluate a variable and returns a
 
89
           bool."""
 
90
        for k, v in expected.iteritems():
 
91
            if k in actual:
 
92
                if isinstance(v, basestring) or \
 
93
                   isinstance(v, bool) or \
 
94
                   isinstance(v, (int, long)):
 
95
                    if v != actual[k]:
 
96
                        return "{}:{}".format(k, actual[k])
 
97
                elif not v(actual[k]):
 
98
                    return "{}:{}".format(k, actual[k])
 
99
            else:
 
100
                return "key '{}' does not exist".format(k)
 
101
        return None
 
102
 
 
103
    def validate_relation_data(self, sentry_unit, relation, expected):
 
104
        """Validate actual relation data based on expected relation data."""
 
105
        actual = sentry_unit.relation(relation[0], relation[1])
 
106
        self.log.debug('actual: {}'.format(repr(actual)))
 
107
        return self._validate_dict_data(expected, actual)
 
108
 
 
109
    def _validate_list_data(self, expected, actual):
 
110
        """Compare expected list vs actual list data."""
 
111
        for e in expected:
 
112
            if e not in actual:
 
113
                return "expected item {} not found in actual list".format(e)
 
114
        return None
 
115
 
 
116
    def not_null(self, string):
 
117
        if string != None:
 
118
            return True
 
119
        else:
 
120
            return False
 
121
 
 
122
    def _get_file_mtime(self, sentry_unit, filename):
 
123
        """Get last modification time of file."""
 
124
        return sentry_unit.file_stat(filename)['mtime']
 
125
 
 
126
    def _get_dir_mtime(self, sentry_unit, directory):
 
127
        """Get last modification time of directory."""
 
128
        return sentry_unit.directory_stat(directory)['mtime']
 
129
 
 
130
    def _get_proc_start_time(self, sentry_unit, service, pgrep_full=False):
 
131
        """Determine start time of the process based on the last modification
 
132
           time of the /proc/pid directory. If pgrep_full is True, the process
 
133
           name is matched against the full command line."""
 
134
        if pgrep_full:
 
135
            cmd = 'pgrep -o -f {}'.format(service)
 
136
        else:
 
137
            cmd = 'pgrep -o {}'.format(service)
 
138
        proc_dir = '/proc/{}'.format(sentry_unit.run(cmd)[0].strip())
 
139
        return self._get_dir_mtime(sentry_unit, proc_dir)
 
140
 
 
141
    def service_restarted(self, sentry_unit, service, filename,
 
142
                          pgrep_full=False, sleep_time=20):
 
143
        """Compare a service's start time vs a file's last modification time
 
144
           (such as a config file for that service) to determine if the service
 
145
           has been restarted."""
 
146
        sleep(sleep_time)
 
147
        if self._get_proc_start_time(sentry_unit, service, pgrep_full) >= \
 
148
           self._get_file_mtime(sentry_unit, filename):
 
149
            return True
 
150
        else:
 
151
            return False
 
152
 
 
153
    def relation_error(self, name, data):
 
154
        return 'unexpected relation data in {} - {}'.format(name, data)
 
155
 
 
156
    def endpoint_error(self, name, data):
 
157
        return 'unexpected endpoint data in {} - {}'.format(name, data)