~ubuntu-branches/ubuntu/vivid/python-heatclient/vivid

« back to all changes in this revision

Viewing changes to heatclient/common/base.py

  • Committer: Package Import Robot
  • Author(s): Chuck Short
  • Date: 2014-03-06 17:41:15 UTC
  • mto: This revision was merged to the branch mainline in revision 8.
  • Revision ID: package-import@ubuntu.com-20140306174115-ecpzxbyb30tl5i7a
Tags: upstream-0.2.8
ImportĀ upstreamĀ versionĀ 0.2.8

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright 2012 OpenStack Foundation
2
 
# All Rights Reserved.
3
 
#
4
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
5
 
#    not use this file except in compliance with the License. You may obtain
6
 
#    a copy of the License at
7
 
#
8
 
#         http://www.apache.org/licenses/LICENSE-2.0
9
 
#
10
 
#    Unless required by applicable law or agreed to in writing, software
11
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
 
#    License for the specific language governing permissions and limitations
14
 
#    under the License.
15
 
 
16
 
"""
17
 
Base utilities to build API operation managers and objects on top of.
18
 
"""
19
 
 
20
 
import copy
21
 
import six
22
 
 
23
 
 
24
 
# Python 2.4 compat
25
 
try:
26
 
    all
27
 
except NameError:
28
 
    def all(iterable):
29
 
        return True not in (not x for x in iterable)
30
 
 
31
 
 
32
 
def getid(obj):
33
 
    """Get by object or ID.
34
 
 
35
 
    Abstracts the common pattern of allowing both an object or an object's ID
36
 
    (UUID) as a parameter when dealing with relationships.
37
 
    """
38
 
    try:
39
 
        return obj.id
40
 
    except AttributeError:
41
 
        return obj
42
 
 
43
 
 
44
 
class Manager(object):
45
 
    """Managers interact with a particular type of API.
46
 
 
47
 
    For example servers, flavors and images.
48
 
    It provides CRUD operations for these objects.
49
 
    """
50
 
    resource_class = None
51
 
 
52
 
    def __init__(self, api):
53
 
        self.api = api
54
 
 
55
 
    def _list(self, url, response_key, obj_class=None, body=None):
56
 
        resp, body = self.api.json_request('GET', url)
57
 
 
58
 
        if obj_class is None:
59
 
            obj_class = self.resource_class
60
 
 
61
 
        data = body[response_key]
62
 
        return [obj_class(self, res, loaded=True) for res in data if res]
63
 
 
64
 
    def _delete(self, url):
65
 
        self.api.raw_request('DELETE', url)
66
 
 
67
 
    def _update(self, url, body, response_key=None):
68
 
        resp, body = self.api.json_request('PUT', url, body=body)
69
 
        # PUT requests may not return a body
70
 
        if body:
71
 
            return self.resource_class(self, body[response_key])
72
 
 
73
 
 
74
 
class Resource(object):
75
 
    """A resource represents a particular instance of an object.
76
 
 
77
 
    For example tenant or user. This is pretty much just a bag for attributes.
78
 
 
79
 
    :param manager: Manager object
80
 
    :param info: dictionary representing resource attributes
81
 
    :param loaded: prevent lazy-loading if set to True
82
 
    """
83
 
    def __init__(self, manager, info, loaded=False):
84
 
        self.manager = manager
85
 
        self._info = info
86
 
        self._add_details(info)
87
 
        self._loaded = loaded
88
 
 
89
 
    def _add_details(self, info):
90
 
        for (k, v) in six.iteritems(info):
91
 
            setattr(self, k, v)
92
 
 
93
 
    def __getattr__(self, k):
94
 
        if k not in self.__dict__:
95
 
            #NOTE(bcwaldon): disallow lazy-loading if already loaded once
96
 
            if not self.is_loaded():
97
 
                self.get()
98
 
                return self.__getattr__(k)
99
 
 
100
 
            raise AttributeError(k)
101
 
        else:
102
 
            return self.__dict__[k]
103
 
 
104
 
    def __repr__(self):
105
 
        reprkeys = sorted(k for k in self.__dict__.keys()
106
 
                          if k[0] != '_' and k != 'manager')
107
 
        info = ", ".join("%s=%s" % (k, getattr(self, k)) for k in reprkeys)
108
 
        return "<%s %s>" % (self.__class__.__name__, info)
109
 
 
110
 
    def get(self):
111
 
        # set_loaded() first ... so if we have to bail, we know we tried.
112
 
        self.set_loaded(True)
113
 
        if not hasattr(self.manager, 'get'):
114
 
            return
115
 
 
116
 
        new = self.manager.get(self.id)
117
 
        if new:
118
 
            self._add_details(new._info)
119
 
 
120
 
    def __eq__(self, other):
121
 
        if not isinstance(other, self.__class__):
122
 
            return False
123
 
        if hasattr(self, 'id') and hasattr(other, 'id'):
124
 
            return self.id == other.id
125
 
        return self._info == other._info
126
 
 
127
 
    def is_loaded(self):
128
 
        return self._loaded
129
 
 
130
 
    def set_loaded(self, val):
131
 
        self._loaded = val
132
 
 
133
 
    def to_dict(self):
134
 
        return copy.deepcopy(self._info)