b508a1ac924ebf692eaef432ef3be471b86b2d37
12 from http
.client
import HTTPSConnection
18 from juju
.errors
import JujuError
, JujuAPIError
, JujuConnectionError
20 log
= logging
.getLogger("websocket")
27 # Connect to an arbitrary api server
28 client = await Connection.connect(
29 api_endpoint, model_uuid, username, password, cacert)
31 # Connect using a controller/model name
32 client = await Connection.connect_model('local.local:default')
34 # Connect to the currently active model
35 client = await Connection.connect_current()
37 Note: Any connection method or constructor can accept an optional `loop`
38 argument to override the default event loop from `asyncio.get_event_loop`.
41 self
, endpoint
, uuid
, username
, password
, cacert
=None,
42 macaroons
=None, loop
=None):
43 self
.endpoint
= endpoint
45 self
.username
= username
46 self
.password
= password
47 self
.macaroons
= macaroons
49 self
.loop
= loop
or asyncio
.get_event_loop()
51 self
.__request
_id
__ = 0
62 def _get_ssl(self
, cert
=None):
63 return ssl
.create_default_context(
64 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
68 url
= "wss://{}/model/{}/api".format(self
.endpoint
, self
.uuid
)
70 url
= "wss://{}/api".format(self
.endpoint
)
73 kw
['ssl'] = self
._get
_ssl
(self
.cacert
)
74 kw
['loop'] = self
.loop
76 self
.ws
= await websockets
.connect(url
, **kw
)
77 log
.info("Driver connected to juju %s", url
)
80 async def close(self
):
84 result
= await self
.ws
.recv()
85 if result
is not None:
86 result
= json
.loads(result
)
89 async def rpc(self
, msg
, encoder
=None):
90 self
.__request
_id
__ += 1
91 msg
['request-id'] = self
.__request
_id
__
92 if'params' not in msg
:
94 if "version" not in msg
:
95 msg
['version'] = self
.facades
[msg
['type']]
96 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
97 await self
.ws
.send(outgoing
)
98 result
= await self
.recv()
103 if 'error' in result
:
105 raise JujuAPIError(result
)
107 if not 'response' in result
:
108 # This may never happen
111 if 'results' in result
['response']:
112 # Check for errors in a result list.
114 for res
in result
['response']['results']:
115 if res
.get('error', {}).get('message'):
116 errors
.append(res
['error']['message'])
118 raise JujuError(errors
)
120 elif result
['response'].get('error', {}).get('message'):
121 raise JujuError(result
['response']['error']['message'])
125 def http_headers(self
):
126 """Return dictionary of http headers necessary for making an http
127 connection to the endpoint of this Connection.
129 :return: Dictionary of headers
132 if not self
.username
:
135 creds
= u
'{}:{}'.format(
136 tag
.user(self
.username
),
139 token
= base64
.b64encode(creds
.encode())
141 'Authorization': 'Basic {}'.format(token
.decode())
144 def https_connection(self
):
145 """Return an https connection to this Connection's endpoint.
147 Returns a 3-tuple containing::
149 1. The :class:`HTTPSConnection` instance
150 2. Dictionary of auth headers to be used with the connection
151 3. The root url path (str) to be used for requests.
154 endpoint
= self
.endpoint
155 host
, remainder
= endpoint
.split(':', 1)
158 port
, _
= remainder
.split('/', 1)
160 conn
= HTTPSConnection(
162 context
=self
._get
_ssl
(self
.cacert
),
166 "/model/{}".format(self
.uuid
)
169 return conn
, self
.http_headers(), path
171 async def clone(self
):
172 """Return a new Connection, connected to the same websocket endpoint
176 return await Connection
.connect(
186 async def controller(self
):
187 """Return a Connection to the controller at self.endpoint
190 return await Connection
.connect(
202 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
203 macaroons
=None, loop
=None):
204 """Connect to the websocket.
206 If uuid is None, the connection will be to the controller. Otherwise it
207 will be to the model.
210 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
,
214 redirect_info
= await client
.redirect_info()
215 if not redirect_info
:
216 await client
.login(username
, password
, macaroons
)
221 s
for servers
in redirect_info
['servers']
222 for s
in servers
if s
["scope"] == 'public'
224 for server
in servers
:
226 "{value}:{port}".format(**server
), uuid
, username
,
227 password
, redirect_info
['ca-cert'], macaroons
)
230 result
= await client
.login(username
, password
, macaroons
)
231 if 'discharge-required-error' in result
:
234 except Exception as e
:
239 "Couldn't authenticate to %s", endpoint
)
242 async def connect_current(cls
, loop
=None):
243 """Connect to the currently active model.
246 jujudata
= JujuData()
247 controller_name
= jujudata
.current_controller()
248 model_name
= jujudata
.current_model()
250 return await cls
.connect_model(
251 '{}:{}'.format(controller_name
, model_name
), loop
)
254 async def connect_current_controller(cls
, loop
=None):
255 """Connect to the currently active controller.
258 jujudata
= JujuData()
259 controller_name
= jujudata
.current_controller()
260 if not controller_name
:
261 raise JujuConnectionError('No current controller')
263 return await cls
.connect_controller(controller_name
, loop
)
266 async def connect_controller(cls
, controller_name
, loop
=None):
267 """Connect to a controller by name.
270 jujudata
= JujuData()
271 controller
= jujudata
.controllers()[controller_name
]
272 endpoint
= controller
['api-endpoints'][0]
273 cacert
= controller
.get('ca-cert')
274 accounts
= jujudata
.accounts()[controller_name
]
275 username
= accounts
['user']
276 password
= accounts
.get('password')
277 macaroons
= get_macaroons() if not password
else None
279 return await cls
.connect(
280 endpoint
, None, username
, password
, cacert
, macaroons
, loop
)
283 async def connect_model(cls
, model
, loop
=None):
284 """Connect to a model by name.
286 :param str model: [<controller>:]<model>
289 jujudata
= JujuData()
292 # explicit controller given
293 controller_name
, model_name
= model
.split(':')
295 # use the current controller if one isn't explicitly given
296 controller_name
= jujudata
.current_controller()
299 accounts
= jujudata
.accounts()[controller_name
]
300 username
= accounts
['user']
301 # model name must include a user prefix, so add it if it doesn't
302 if '/' not in model_name
:
303 model_name
= '{}/{}'.format(username
, model_name
)
305 controller
= jujudata
.controllers()[controller_name
]
306 endpoint
= controller
['api-endpoints'][0]
307 cacert
= controller
.get('ca-cert')
308 password
= accounts
.get('password')
309 models
= jujudata
.models()[controller_name
]
310 model_uuid
= models
['models'][model_name
]['uuid']
311 macaroons
= get_macaroons() if not password
else None
313 return await cls
.connect(
314 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
, loop
)
316 def build_facades(self
, info
):
319 self
.facades
[facade
['name']] = facade
['versions'][-1]
321 async def login(self
, username
, password
, macaroons
=None):
326 if username
and not username
.startswith('user-'):
327 username
= 'user-{}'.format(username
)
329 result
= await self
.rpc({
334 "auth-tag": username
,
335 "credentials": password
,
336 "nonce": "".join(random
.sample(string
.printable
, 12)),
337 "macaroons": macaroons
or []
339 response
= result
['response']
340 self
.build_facades(response
.get('facades', {}))
341 self
.info
= response
.copy()
344 async def redirect_info(self
):
346 result
= await self
.rpc({
348 "request": "RedirectInfo",
351 except JujuAPIError
as e
:
352 if e
.message
== 'not redirected':
355 return result
['response']
360 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
361 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
363 def current_controller(self
):
364 cmd
= shlex
.split('juju list-controllers --format yaml')
365 output
= subprocess
.check_output(cmd
)
366 output
= yaml
.safe_load(output
)
367 return output
.get('current-controller', '')
369 def current_model(self
, controller_name
=None):
370 if not controller_name
:
371 controller_name
= self
.current_controller()
372 models
= self
.models()[controller_name
]
373 if 'current-model' not in models
:
374 raise JujuError('No current model')
375 return models
['current-model']
377 def controllers(self
):
378 return self
._load
_yaml
('controllers.yaml', 'controllers')
381 return self
._load
_yaml
('models.yaml', 'controllers')
384 return self
._load
_yaml
('accounts.yaml', 'controllers')
386 def _load_yaml(self
, filename
, key
):
387 filepath
= os
.path
.join(self
.path
, filename
)
388 with io
.open(filepath
, 'rt') as f
:
389 return yaml
.safe_load(f
)[key
]
393 """Decode and return macaroons from default ~/.go-cookies
397 cookie_file
= os
.path
.expanduser('~/.go-cookies')
398 with
open(cookie_file
, 'r') as f
:
399 cookies
= json
.load(f
)
400 except (OSError, ValueError):
401 log
.warn("Couldn't load macaroons from %s", cookie_file
)
405 c
['Value'] for c
in cookies
406 if c
['Name'].startswith('macaroon-') and c
['Value']
410 json
.loads(base64
.b64decode(value
).decode('utf-8'))
411 for value
in base64_macaroons