~openstack-charmers-archive/charms/precise/ceilometer-agent/old-1501

« back to all changes in this revision

Viewing changes to hooks/charmhelpers/core/services/helpers.py

  • Committer: james.page at ubuntu
  • Date: 2014-12-15 09:20:47 UTC
  • mfrom: (41.1.4 ceilometer-agent)
  • Revision ID: james.page@ubuntu.com-20141215092047-vxt3kkhc5jh4zk81
[corey.bryant,r=james-page] Sort out charmhelpers issues.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
 
2
import yaml
1
3
from charmhelpers.core import hookenv
2
4
from charmhelpers.core import templating
3
5
 
19
21
    the `name` attribute that are complete will used to populate the dictionary
20
22
    values (see `get_data`, below).
21
23
 
22
 
    The generated context will be namespaced under the interface type, to prevent
23
 
    potential naming conflicts.
 
24
    The generated context will be namespaced under the relation :attr:`name`,
 
25
    to prevent potential naming conflicts.
 
26
 
 
27
    :param str name: Override the relation :attr:`name`, since it can vary from charm to charm
 
28
    :param list additional_required_keys: Extend the list of :attr:`required_keys`
24
29
    """
25
30
    name = None
26
31
    interface = None
27
32
    required_keys = []
28
33
 
29
 
    def __init__(self, *args, **kwargs):
30
 
        super(RelationContext, self).__init__(*args, **kwargs)
 
34
    def __init__(self, name=None, additional_required_keys=None):
 
35
        if name is not None:
 
36
            self.name = name
 
37
        if additional_required_keys is not None:
 
38
            self.required_keys.extend(additional_required_keys)
31
39
        self.get_data()
32
40
 
33
41
    def __bool__(self):
101
109
        return {}
102
110
 
103
111
 
 
112
class MysqlRelation(RelationContext):
 
113
    """
 
114
    Relation context for the `mysql` interface.
 
115
 
 
116
    :param str name: Override the relation :attr:`name`, since it can vary from charm to charm
 
117
    :param list additional_required_keys: Extend the list of :attr:`required_keys`
 
118
    """
 
119
    name = 'db'
 
120
    interface = 'mysql'
 
121
    required_keys = ['host', 'user', 'password', 'database']
 
122
 
 
123
 
 
124
class HttpRelation(RelationContext):
 
125
    """
 
126
    Relation context for the `http` interface.
 
127
 
 
128
    :param str name: Override the relation :attr:`name`, since it can vary from charm to charm
 
129
    :param list additional_required_keys: Extend the list of :attr:`required_keys`
 
130
    """
 
131
    name = 'website'
 
132
    interface = 'http'
 
133
    required_keys = ['host', 'port']
 
134
 
 
135
    def provide_data(self):
 
136
        return {
 
137
            'host': hookenv.unit_get('private-address'),
 
138
            'port': 80,
 
139
        }
 
140
 
 
141
 
 
142
class RequiredConfig(dict):
 
143
    """
 
144
    Data context that loads config options with one or more mandatory options.
 
145
 
 
146
    Once the required options have been changed from their default values, all
 
147
    config options will be available, namespaced under `config` to prevent
 
148
    potential naming conflicts (for example, between a config option and a
 
149
    relation property).
 
150
 
 
151
    :param list *args: List of options that must be changed from their default values.
 
152
    """
 
153
 
 
154
    def __init__(self, *args):
 
155
        self.required_options = args
 
156
        self['config'] = hookenv.config()
 
157
        with open(os.path.join(hookenv.charm_dir(), 'config.yaml')) as fp:
 
158
            self.config = yaml.load(fp).get('options', {})
 
159
 
 
160
    def __bool__(self):
 
161
        for option in self.required_options:
 
162
            if option not in self['config']:
 
163
                return False
 
164
            current_value = self['config'][option]
 
165
            default_value = self.config[option].get('default')
 
166
            if current_value == default_value:
 
167
                return False
 
168
            if current_value in (None, '') and default_value in (None, ''):
 
169
                return False
 
170
        return True
 
171
 
 
172
    def __nonzero__(self):
 
173
        return self.__bool__()
 
174
 
 
175
 
 
176
class StoredContext(dict):
 
177
    """
 
178
    A data context that always returns the data that it was first created with.
 
179
 
 
180
    This is useful to do a one-time generation of things like passwords, that
 
181
    will thereafter use the same value that was originally generated, instead
 
182
    of generating a new value each time it is run.
 
183
    """
 
184
    def __init__(self, file_name, config_data):
 
185
        """
 
186
        If the file exists, populate `self` with the data from the file.
 
187
        Otherwise, populate with the given data and persist it to the file.
 
188
        """
 
189
        if os.path.exists(file_name):
 
190
            self.update(self.read_context(file_name))
 
191
        else:
 
192
            self.store_context(file_name, config_data)
 
193
            self.update(config_data)
 
194
 
 
195
    def store_context(self, file_name, config_data):
 
196
        if not os.path.isabs(file_name):
 
197
            file_name = os.path.join(hookenv.charm_dir(), file_name)
 
198
        with open(file_name, 'w') as file_stream:
 
199
            os.fchmod(file_stream.fileno(), 0o600)
 
200
            yaml.dump(config_data, file_stream)
 
201
 
 
202
    def read_context(self, file_name):
 
203
        if not os.path.isabs(file_name):
 
204
            file_name = os.path.join(hookenv.charm_dir(), file_name)
 
205
        with open(file_name, 'r') as file_stream:
 
206
            data = yaml.load(file_stream)
 
207
            if not data:
 
208
                raise OSError("%s is empty" % file_name)
 
209
            return data
 
210
 
 
211
 
104
212
class TemplateCallback(ManagerCallback):
105
213
    """
106
 
    Callback class that will render a template, for use as a ready action.
 
214
    Callback class that will render a Jinja2 template, for use as a ready
 
215
    action.
 
216
 
 
217
    :param str source: The template source file, relative to
 
218
    `$CHARM_DIR/templates`
 
219
 
 
220
    :param str target: The target to write the rendered template to
 
221
    :param str owner: The owner of the rendered file
 
222
    :param str group: The group of the rendered file
 
223
    :param int perms: The permissions of the rendered file
107
224
    """
108
 
    def __init__(self, source, target, owner='root', group='root', perms=0444):
 
225
    def __init__(self, source, target,
 
226
                 owner='root', group='root', perms=0o444):
109
227
        self.source = source
110
228
        self.target = target
111
229
        self.owner = owner