Update odltools
[netvirt.git] / resources / tools / odltools / odltools / mdsal / request.py
1 # Copyright 2018 Red Hat, Inc. and others. All Rights Reserved.
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 errno
16 import json
17 import logging
18 import os
19 import requests
20
21 logger = logging.getLogger("mdsal.request")
22
23
24 def debug_print(fname, text1, data):
25     logger.debug("%s: request: %s: processed %d lines", fname, text1, len(data))
26     # logger.debug("%s:\n%s", fname, json.dumps(data))
27     logger.debug("%s:\n%s", fname, json.dumps(data, indent=4, separators=(',', ': ')))
28
29
30 def get(url, user, pw):
31     try:
32         resp = requests.get(url, auth=(user, pw))
33     except requests.exceptions.RequestException:
34         logger.exception("Failed to get url %s", url)
35         return None
36
37     try:
38         data = resp.json()
39     except ValueError:
40         logger.exception("Failed to get url %s", url)
41         return None
42
43     if logger.isEnabledFor(logging.DEBUG):
44         debug_print("get", url, data)
45     return data
46
47
48 def read_file(filename):
49     if os.path.isfile(filename) is False:
50         return None
51
52     with open(filename) as json_file:
53         data = json.load(json_file)
54     if logger.isEnabledFor(logging.DEBUG):
55         debug_print("read_file", filename, data)
56     return data
57
58
59 def write_file(filename, data, pretty_print=False):
60     try:
61         os.makedirs(os.path.dirname(filename))
62     except OSError as exception:
63         if exception.errno != errno.EEXIST:
64             raise
65
66     with open(filename, 'w') as fp:
67         if pretty_print:
68             json.dump(data, fp, indent=4, separators=(',', ': '))
69         else:
70             json.dump(data, fp)
71     if logger.isEnabledFor(logging.DEBUG):
72         debug_print("write_file", filename, data)