Setup micro-service of multivim broker
[multicloud/framework.git] / multivimbroker / multivimbroker / pub / utils / fileutil.py
1 # Copyright (c) 2017 Wind River Systems, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #       http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 import os
12 import shutil
13 import logging
14 import traceback
15 import urllib2
16
17 logger = logging.getLogger(__name__)
18
19
20 def make_dirs(path):
21     if not os.path.exists(path):
22         os.makedirs(path, 0777)
23
24
25 def delete_dirs(path):
26     try:
27         if os.path.exists(path):
28             shutil.rmtree(path)
29     except Exception as e:
30         logger.error(traceback.format_exc())
31         logger.error("Failed to delete %s:%s", path, e.message)
32
33
34 def download_file_from_http(url, local_dir, file_name):
35     local_file_name = os.path.join(local_dir, file_name)
36     is_download_ok = False
37     try:
38         make_dirs(local_dir)
39         r = urllib2.Request(url)
40         req = urllib2.urlopen(r)
41         save_file = open(local_file_name, 'wb')
42         save_file.write(req.read())
43         save_file.close()
44         req.close()
45         is_download_ok = True
46     except:
47         logger.error(traceback.format_exc())
48         logger.error("Failed to download %s to %s.", url, local_file_name)
49     return is_download_ok, local_file_name