Changed credentials for deploying heat templates.
[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 the path is a directory
36     :return:
37     """
38     if os.path.exists(file_path):
39         if os.path.isdir(file_path):
40             return False
41         return os.path.isfile(file_path)
42     return False
43
44
45 def download(url, dest_path, name=None):
46     """
47     Download a file to a destination path given a URL
48     :param url: the endpoint to the file to download
49     :param dest_path: the directory to save the file
50     :param name: the file name (optional)
51     :rtype : File object
52     """
53     if not name:
54         name = url.rsplit('/')[-1]
55     dest = dest_path + '/' + name
56     logger.debug('Downloading file from - ' + url)
57     # Override proxy settings to use localhost to download file
58     f = None
59
60     if not os.path.isdir(dest_path):
61         try:
62             os.mkdir(dest_path)
63         except:
64             raise
65     try:
66         with open(dest, 'wb') as f:
67             logger.debug('Saving file to - ' + os.path.abspath(f.name))
68             response = __get_url_response(url)
69             f.write(response.read())
70         return f
71     finally:
72         if f:
73             f.close()
74
75
76 def get_content_length(url):
77     """
78     Returns the number of bytes to be downloaded from the given URL
79     :param url: the URL to inspect
80     :return: the number of bytes
81     """
82     response = __get_url_response(url)
83     return response.headers['Content-Length']
84
85
86 def __get_url_response(url):
87     """
88     Returns a response object for a given URL
89     :param url: the URL
90     :return: the response
91     """
92     proxy_handler = urllib.ProxyHandler({})
93     opener = urllib.build_opener(proxy_handler)
94     urllib.install_opener(opener)
95     return urllib.urlopen(url)
96
97
98 def read_yaml(config_file_path):
99     """
100     Reads the yaml file and returns a dictionary object representation
101     :param config_file_path: The file path to config
102     :return: a dictionary
103     """
104     logger.debug('Attempting to load configuration file - ' + config_file_path)
105     with open(config_file_path) as config_file:
106         config = yaml.safe_load(config_file)
107         logger.info('Loaded configuration')
108     config_file.close()
109     logger.info('Closing configuration file')
110     return config
111
112
113 def read_os_env_file(os_env_filename):
114     """
115     Reads the OS environment source file and returns a map of each key/value
116     Will ignore lines beginning with a '#' and will replace any single or double quotes contained within the value
117     :param os_env_filename: The name of the OS environment file to read
118     :return: a dictionary
119     """
120     if os_env_filename:
121         logger.info('Attempting to read OS environment file - ' + os_env_filename)
122         out = {}
123         for line in open(os_env_filename):
124             line = line.lstrip()
125             if not line.startswith('#') and line.startswith('export '):
126                 line = line.lstrip('export ').strip()
127                 tokens = line.split('=')
128                 if len(tokens) > 1:
129                     # Remove leading and trailing ' & " characters from value
130                     out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
131         return out
132
133
134 def read_file(filename):
135     """
136     Returns the contents of a file as a string
137     :param filename: the name of the file
138     :return:
139     """
140     out = str()
141     for line in open(filename):
142         out += line
143
144     return out