Pass through event loop
[osm/N2VC.git] / juju / controller.py
1 import asyncio
2 import logging
3
4 from . import tag
5 from . import utils
6 from .client import client
7 from .client import connection
8 from .model import Model
9
10 log = logging.getLogger(__name__)
11
12
13 class Controller(object):
14 def __init__(self, loop=None):
15 """Instantiate a new Controller.
16
17 One of the connect_* methods will need to be called before this
18 object can be used for anything interesting.
19
20 :param loop: an asyncio event loop
21
22 """
23 self.loop = loop or asyncio.get_event_loop()
24 self.connection = None
25
26 async def connect(
27 self, endpoint, username, password, cacert=None, macaroons=None):
28 """Connect to an arbitrary Juju controller.
29
30 """
31 self.connection = await connection.Connection.connect(
32 endpoint, None, username, password, cacert, macaroons)
33
34 async def connect_current(self):
35 """Connect to the current Juju controller.
36
37 """
38 self.connection = (
39 await connection.Connection.connect_current_controller())
40
41 async def connect_controller(self, controller_name):
42 """Connect to a Juju controller by name.
43
44 """
45 self.connection = (
46 await connection.Connection.connect_controller(controller_name))
47
48 async def disconnect(self):
49 """Shut down the watcher task and close websockets.
50
51 """
52 if self.connection and self.connection.is_open:
53 log.debug('Closing controller connection')
54 await self.connection.close()
55 self.connection = None
56
57 async def add_model(
58 self, model_name, cloud_name=None, credential_name=None,
59 owner=None, config=None, region=None):
60 """Add a model to this controller.
61
62 :param str model_name: Name to give the new model.
63 :param str cloud_name: Name of the cloud in which to create the
64 model, e.g. 'aws'. Defaults to same cloud as controller.
65 :param str credential_name: Name of the credential to use when
66 creating the model. Defaults to current credential. If you
67 pass a credential_name, you must also pass a cloud_name,
68 even if it's the default cloud.
69 :param str owner: Username that will own the model. Defaults to
70 the current user.
71 :param dict config: Model configuration.
72 :param str region: Region in which to create the model.
73
74 """
75 model_facade = client.ModelManagerFacade()
76 model_facade.connect(self.connection)
77
78 owner = owner or self.connection.info['user-info']['identity']
79 cloud_name = cloud_name or await self.get_cloud()
80
81 if credential_name:
82 credential = tag.credential(
83 cloud_name,
84 tag.untag('user-', owner),
85 credential_name
86 )
87 else:
88 credential = None
89
90 log.debug('Creating model %s', model_name)
91
92 model_info = await model_facade.CreateModel(
93 tag.cloud(cloud_name),
94 config,
95 credential,
96 model_name,
97 owner,
98 region,
99 )
100
101 # Add our ssh key to the model, to work around
102 # https://bugs.launchpad.net/juju/+bug/1643076
103 try:
104 ssh_key = await utils.read_ssh_key(loop=self.loop)
105 await utils.execute_process(
106 'juju', 'add-ssh-key', '-m', model_name, ssh_key, log=log,
107 loop=self.loop)
108 except Exception:
109 log.exception(
110 "Could not add ssh key to model. You will not be able "
111 "to ssh into machines in this model. "
112 "Manually running `juju add-ssh-key <key>` in the cli "
113 "may fix this problem.")
114
115 model = Model()
116 await model.connect(
117 self.connection.endpoint,
118 model_info.uuid,
119 self.connection.username,
120 self.connection.password,
121 self.connection.cacert,
122 self.connection.macaroons,
123 loop=self.loop,
124 )
125
126 return model
127
128 async def destroy_models(self, *uuids):
129 """Destroy one or more models.
130
131 :param str \*uuids: UUIDs of models to destroy
132
133 """
134 model_facade = client.ModelManagerFacade()
135 model_facade.connect(self.connection)
136
137 log.debug(
138 'Destroying model%s %s',
139 '' if len(uuids) == 1 else 's',
140 ', '.join(uuids)
141 )
142
143 await model_facade.DestroyModels([
144 client.Entity(tag.model(uuid))
145 for uuid in uuids
146 ])
147 destroy_model = destroy_models
148
149 def add_user(self, username, display_name=None, acl=None, models=None):
150 """Add a user to this controller.
151
152 :param str username: Username
153 :param str display_name: Display name
154 :param str acl: Access control, e.g. 'read'
155 :param list models: Models to which the user is granted access
156
157 """
158 raise NotImplementedError()
159
160 def change_user_password(self, username, password):
161 """Change the password for a user in this controller.
162
163 :param str username: Username
164 :param str password: New password
165
166 """
167 raise NotImplementedError()
168
169 def destroy(self, destroy_all_models=False):
170 """Destroy this controller.
171
172 :param bool destroy_all_models: Destroy all hosted models in the
173 controller.
174
175 """
176 raise NotImplementedError()
177
178 def disable_user(self, username):
179 """Disable a user.
180
181 :param str username: Username
182
183 """
184 raise NotImplementedError()
185
186 def enable_user(self):
187 """Re-enable a previously disabled user.
188
189 """
190 raise NotImplementedError()
191
192 def kill(self):
193 """Forcibly terminate all machines and other associated resources for
194 this controller.
195
196 """
197 raise NotImplementedError()
198
199 async def get_cloud(self):
200 """
201 Get the name of the cloud that this controller lives on.
202 """
203 cloud_facade = client.CloudFacade()
204 cloud_facade.connect(self.connection)
205
206 result = await cloud_facade.Clouds()
207 cloud = list(result.clouds.keys())[0] # only lives on one cloud
208 return tag.untag('cloud-', cloud)
209
210 def get_models(self, all_=False, username=None):
211 """Return list of available models on this controller.
212
213 :param bool all_: List all models, regardless of user accessibilty
214 (admin use only)
215 :param str username: User for which to list models (admin use only)
216
217 """
218 raise NotImplementedError()
219
220 def get_payloads(self, *patterns):
221 """Return list of known payloads.
222
223 :param str \*patterns: Patterns to match against
224
225 Each pattern will be checked against the following info in Juju::
226
227 - unit name
228 - machine id
229 - payload type
230 - payload class
231 - payload id
232 - payload tag
233 - payload status
234
235 """
236 raise NotImplementedError()
237
238 def get_users(self, all_=False):
239 """Return list of users that can connect to this controller.
240
241 :param bool all_: Include disabled users
242
243 """
244 raise NotImplementedError()
245
246 def login(self):
247 """Log in to this controller.
248
249 """
250 raise NotImplementedError()
251
252 def logout(self, force=False):
253 """Log out of this controller.
254
255 :param bool force: Don't fail even if user not previously logged in
256 with a password
257
258 """
259 raise NotImplementedError()
260
261 def get_model(self, name):
262 """Get a model by name.
263
264 :param str name: Model name
265
266 """
267 raise NotImplementedError()
268
269 def get_user(self, username):
270 """Get a user by name.
271
272 :param str username: Username
273
274 """
275 raise NotImplementedError()