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 logger = logging.getLogger(__name__)
30 def __init__(self, base_url, topic, consumer_group, consumer_id, timeout_ms=-1, limit=-1, filter=''):
31 self.base_url = base_url
33 self.group = consumer_group
34 self.comsumer_id = consumer_id
35 self.timeout_ms = timeout_ms
39 def set_api_credentials(self, api_key, api_secret):
40 self.api_key = api_key
41 self.api_secret = api_secret
44 url = self.base_url + "/events/%s/%s/%s" % (self.topic, self.group, self.comsumer_id)
46 if self.timeout_ms > -1:
47 add_url += "timeout=%s" % self.timeout_ms
51 add_url += "limit=%s" % self.limit
55 add_url += "filter=%s" % self.filter.encode("utf-8")
57 url = url + "?" + add_url
61 def create_headers(self):
62 data = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S') + '-04:00'
63 hmac_code = hmac.new(self.api_secret.encode(), data.encode(), sha1).digest()
64 signature = base64.b64encode(hmac_code).decode()
65 auth = self.api_key + ':' + signature
67 'X-CambriaDate': data,
75 url = self.create_url()
77 headers = self.create_headers()
78 ret = requests.get(url=url, headers=headers)
80 ret = requests.get(url)
81 logger.info("Status code is %s, detail is %s.", ret.status_code, ret.json())
82 if ret.status_code != 200:
83 raise DmaapClientException(
84 'Call dmaap failed. Status code is %s, detail is %s.' % (ret.status_code, ret.json()))
90 except Exception as e:
91 raise DmaapClientException(e.message)