Fix AAI request url for NxI Termination
[optf/osdf.git] / osdf / adapters / dcae / message_router.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2015-2017 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 import requests
20 from osdf.utils.data_types import list_like
21 from osdf.operation.exceptions import MessageBusConfigurationException
22
23
24 class MessageRouterClient(object):
25     def __init__(self,
26                  dmaap_url='',
27                  consumer_group_id=':',
28                  timeout_ms=15000, fetch_limit=1000,
29                  userid_passwd=':'):
30         """
31         :param dmaap_url: protocol, host and port; can also be a list of URLs
32                (e.g. https://dmaap-host.onapdemo.onap.org:3905/events/org.onap.dmaap.MULTICLOUD.URGENT),
33                can also be a list of such URLs
34         :param consumer_group_id: DMaaP consumer group and consumer id (':' separated)
35                consumer_group is unique for each subscriber; required for GET
36                consumer_id: DMaaP consumer ID (unique for each thread/process for a subscriber; required for GET)
37         :param timeout_ms: (optional, default 15 seconds or 15,000 ms) server-side timeout for GET request
38         :param fetch_limit: (optional, default 1000 messages per request for GET), ignored for "POST"
39         :param userid_passwd: (optional, userid:password for HTTP basic authentication)
40         """
41         mr_error = MessageBusConfigurationException
42         if not dmaap_url:  # definitely not DMaaP, so use UEB mode
43             raise mr_error("Not a valid DMaaP configuration")
44         self.topic_urls = [dmaap_url] if not list_like(dmaap_url) else dmaap_url
45         self.timeout_ms = timeout_ms
46         self.fetch_limit = fetch_limit
47         userid, passwd = userid_passwd.split(':')
48         self.auth = (userid, passwd) if userid and passwd else None
49         consumer_group, consumer_id = consumer_group_id.split(':')
50         self.consumer_group = consumer_group
51         self.consumer_id = consumer_id
52
53     def get(self, outputjson=True):
54         """Fetch messages from message router (DMaaP or UEB)
55         :param outputjson: (optional, specifies if response is expected to be in json format), ignored for "POST"
56         :return: response as a json object (if outputjson is True) or as a string
57         """
58         url_fmt = "{topic_url}/{cgroup}/{cid}?timeout={timeout_ms}&limit={limit}"
59         urls = [url_fmt.format(topic_url=x, timeout_ms=self.timeout_ms, limit=self.fetch_limit,
60                                cgroup=self.consumer_group, cid=self.consumer_id) for x in self.topic_urls]
61         for url in urls[:-1]:
62             try:
63                 return self.http_request(method='GET', url=url, outputjson=outputjson)
64             except:
65                 pass
66         return self.http_request(method='GET', url=urls[-1], outputjson=outputjson)
67
68     def post(self, msg, inputjson=True):
69         for url in self.topic_urls[:-1]:
70             try:
71                 return self.http_request(method='POST', url=url, inputjson=inputjson, msg=msg)
72             except:
73                 pass
74         return self.http_request(method='POST', url=self.topic_urls[-1], inputjson=inputjson, msg=msg)
75
76     def http_request(self, url, method, inputjson=True, outputjson=True, msg=None, **kwargs):
77         """
78         Perform the actual URL request (GET or POST), and do error handling
79         :param url: full URL (including topic, limit, timeout, etc.)
80         :param method: GET or POST
81         :param inputjson: Specify whether input is in json format (valid only for POST)
82         :param outputjson: Is response expected in a json format
83         :param msg: content to be posted (valid only for POST)
84         :return: response as a json object (if outputjson or POST) or as a string; None if error
85         """
86         res = requests.request(url=url, method=method, auth=self.auth, **kwargs)
87         if res.status_code == requests.codes.ok:
88             return res.json() if outputjson or method == "POST" else res.content
89         else:
90             raise Exception("HTTP Response Error: code {}; headers:{}, content: {}".format(
91                 res.status_code, res.headers, res.content))