Update license
[multicloud/framework.git] / multivimbroker / multivimbroker / pub / utils / fileutil.py
1 # Copyright (c) 2017 Wind River Systems, Inc.
2 # Copyright (c) 2017-2018 VMware, Inc.
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 #       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 import os
13 import shutil
14 import logging
15 import traceback
16 import urllib2
17
18 logger = logging.getLogger(__name__)
19
20
21 def make_dirs(path):
22     if not os.path.exists(path):
23         os.makedirs(path, 0777)
24
25
26 def delete_dirs(path):
27     try:
28         if os.path.exists(path):
29             shutil.rmtree(path)
30     except Exception as e:
31         logger.error(traceback.format_exc())
32         logger.error("Failed to delete %s:%s", path, e.message)
33
34
35 def download_file_from_http(url, local_dir, file_name):
36     local_file_name = os.path.join(local_dir, file_name)
37     is_download_ok = False
38     try:
39         make_dirs(local_dir)
40         r = urllib2.Request(url)
41         req = urllib2.urlopen(r)
42         save_file = open(local_file_name, 'wb')
43         save_file.write(req.read())
44         save_file.close()
45         req.close()
46         is_download_ok = True
47     except Exception:
48         logger.error(traceback.format_exc())
49         logger.error("Failed to download %s to %s.", url, local_file_name)
50     return is_download_ok, local_file_name