Jira ESCALATOR-41:get cluster list from installer
[escalator.git] / api / escalator / api / v1 / clusters.py
1 # Copyright 2013 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 /clusters list for Escalator v1 API
18 """
19 from oslo_log import log as logging
20 from webob.exc import HTTPBadRequest
21 from webob.exc import HTTPForbidden
22
23 from escalator.api import policy
24 from escalator.api.v1 import controller
25 from escalator.common import exception
26 from escalator.common import utils
27 from escalator.common import wsgi
28 from escalator import i18n
29 from escalator import notifier
30 import escalator.installer.daisy.api as daisy_api
31
32 LOG = logging.getLogger(__name__)
33 _ = i18n._
34 _LE = i18n._LE
35 _LI = i18n._LI
36 _LW = i18n._LW
37
38
39 class Controller(controller.BaseController):
40     """
41     WSGI controller for clusters resource in Escalaotr v1 API
42
43     The clusters resource API is a RESTful web service for cluster data.
44     The API is as follows::
45
46         GET  /clusters -- Returns a set of brief metadata about clusters
47         GET  /clusters -- Returns a set of detailed metadata about
48                               clusters
49     """
50     def __init__(self):
51         self.notifier = notifier.Notifier()
52         self.policy = policy.Enforcer()
53
54     def _enforce(self, req, action, target=None):
55         """Authorize an action against our policies"""
56         if target is None:
57             target = {}
58         try:
59             self.policy.enforce(req.context, action, target)
60         except exception.Forbidden:
61             raise HTTPForbidden()
62
63     def detail(self, req):
64         """
65         Returns detailed information for all available clusters
66
67         :param req: The WSGI/Webob Request object
68         :retval The response body is a mapping of the following form::
69
70             {'clusters': [
71                 {'id': <ID>,
72                  'name': <NAME>,
73                  'nodes': <NODES>,
74                  'networks': <NETWORKS>,
75                  'description': <DESCRIPTION>,
76                  'created_at': <TIMESTAMP>,
77                  'updated_at': <TIMESTAMP>,
78                  'deleted_at': <TIMESTAMP>|<NONE>,}, ...
79             ]}
80         """
81         self._enforce(req, 'get_clusters')
82         try:
83             clusters = daisy_api.cluster_list(req.context)
84             clusters_list = list()
85             while True:
86                 try:
87                     cluster_new = next(clusters)
88                     clusters_list.append(cluster_new)
89                 except StopIteration:
90                     break
91         except exception.Invalid as e:
92             raise HTTPBadRequest(explanation=e.msg, request=req)
93         return dict(clusters=clusters_list)
94
95
96 class ProjectDeserializer(wsgi.JSONRequestDeserializer):
97     """Handles deserialization of specific controller method requests."""
98
99     def _deserialize(self, request):
100         result = {}
101         result["cluster_meta"] = utils.get_cluster_meta(request)
102         return result
103
104
105 class ProjectSerializer(wsgi.JSONResponseSerializer):
106     """Handles serialization of specific controller method responses."""
107
108     def __init__(self):
109         self.notifier = notifier.Notifier()
110
111     def get_cluster(self, response, result):
112         cluster_meta = result['cluster_meta']
113         response.status = 201
114         response.headers['Content-Type'] = 'application/json'
115         response.body = self.to_json(dict(cluster=cluster_meta))
116         return response
117
118
119 def create_resource():
120     """Projects resource factory method"""
121     deserializer = ProjectDeserializer()
122     serializer = ProjectSerializer()
123     return wsgi.Resource(Controller(), deserializer, serializer)