Rebase framework to py36
[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 import urllib.request
18 import urllib.parse
19 import urllib.error
20
21 logger = logging.getLogger(__name__)
22
23
24 def make_dirs(path):
25     if not os.path.exists(path):
26         os.makedirs(path, 0o777)
27
28
29 def delete_dirs(path):
30     try:
31         if os.path.exists(path):
32             shutil.rmtree(path)
33     except Exception as e:
34         logger.error(traceback.format_exc())
35         logger.error("Failed to delete %s:%s", path, e)
36
37
38 def download_file_from_http(url, local_dir, file_name):
39     local_file_name = os.path.join(local_dir, file_name)
40     is_download_ok = False
41     try:
42         make_dirs(local_dir)
43         r = urllib.request.Request(url)
44         req = urllib.request.urlopen(r)
45         save_file = open(local_file_name, 'wb')
46         save_file.write(req.read())
47         save_file.close()
48         req.close()
49         is_download_ok = True
50     except Exception:
51         logger.error(traceback.format_exc())
52         logger.error("Failed to download %s to %s.", url, local_file_name)
53     return is_download_ok, local_file_name