3b5bfc4828552fd5f29602d45e920f34bb3419aa
14 log
= logging
.getLogger("websocket")
21 # Connect to an arbitrary api server
22 client = await Connection.connect(
23 api_endpoint, model_uuid, username, password, cacert)
25 # Connect using a controller/model name
26 client = await Connection.connect_model('local.local:default')
28 # Connect to the currently active model
29 client = await Connection.connect_current()
32 def __init__(self
, endpoint
, uuid
, username
, password
, cacert
=None):
33 self
.endpoint
= endpoint
35 self
.username
= username
36 self
.password
= password
39 self
.__request
_id
__ = 0
50 def _get_ssl(self
, cert
):
51 return ssl
.create_default_context(
52 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
54 async def open(self
, addr
, cert
=None):
57 kw
['ssl'] = self
._get
_ssl
(cert
)
59 self
.ws
= await websockets
.connect(addr
, **kw
)
62 async def close(self
):
66 result
= await self
.ws
.recv()
67 if result
is not None:
68 result
= json
.loads(result
)
71 async def rpc(self
, msg
, encoder
=None):
72 self
.__request
_id
__ += 1
73 msg
['request-id'] = self
.__request
_id
__
74 if'params' not in msg
:
76 if "version" not in msg
:
77 msg
['version'] = self
.facades
[msg
['type']]
78 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
79 await self
.ws
.send(outgoing
)
80 result
= await self
.recv()
81 #log.debug("Send: %s", outgoing)
82 #log.debug("Recv: %s", result)
83 if result
and 'error' in result
:
84 raise RuntimeError(result
)
87 async def clone(self
):
88 """Return a new Connection, connected to the same websocket endpoint
92 return await Connection
.connect(
100 async def controller(self
):
101 """Return a Connection to the controller at self.endpoint
104 return await Connection
.connect(
113 async def connect(cls
, endpoint
, uuid
, username
, password
, cacert
=None):
114 """Connect to the websocket.
116 If uuid is None, the connection will be to the controller. Otherwise it
117 will be to the model.
121 url
= "wss://{}/model/{}/api".format(endpoint
, uuid
)
123 url
= "wss://{}/api".format(endpoint
)
124 client
= cls(endpoint
, uuid
, username
, password
, cacert
)
125 await client
.open(url
, cacert
)
126 server_info
= await client
.login(username
, password
)
127 client
.build_facades(server_info
['facades'])
128 log
.info("Driver connected to juju %s", url
)
133 async def connect_current(cls
):
134 """Connect to the currently active model.
137 jujudata
= JujuData()
138 controller_name
= jujudata
.current_controller()
139 controller
= jujudata
.controllers()[controller_name
]
140 endpoint
= controller
['api-endpoints'][0]
141 cacert
= controller
.get('ca-cert')
142 accounts
= jujudata
.accounts()[controller_name
]
143 username
= accounts
['user']
144 password
= accounts
['password']
145 models
= jujudata
.models()[controller_name
]
146 model_name
= models
['current-model']
147 model_uuid
= models
['models'][model_name
]['uuid']
149 return await cls
.connect(
150 endpoint
, model_uuid
, username
, password
, cacert
)
153 async def connect_model(cls
, model
):
154 """Connect to a model by name.
156 :param str model: <controller>:<model>
159 controller_name
, model_name
= model
.split(':')
161 jujudata
= JujuData()
162 controller
= jujudata
.controllers()[controller_name
]
163 endpoint
= controller
['api-endpoints'][0]
164 cacert
= controller
.get('ca-cert')
165 accounts
= jujudata
.accounts()[controller_name
]
166 username
= accounts
['user']
167 password
= accounts
['password']
168 models
= jujudata
.models()[controller_name
]
169 model_uuid
= models
['models'][model_name
]['uuid']
171 return await cls
.connect(
172 endpoint
, model_uuid
, username
, password
, cacert
)
174 def build_facades(self
, info
):
177 self
.facades
[facade
['name']] = facade
['versions'][-1]
179 async def login(self
, username
, password
):
180 if not username
.startswith('user-'):
181 username
= 'user-{}'.format(username
)
183 result
= await self
.rpc({
188 "auth-tag": username
,
189 "credentials": password
,
190 "nonce": "".join(random
.sample(string
.printable
, 12)),
192 return result
['response']
197 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
198 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
200 def current_controller(self
):
201 cmd
= shlex
.split('juju show-controller --format yaml')
202 output
= subprocess
.check_output(cmd
)
203 output
= yaml
.safe_load(output
)
204 return list(output
.keys())[0]
206 def controllers(self
):
207 return self
._load
_yaml
('controllers.yaml', 'controllers')
210 return self
._load
_yaml
('models.yaml', 'controllers')
213 return self
._load
_yaml
('accounts.yaml', 'controllers')
215 def _load_yaml(self
, filename
, key
):
216 filepath
= os
.path
.join(self
.path
, filename
)
217 with io
.open(filepath
, 'rt') as f
:
218 return yaml
.safe_load(f
)[key
]