9e8cb8fa01f362683a1b0b09eb65a212ccba33db
12 from http
.client
import HTTPSConnection
17 from juju
.errors
import JujuAPIError
, JujuConnectionError
19 log
= logging
.getLogger("websocket")
26 # Connect to an arbitrary api server
27 client = await Connection.connect(
28 api_endpoint, model_uuid, username, password, cacert)
30 # Connect using a controller/model name
31 client = await Connection.connect_model('local.local:default')
33 # Connect to the currently active model
34 client = await Connection.connect_current()
38 self
, endpoint
, uuid
, username
, password
, cacert
=None,
40 self
.endpoint
= endpoint
42 self
.username
= username
43 self
.password
= password
44 self
.macaroons
= macaroons
47 self
.__request
_id
__ = 0
58 def _get_ssl(self
, cert
=None):
59 return ssl
.create_default_context(
60 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
64 url
= "wss://{}/model/{}/api".format(self
.endpoint
, self
.uuid
)
66 url
= "wss://{}/api".format(self
.endpoint
)
69 kw
['ssl'] = self
._get
_ssl
(self
.cacert
)
71 self
.ws
= await websockets
.connect(url
, **kw
)
72 log
.info("Driver connected to juju %s", url
)
75 async def close(self
):
79 result
= await self
.ws
.recv()
80 if result
is not None:
81 result
= json
.loads(result
)
84 async def rpc(self
, msg
, encoder
=None):
85 self
.__request
_id
__ += 1
86 msg
['request-id'] = self
.__request
_id
__
87 if'params' not in msg
:
89 if "version" not in msg
:
90 msg
['version'] = self
.facades
[msg
['type']]
91 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
92 await self
.ws
.send(outgoing
)
93 result
= await self
.recv()
94 if result
and 'error' in result
:
95 raise JujuAPIError(result
)
98 def http_headers(self
):
99 """Return dictionary of http headers necessary for making an http
100 connection to the endpoint of this Connection.
102 :return: Dictionary of headers
105 if not self
.username
:
108 creds
= u
'{}:{}'.format(
109 tag
.user(self
.username
),
112 token
= base64
.b64encode(creds
.encode())
114 'Authorization': 'Basic {}'.format(token
.decode())
117 def https_connection(self
):
118 """Return an https connection to this Connection's endpoint.
120 Returns a 3-tuple containing::
122 1. The :class:`HTTPSConnection` instance
123 2. Dictionary of auth headers to be used with the connection
124 3. The root url path (str) to be used for requests.
127 endpoint
= self
.endpoint
128 host
, remainder
= endpoint
.split(':', 1)
131 port
, _
= remainder
.split('/', 1)
133 conn
= HTTPSConnection(
135 context
=self
._get
_ssl
(self
.cacert
),
139 "/model/{}".format(self
.uuid
)
142 return conn
, self
.http_headers(), path
144 async def clone(self
):
145 """Return a new Connection, connected to the same websocket endpoint
149 return await Connection
.connect(
158 async def controller(self
):
159 """Return a Connection to the controller at self.endpoint
162 return await Connection
.connect(
173 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
175 """Connect to the websocket.
177 If uuid is None, the connection will be to the controller. Otherwise it
178 will be to the model.
181 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
)
184 redirect_info
= await client
.redirect_info()
185 if not redirect_info
:
186 await client
.login(username
, password
, macaroons
)
191 s
for servers
in redirect_info
['servers']
192 for s
in servers
if s
["scope"] == 'public'
194 for server
in servers
:
196 "{value}:{port}".format(**server
), uuid
, username
,
197 password
, redirect_info
['ca-cert'], macaroons
)
200 result
= await client
.login(username
, password
, macaroons
)
201 if 'discharge-required-error' in result
:
204 except Exception as e
:
209 "Couldn't authenticate to %s", endpoint
)
212 async def connect_current(cls
):
213 """Connect to the currently active model.
216 jujudata
= JujuData()
217 controller_name
= jujudata
.current_controller()
218 models
= jujudata
.models()[controller_name
]
219 model_name
= models
['current-model']
221 return await cls
.connect_model(
222 '{}:{}'.format(controller_name
, model_name
))
225 async def connect_current_controller(cls
):
226 """Connect to the currently active controller.
229 jujudata
= JujuData()
230 controller_name
= jujudata
.current_controller()
231 if not controller_name
:
232 raise JujuConnectionError('No current controller')
234 return await cls
.connect_controller(controller_name
)
237 async def connect_controller(cls
, controller_name
):
238 """Connect to a controller by name.
241 jujudata
= JujuData()
242 controller
= jujudata
.controllers()[controller_name
]
243 endpoint
= controller
['api-endpoints'][0]
244 cacert
= controller
.get('ca-cert')
245 accounts
= jujudata
.accounts()[controller_name
]
246 username
= accounts
['user']
247 password
= accounts
.get('password')
248 macaroons
= get_macaroons() if not password
else None
250 return await cls
.connect(
251 endpoint
, None, username
, password
, cacert
, macaroons
)
254 async def connect_model(cls
, model
):
255 """Connect to a model by name.
257 :param str model: <controller>:<model>
260 controller_name
, model_name
= model
.split(':')
262 jujudata
= JujuData()
263 controller
= jujudata
.controllers()[controller_name
]
264 endpoint
= controller
['api-endpoints'][0]
265 cacert
= controller
.get('ca-cert')
266 accounts
= jujudata
.accounts()[controller_name
]
267 username
= accounts
['user']
268 password
= accounts
.get('password')
269 models
= jujudata
.models()[controller_name
]
270 model_uuid
= models
['models'][model_name
]['uuid']
271 macaroons
= get_macaroons() if not password
else None
273 return await cls
.connect(
274 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
)
276 def build_facades(self
, info
):
279 self
.facades
[facade
['name']] = facade
['versions'][-1]
281 async def login(self
, username
, password
, macaroons
=None):
286 if username
and not username
.startswith('user-'):
287 username
= 'user-{}'.format(username
)
289 result
= await self
.rpc({
294 "auth-tag": username
,
295 "credentials": password
,
296 "nonce": "".join(random
.sample(string
.printable
, 12)),
297 "macaroons": macaroons
or []
299 response
= result
['response']
300 self
.build_facades(response
.get('facades', {}))
301 self
.info
= response
.copy()
304 async def redirect_info(self
):
306 result
= await self
.rpc({
308 "request": "RedirectInfo",
311 except JujuAPIError
as e
:
312 if e
.message
== 'not redirected':
315 return result
['response']
320 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
321 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
323 def current_controller(self
):
324 cmd
= shlex
.split('juju list-controllers --format yaml')
325 output
= subprocess
.check_output(cmd
)
326 output
= yaml
.safe_load(output
)
327 return output
.get('current-controller', '')
329 def controllers(self
):
330 return self
._load
_yaml
('controllers.yaml', 'controllers')
333 return self
._load
_yaml
('models.yaml', 'controllers')
336 return self
._load
_yaml
('accounts.yaml', 'controllers')
338 def _load_yaml(self
, filename
, key
):
339 filepath
= os
.path
.join(self
.path
, filename
)
340 with io
.open(filepath
, 'rt') as f
:
341 return yaml
.safe_load(f
)[key
]
345 """Decode and return macaroons from default ~/.go-cookies
349 cookie_file
= os
.path
.expanduser('~/.go-cookies')
350 with
open(cookie_file
, 'r') as f
:
351 cookies
= json
.load(f
)
352 except (OSError, ValueError) as e
:
353 log
.warn("Couldn't load macaroons from %s", cookie_file
)
357 c
['Value'] for c
in cookies
358 if c
['Name'].startswith('macaroon-') and c
['Value']
362 json
.loads(base64
.b64decode(value
).decode('utf-8'))
363 for value
in base64_macaroons