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()
99 if result
and 'error' in result
:
100 raise JujuAPIError(result
)
103 def http_headers(self
):
104 """Return dictionary of http headers necessary for making an http
105 connection to the endpoint of this Connection.
107 :return: Dictionary of headers
110 if not self
.username
:
113 creds
= u
'{}:{}'.format(
114 tag
.user(self
.username
),
117 token
= base64
.b64encode(creds
.encode())
119 'Authorization': 'Basic {}'.format(token
.decode())
122 def https_connection(self
):
123 """Return an https connection to this Connection's endpoint.
125 Returns a 3-tuple containing::
127 1. The :class:`HTTPSConnection` instance
128 2. Dictionary of auth headers to be used with the connection
129 3. The root url path (str) to be used for requests.
132 endpoint
= self
.endpoint
133 host
, remainder
= endpoint
.split(':', 1)
136 port
, _
= remainder
.split('/', 1)
138 conn
= HTTPSConnection(
140 context
=self
._get
_ssl
(self
.cacert
),
144 "/model/{}".format(self
.uuid
)
147 return conn
, self
.http_headers(), path
149 async def clone(self
):
150 """Return a new Connection, connected to the same websocket endpoint
154 return await Connection
.connect(
164 async def controller(self
):
165 """Return a Connection to the controller at self.endpoint
168 return await Connection
.connect(
180 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
181 macaroons
=None, loop
=None):
182 """Connect to the websocket.
184 If uuid is None, the connection will be to the controller. Otherwise it
185 will be to the model.
188 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
,
192 redirect_info
= await client
.redirect_info()
193 if not redirect_info
:
194 await client
.login(username
, password
, macaroons
)
199 s
for servers
in redirect_info
['servers']
200 for s
in servers
if s
["scope"] == 'public'
202 for server
in servers
:
204 "{value}:{port}".format(**server
), uuid
, username
,
205 password
, redirect_info
['ca-cert'], macaroons
)
208 result
= await client
.login(username
, password
, macaroons
)
209 if 'discharge-required-error' in result
:
212 except Exception as e
:
217 "Couldn't authenticate to %s", endpoint
)
220 async def connect_current(cls
, loop
=None):
221 """Connect to the currently active model.
224 jujudata
= JujuData()
225 controller_name
= jujudata
.current_controller()
226 model_name
= jujudata
.current_model()
228 return await cls
.connect_model(
229 '{}:{}'.format(controller_name
, model_name
), loop
)
232 async def connect_current_controller(cls
, loop
=None):
233 """Connect to the currently active controller.
236 jujudata
= JujuData()
237 controller_name
= jujudata
.current_controller()
238 if not controller_name
:
239 raise JujuConnectionError('No current controller')
241 return await cls
.connect_controller(controller_name
, loop
)
244 async def connect_controller(cls
, controller_name
, loop
=None):
245 """Connect to a controller by name.
248 jujudata
= JujuData()
249 controller
= jujudata
.controllers()[controller_name
]
250 endpoint
= controller
['api-endpoints'][0]
251 cacert
= controller
.get('ca-cert')
252 accounts
= jujudata
.accounts()[controller_name
]
253 username
= accounts
['user']
254 password
= accounts
.get('password')
255 macaroons
= get_macaroons() if not password
else None
257 return await cls
.connect(
258 endpoint
, None, username
, password
, cacert
, macaroons
, loop
)
261 async def connect_model(cls
, model
, loop
=None):
262 """Connect to a model by name.
264 :param str model: [<controller>:]<model>
267 jujudata
= JujuData()
270 # explicit controller given
271 controller_name
, model_name
= model
.split(':')
273 # use the current controller if one isn't explicitly given
274 controller_name
= jujudata
.current_controller()
277 accounts
= jujudata
.accounts()[controller_name
]
278 username
= accounts
['user']
279 # model name must include a user prefix, so add it if it doesn't
280 if '/' not in model_name
:
281 model_name
= '{}/{}'.format(username
, model_name
)
283 controller
= jujudata
.controllers()[controller_name
]
284 endpoint
= controller
['api-endpoints'][0]
285 cacert
= controller
.get('ca-cert')
286 password
= accounts
.get('password')
287 models
= jujudata
.models()[controller_name
]
288 model_uuid
= models
['models'][model_name
]['uuid']
289 macaroons
= get_macaroons() if not password
else None
291 return await cls
.connect(
292 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
, loop
)
294 def build_facades(self
, info
):
297 self
.facades
[facade
['name']] = facade
['versions'][-1]
299 async def login(self
, username
, password
, macaroons
=None):
304 if username
and not username
.startswith('user-'):
305 username
= 'user-{}'.format(username
)
307 result
= await self
.rpc({
312 "auth-tag": username
,
313 "credentials": password
,
314 "nonce": "".join(random
.sample(string
.printable
, 12)),
315 "macaroons": macaroons
or []
317 response
= result
['response']
318 self
.build_facades(response
.get('facades', {}))
319 self
.info
= response
.copy()
322 async def redirect_info(self
):
324 result
= await self
.rpc({
326 "request": "RedirectInfo",
329 except JujuAPIError
as e
:
330 if e
.message
== 'not redirected':
333 return result
['response']
338 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
339 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
341 def current_controller(self
):
342 cmd
= shlex
.split('juju list-controllers --format yaml')
343 output
= subprocess
.check_output(cmd
)
344 output
= yaml
.safe_load(output
)
345 return output
.get('current-controller', '')
347 def current_model(self
, controller_name
=None):
348 if not controller_name
:
349 controller_name
= self
.current_controller()
350 models
= self
.models()[controller_name
]
351 if 'current-model' not in models
:
352 raise JujuError('No current model')
353 return models
['current-model']
355 def controllers(self
):
356 return self
._load
_yaml
('controllers.yaml', 'controllers')
359 return self
._load
_yaml
('models.yaml', 'controllers')
362 return self
._load
_yaml
('accounts.yaml', 'controllers')
364 def _load_yaml(self
, filename
, key
):
365 filepath
= os
.path
.join(self
.path
, filename
)
366 with io
.open(filepath
, 'rt') as f
:
367 return yaml
.safe_load(f
)[key
]
371 """Decode and return macaroons from default ~/.go-cookies
375 cookie_file
= os
.path
.expanduser('~/.go-cookies')
376 with
open(cookie_file
, 'r') as f
:
377 cookies
= json
.load(f
)
378 except (OSError, ValueError):
379 log
.warn("Couldn't load macaroons from %s", cookie_file
)
383 c
['Value'] for c
in cookies
384 if c
['Name'].startswith('macaroon-') and c
['Value']
388 json
.loads(base64
.b64decode(value
).decode('utf-8'))
389 for value
in base64_macaroons