| 1 |
# Copyright 2016 Red Hat, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 |
# not use this file except in compliance with the License. You may obtain |
| 5 |
# a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 |
# License for the specific language governing permissions and limitations |
| 13 |
# under the License. |
| 14 |
# |
| 15 |
import json |
| 16 |
|
| 17 |
from oslo_log import log as logging |
| 18 |
from oslo_utils import importutils |
| 19 |
from oslo_utils import uuidutils |
| 20 |
|
| 21 |
from zaqarclient.transport import base |
| 22 |
from zaqarclient.transport import request |
| 23 |
from zaqarclient.transport import response |
| 24 |
|
| 25 |
websocket = importutils.try_import('websocket') |
| 26 |
|
| 27 |
LOG = logging.getLogger(__name__) |
| 28 |
|
| 29 |
|
| 30 |
class WebsocketTransport(base.Transport): |
| 31 |
|
| 32 |
"""Zaqar websocket transport. |
| 33 |
|
| 34 |
*NOTE:* Zaqar's websocket interface does not yet appear to work |
| 35 |
well with parameters. Until it does the websocket transport may not |
| 36 |
integrate with all of zaqarclients higherlevel request. Even so... |
| 37 |
websockets today is still quite usable and use of the transport |
| 38 |
via lower level API's in zaqarclient work quite nicely. Example: |
| 39 |
|
| 40 |
conf = { |
| 41 |
'auth_opts': { |
| 42 |
'backend': 'keystone', |
| 43 |
'options': { |
| 44 |
'os_auth_token': ks.auth_token, |
| 45 |
'os_project_id': CONF.zaqar.project_id |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
endpoint = 'ws://172.19.0.3:9000' |
| 51 |
|
| 52 |
with transport.get_transport_for(endpoint, options=conf) as ws: |
| 53 |
req = request.Request(endpoint, 'queue_create', |
| 54 |
content=json.dumps({'queue_name': 'foo'})) |
| 55 |
resp = ws.send(req) |
| 56 |
|
| 57 |
""" |
| 58 |
def __init__(self, options): |
| 59 |
super().__init__(options) |
| 60 |
option = options['auth_opts']['options'] |
| 61 |
# TODO(wangxiyuan): To keep backwards compatibility, we leave |
| 62 |
# "os_project_id" here. Remove it in the next release. |
| 63 |
self._project_id = option.get('os_project_id', |
| 64 |
option.get('project_id')) |
| 65 |
self._token = options['auth_opts']['options']['os_auth_token'] |
| 66 |
self._websocket_client_id = None |
| 67 |
self._ws = None |
| 68 |
|
| 69 |
def _init_client(self, endpoint): |
| 70 |
"""Initialize a websocket transport client. |
| 71 |
|
| 72 |
:param endpoint: The websocket endpoint. Example: ws://127.0.0.1:9000/. |
| 73 |
Required. |
| 74 |
:type endpoint: string |
| 75 |
""" |
| 76 |
self._websocket_client_id = uuidutils.generate_uuid() |
| 77 |
|
| 78 |
LOG.debug('Instantiating messaging websocket client: %s', endpoint) |
| 79 |
self._ws = self._create_connection(endpoint) |
| 80 |
|
| 81 |
auth_req = request.Request(endpoint, 'authenticate', |
| 82 |
headers={'X-Auth-Token': self._token}) |
| 83 |
self.send(auth_req) |
| 84 |
|
| 85 |
def _create_connection(self, endpoint): |
| 86 |
return websocket.create_connection(endpoint) |
| 87 |
|
| 88 |
def send(self, request): |
| 89 |
if not self._ws: |
| 90 |
self._init_client(request.endpoint) |
| 91 |
|
| 92 |
headers = request.headers.copy() |
| 93 |
headers.update({ |
| 94 |
'Client-ID': self._websocket_client_id, |
| 95 |
'X-Project-ID': self._project_id |
| 96 |
}) |
| 97 |
|
| 98 |
msg = {'action': request.operation, 'headers': headers} |
| 99 |
if request.content: |
| 100 |
msg['body'] = json.loads(request.content) |
| 101 |
# NOTE(dprince): Zaqar websockets do not yet seem to support params?! |
| 102 |
# Users of this protocol will need to send everything in the body. |
| 103 |
if request.params: |
| 104 |
LOG.warning('Websocket transport does not yet support params.') |
| 105 |
self._ws.send(json.dumps(msg)) |
| 106 |
ret = self.recv() |
| 107 |
|
| 108 |
resp = response.Response(request, json.dumps(ret.get('body', '')), |
| 109 |
headers=ret['headers'], |
| 110 |
status_code=int(ret['headers']['status'])) |
| 111 |
|
| 112 |
if resp.status_code in self.http_to_zaqar: |
| 113 |
kwargs = {} |
| 114 |
try: |
| 115 |
error_body = json.loads(resp.content) |
| 116 |
kwargs['title'] = 'Websocket Transport Error' |
| 117 |
kwargs['description'] = error_body['error'] |
| 118 |
except Exception: |
| 119 |
kwargs['text'] = resp.content |
| 120 |
raise self.http_to_zaqar[resp.status_code](**kwargs) |
| 121 |
|
| 122 |
return resp |
| 123 |
|
| 124 |
def recv(self): |
| 125 |
return json.loads(self._ws.recv()) |
| 126 |
|
| 127 |
def cleanup(self): |
| 128 |
if self._ws: |
| 129 |
self._ws.close() |
| 130 |
self._ws = None |
| 131 |
|
| 132 |
def __enter__(self): |
| 133 |
"""Return self to allow usage as a context manager""" |
| 134 |
return self |
| 135 |
|
| 136 |
def __exit__(self, *exc): |
| 137 |
"""Call cleanup when exiting the context manager""" |
| 138 |
self.cleanup() |