Expanding controller.py with basic user functions, get_models and destroy (#89)
[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 self.controller_name = None
26
27 async def connect(
28 self, endpoint, username, password, cacert=None, macaroons=None):
29 """Connect to an arbitrary Juju controller.
30
31 """
32 self.connection = await connection.Connection.connect(
33 endpoint, None, username, password, cacert, macaroons)
34
35 async def connect_current(self):
36 """Connect to the current Juju controller.
37
38 """
39 self.connection = (
40 await connection.Connection.connect_current_controller())
41
42 async def connect_controller(self, controller_name):
43 """Connect to a Juju controller by name.
44
45 """
46 self.connection = (
47 await connection.Connection.connect_controller(controller_name))
48 self.controller_name = controller_name
49
50 async def disconnect(self):
51 """Shut down the watcher task and close websockets.
52
53 """
54 if self.connection and self.connection.is_open:
55 log.debug('Closing controller connection')
56 await self.connection.close()
57 self.connection = None
58
59 async def add_model(
60 self, model_name, cloud_name=None, credential_name=None,
61 owner=None, config=None, region=None):
62 """Add a model to this controller.
63
64 :param str model_name: Name to give the new model.
65 :param str cloud_name: Name of the cloud in which to create the
66 model, e.g. 'aws'. Defaults to same cloud as controller.
67 :param str credential_name: Name of the credential to use when
68 creating the model. Defaults to current credential. If you
69 pass a credential_name, you must also pass a cloud_name,
70 even if it's the default cloud.
71 :param str owner: Username that will own the model. Defaults to
72 the current user.
73 :param dict config: Model configuration.
74 :param str region: Region in which to create the model.
75
76 """
77 model_facade = client.ModelManagerFacade()
78 model_facade.connect(self.connection)
79
80 owner = owner or self.connection.info['user-info']['identity']
81 cloud_name = cloud_name or await self.get_cloud()
82
83 if credential_name:
84 credential = tag.credential(
85 cloud_name,
86 tag.untag('user-', owner),
87 credential_name
88 )
89 else:
90 credential = None
91
92 log.debug('Creating model %s', model_name)
93
94 model_info = await model_facade.CreateModel(
95 tag.cloud(cloud_name),
96 config,
97 credential,
98 model_name,
99 owner,
100 region
101 )
102
103 # Add our ssh key to the model, to work around
104 # https://bugs.launchpad.net/juju/+bug/1643076
105 try:
106 ssh_key = await utils.read_ssh_key(loop=self.loop)
107
108 if self.controller_name:
109 model_name = "{}:{}".format(self.controller_name, model_name)
110
111 cmd = ['juju', 'add-ssh-key', '-m', model_name, ssh_key]
112
113 await utils.execute_process(*cmd, log=log, loop=self.loop)
114 except Exception:
115 log.exception(
116 "Could not add ssh key to model. You will not be able "
117 "to ssh into machines in this model. "
118 "Manually running `juju add-ssh-key <key>` in the cli "
119 "may fix this problem.")
120
121 model = Model()
122 await model.connect(
123 self.connection.endpoint,
124 model_info.uuid,
125 self.connection.username,
126 self.connection.password,
127 self.connection.cacert,
128 self.connection.macaroons,
129 loop=self.loop,
130 )
131
132 return model
133
134 async def destroy_models(self, *uuids):
135 """Destroy one or more models.
136
137 :param str \*uuids: UUIDs of models to destroy
138
139 """
140 model_facade = client.ModelManagerFacade()
141 model_facade.connect(self.connection)
142
143 log.debug(
144 'Destroying model%s %s',
145 '' if len(uuids) == 1 else 's',
146 ', '.join(uuids)
147 )
148
149 await model_facade.DestroyModels([
150 client.Entity(tag.model(uuid))
151 for uuid in uuids
152 ])
153 destroy_model = destroy_models
154
155 async def add_user(self, username, password=None, display_name=None):
156 """Add a user to this controller.
157
158 :param str username: Username
159 :param str display_name: Display name
160 :param str acl: Access control, e.g. 'read'
161 :param list models: Models to which the user is granted access
162
163 """
164 if not display_name:
165 display_name = username
166 user_facade = client.UserManagerFacade()
167 user_facade.connect(self.connection)
168 users = [{'display_name': display_name,
169 'password': password,
170 'username': username}]
171 return await user_facade.AddUser(users)
172
173 async def change_user_password(self, username, password):
174 """Change the password for a user in this controller.
175
176 :param str username: Username
177 :param str password: New password
178
179 """
180 user_facade = client.UserManagerFacade()
181 user_facade.connect(self.connection)
182 entity = client.EntityPassword(password, tag.user(username))
183 return await user_facade.SetPassword([entity])
184
185 async def destroy(self, destroy_all_models=False):
186 """Destroy this controller.
187
188 :param bool destroy_all_models: Destroy all hosted models in the
189 controller.
190
191 """
192 controller_facade = client.ControllerFacade()
193 controller_facade.connect(self.connection)
194 return await controller_facade.DestroyController(destroy_all_models)
195
196 async def disable_user(self, username):
197 """Disable a user.
198
199 :param str username: Username
200
201 """
202 user_facade = client.UserManagerFacade()
203 user_facade.connect(self.connection)
204 entity = client.Entity(tag.user(username))
205 return await user_facade.DisableUser([entity])
206
207 async def enable_user(self, username):
208 """Re-enable a previously disabled user.
209
210 """
211 user_facade = client.UserManagerFacade()
212 user_facade.connect(self.connection)
213 entity = client.Entity(tag.user(username))
214 return await user_facade.EnableUser([entity])
215
216 def kill(self):
217 """Forcibly terminate all machines and other associated resources for
218 this controller.
219
220 """
221 raise NotImplementedError()
222
223 async def get_cloud(self):
224 """
225 Get the name of the cloud that this controller lives on.
226 """
227 cloud_facade = client.CloudFacade()
228 cloud_facade.connect(self.connection)
229
230 result = await cloud_facade.Clouds()
231 cloud = list(result.clouds.keys())[0] # only lives on one cloud
232 return tag.untag('cloud-', cloud)
233
234 async def get_models(self, all_=False, username=None):
235 """Return list of available models on this controller.
236
237 :param bool all_: List all models, regardless of user accessibilty
238 (admin use only)
239 :param str username: User for which to list models (admin use only)
240
241 """
242 controller_facade = client.ControllerFacade()
243 controller_facade.connect(self.connection)
244 return await controller_facade.AllModels()
245
246
247 def get_payloads(self, *patterns):
248 """Return list of known payloads.
249
250 :param str \*patterns: Patterns to match against
251
252 Each pattern will be checked against the following info in Juju::
253
254 - unit name
255 - machine id
256 - payload type
257 - payload class
258 - payload id
259 - payload tag
260 - payload status
261
262 """
263 raise NotImplementedError()
264
265 def get_users(self, all_=False):
266 """Return list of users that can connect to this controller.
267
268 :param bool all_: Include disabled users
269
270 """
271 raise NotImplementedError()
272
273 def login(self):
274 """Log in to this controller.
275
276 """
277 raise NotImplementedError()
278
279 def logout(self, force=False):
280 """Log out of this controller.
281
282 :param bool force: Don't fail even if user not previously logged in
283 with a password
284
285 """
286 raise NotImplementedError()
287
288 def get_model(self, name):
289 """Get a model by name.
290
291 :param str name: Model name
292
293 """
294 raise NotImplementedError()
295
296 async def get_user(self, username, include_disabled=False):
297 """Get a user by name.
298
299 :param str username: Username
300
301 """
302 client_facade = client.UserManagerFacade()
303 client_facade.connect(self.connection)
304 user = tag.user(username)
305 return await client_facade.UserInfo([client.Entity(user)], include_disabled)
306
307 async def grant(self, username, acl='login'):
308 """Set access level of the given user on the controller
309
310 :param str username: Username
311 :param str acl: Access control ('login', 'add-model' or 'superuser')
312
313 """
314 controller_facade = client.ControllerFacade()
315 controller_facade.connect(self.connection)
316 user = tag.user(username)
317 await self.revoke(username)
318 changes = client.ModifyControllerAccess(acl, 'grant', user)
319 return await controller_facade.ModifyControllerAccess([changes])
320
321 async def revoke(self, username):
322 """Removes all access from a controller
323
324 :param str username: username
325
326 """
327 controller_facade = client.ControllerFacade()
328 controller_facade.connect(self.connection)
329 user = tag.user(username)
330 changes = client.ModifyControllerAccess('login', 'revoke', user)
331 return await controller_facade.ModifyControllerAccess([changes])