Change notify handler to support https.
[pti/o2.git] / o2common / service / command / handler.py
1 # Copyright (C) 2022 Wind River Systems, Inc.
2 #
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
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,
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.
14
15 import http.client
16 import ssl
17 from o2common.helper import o2logging
18 from o2common.config import config
19
20 logger = o2logging.get_logger(__name__)
21
22
23 def post_data(conn, path, data):
24     headers = {'Content-type': 'application/json'}
25     conn.request('POST', path, data, headers)
26     resp = conn.getresponse()
27     data = resp.read().decode('utf-8')
28     # json_data = json.loads(data)
29     if resp.status >= 200 and resp.status <= 299:
30         logger.info('Post data to SMO successed, response code {} {}, data {}'.
31                     format(resp.status, resp.reason, data))
32         return True, resp.status
33     logger.error('Response code is: {}'.format(resp.status))
34     return False, resp.status
35
36
37 def get_http_conn(callbackurl):
38     conn = http.client.HTTPConnection(callbackurl)
39     return conn
40
41
42 # with default CA
43 def get_https_conn_default(callbackurl):
44     sslctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
45     sslctx.check_hostname = True
46     sslctx.verify_mode = ssl.CERT_REQUIRED
47     sslctx.load_default_certs()
48     conn = http.client.HTTPSConnection(callbackurl, context=sslctx)
49     return conn
50
51
52 # with self signed ca
53 def get_https_conn_selfsigned(callbackurl):
54     sslctx = ssl.create_default_context(
55         purpose=ssl.Purpose.SERVER_AUTH)
56     smo_ca_path = config.get_smo_ca_config_path()
57     sslctx.load_verify_locations(smo_ca_path)
58     sslctx.check_hostname = False
59     sslctx.verify_mode = ssl.CERT_REQUIRED
60     conn = http.client.HTTPSConnection(callbackurl, context=sslctx)
61     return conn