1 # Copyright (c) 2019, CMCC Technologies. Co., Ltd.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
20 from hashlib import sha1
24 from catalog.pub.Dmaap_lib.pub.exceptions import DmaapClientException
26 requests.packages.urllib3.disable_warnings()
27 logger = logging.getLogger(__name__)
31 def __init__(self, base_url, topic, consumer_group, consumer_id, timeout_ms=-1, limit=-1, filter=''):
32 self.base_url = base_url
34 self.group = consumer_group
35 self.comsumer_id = consumer_id
36 self.timeout_ms = timeout_ms
40 def set_api_credentials(self, api_key, api_secret):
41 self.api_key = api_key
42 self.api_secret = api_secret
45 url = self.base_url + "/events/%s/%s/%s" % (self.topic, self.group, self.comsumer_id)
47 if self.timeout_ms > -1:
48 add_url += "timeout=%s" % self.timeout_ms
52 add_url += "limit=%s" % self.limit
56 add_url += "filter=%s" % self.filter.encode("utf-8")
58 url = url + "?" + add_url
62 def create_headers(self):
63 data = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + '-04:00'
64 hmac_code = hmac.new(self.api_secret.encode(), data.encode(), sha1).digest()
65 signature = base64.b64encode(hmac_code).decode()
66 auth = self.api_key + ':' + signature
68 'X-CambriaDate': data,
76 url = self.create_url()
78 headers = self.create_headers()
79 ret = requests.get(url=url, headers=headers, verify=False)
81 ret = requests.get(url)
82 logger.info("Status code is %s, detail is %s.", ret.status_code, ret.json())
83 if ret.status_code != 200:
84 raise DmaapClientException(
85 'Call dmaap failed. Status code is %s, detail is %s.' % (ret.status_code, ret.json()))
91 except Exception as e:
92 raise DmaapClientException(e.message)