Fixed test for security groups when checking for project/tenant ID
[snaps.git] / snaps / file_utils.py
1 # Copyright (c) 2016 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 urllib2
17 import logging
18
19 import yaml
20
21 __author__ = 'spisarski'
22
23 """
24 Utilities for basic file handling
25 """
26
27 logger = logging.getLogger('file_utils')
28
29
30 def file_exists(file_path):
31     """
32     Returns True if the image file already exists and throws an exception if the path is a directory
33     :return:
34     """
35     if os.path.exists(file_path):
36         if os.path.isdir(file_path):
37             return False
38         return os.path.isfile(file_path)
39     return False
40
41
42 def get_file(file_path):
43     """
44     Returns True if the image file has already been downloaded
45     :return: the image file object
46     :raise Exception when file cannot be found
47     """
48     if file_exists(file_path):
49         return open(file_path, 'r')
50     else:
51         raise Exception('File with path cannot be found - ' + file_path)
52
53
54 def download(url, dest_path):
55     """
56     Download a file to a destination path given a URL
57     :rtype : File object
58     """
59     name = url.rsplit('/')[-1]
60     dest = dest_path + '/' + name
61     try:
62         # Override proxy settings to use localhost to download file
63         proxy_handler = urllib2.ProxyHandler({})
64         opener = urllib2.build_opener(proxy_handler)
65         urllib2.install_opener(opener)
66         response = urllib2.urlopen(url)
67     except (urllib2.HTTPError, urllib2.URLError):
68         raise Exception
69
70     with open(dest, 'wb') as f:
71         f.write(response.read())
72     return f
73
74
75 def read_yaml(config_file_path):
76     """
77     Reads the yaml file and returns a dictionary object representation
78     :param config_file_path: The file path to config
79     :return: a dictionary
80     """
81     logger.debug('Attempting to load configuration file - ' + config_file_path)
82     with open(config_file_path) as config_file:
83         config = yaml.safe_load(config_file)
84         logger.info('Loaded configuration')
85     config_file.close()
86     logger.info('Closing configuration file')
87     return config
88
89
90 def read_os_env_file(os_env_filename):
91     """
92     Reads the OS environment source file and returns a map of each key/value
93     Will ignore lines beginning with a '#' and will replace any single or double quotes contained within the value
94     :param os_env_filename: The name of the OS environment file to read
95     :return: a dictionary
96     """
97     if os_env_filename:
98         logger.info('Attempting to read OS environment file - ' + os_env_filename)
99         out = {}
100         for line in open(os_env_filename):
101             line = line.lstrip()
102             if not line.startswith('#') and line.startswith('export '):
103                 line = line.lstrip('export ').strip()
104                 tokens = line.split('=')
105                 if len(tokens) > 1:
106                     # Remove leading and trailing ' & " characters from value
107                     out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')
108         return out