Avoid checking Keystone v3 domains when using API v2.0
[snaps.git] / snaps / file_utils.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
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 import os
16 import logging
17 try:
18     import urllib.request as urllib
19 except ImportError:
20     import urllib2 as urllib
21
22 import yaml
23
24 __author__ = 'spisarski'
25
26 """
27 Utilities for basic file handling
28 """
29
30 logger = logging.getLogger('file_utils')
31
32
33 def file_exists(file_path):
34     """
35     Returns True if the image file already exists and throws an exception if
36     the path is a directory
37     :return:
38     """
39     if os.path.exists(file_path):
40         if os.path.isdir(file_path):
41             return False
42         return os.path.isfile(file_path)
43     return False
44
45
46 def download(url, dest_path, name=None):
47     """
48     Download a file to a destination path given a URL
49     :param url: the endpoint to the file to download
50     :param dest_path: the directory to save the file
51     :param name: the file name (optional)
52     :rtype : File object
53     """
54     if not name:
55         name = url.rsplit('/')[-1]
56     dest = dest_path + '/' + name
57     logger.debug('Downloading file from - ' + url)
58     # Override proxy settings to use localhost to download file
59     download_file = None
60
61     if not os.path.isdir(dest_path):
62         try:
63             os.mkdir(dest_path)
64         except:
65             raise
66     try:
67         with open(dest, 'wb') as download_file:
68             logger.debug('Saving file to - ' + os.path.abspath(download_file.name))
69             response = __get_url_response(url)
70             download_file.write(response.read())
71         return download_file
72     finally:
73         if download_file:
74             download_file.close()
75
76
77 def get_content_length(url):
78     """
79     Returns the number of bytes to be downloaded from the given URL
80     :param url: the URL to inspect
81     :return: the number of bytes
82     """
83     response = __get_url_response(url)
84     return response.headers['Content-Length']
85
86
87 def __get_url_response(url):
88     """
89     Returns a response object for a given URL
90     :param url: the URL
91     :return: the response
92     """
93     proxy_handler = urllib.ProxyHandler({})
94     opener = urllib.build_opener(proxy_handler)
95     urllib.install_opener(opener)
96     return urllib.urlopen(url)
97
98
99 def read_yaml(config_file_path):
100     """
101     Reads the yaml file and returns a dictionary object representation
102     :param config_file_path: The file path to config
103     :return: a dictionary
104     """
105     logger.debug('Attempting to load configuration file - ' + config_file_path)
106     config_file = None
107     try:
108         with open(config_file_path) as config_file:
109             config = yaml.safe_load(config_file)
110             logger.info('Loaded configuration')
111         return config
112     finally:
113         if config_file:
114             logger.info('Closing configuration file')
115             config_file.close()
116
117
118 def read_os_env_file(os_env_filename):
119     """
120     Reads the OS environment source file and returns a map of each key/value
121     Will ignore lines beginning with a '#' and will replace any single or
122     double quotes contained within the value
123     :param os_env_filename: The name of the OS environment file to read
124     :return: a dictionary
125     """
126     if os_env_filename:
127         logger.info('Attempting to read OS environment file - %s',
128                     os_env_filename)
129         out = {}
130         env_file = None
131         try:
132             env_file = open(os_env_filename)
133             for line in env_file:
134                 line = line.lstrip()
135                 if not line.startswith('#') and line.startswith('export '):
136                     line = line.lstrip('export ').strip()
137                     tokens = line.split('=')
138                     if len(tokens) > 1:
139                         # Remove leading and trailing ' & " characters from
140                         # value
141                         out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
142         finally:
143             if env_file:
144                 env_file.close()
145         return out
146
147
148 def read_file(filename):
149     """
150     Returns the contents of a file as a string
151     :param filename: the name of the file
152     :return:
153     """
154     out = str()
155     the_file = None
156     try:
157         the_file = open(filename)
158         for line in the_file:
159             out += line
160         return out
161     finally:
162         if the_file:
163             the_file.close()