1 # Copyright 2017 ZTE Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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 # See the License for the specific language governing permissions and
13 # limitations under the License.
22 logger = logging.getLogger(__name__)
26 if not os.path.exists(path):
27 os.makedirs(path, 0o777)
30 def delete_dirs(path):
32 if os.path.exists(path):
34 except Exception as e:
35 logger.error(traceback.format_exc())
36 logger.error("Failed to delete %s:%s", path, e.args[0])
39 def download_file_from_http(url, local_dir, file_name):
40 local_file_name = os.path.join(local_dir, file_name)
41 is_download_ok = False
44 req = urllib.request.urlopen(url)
45 save_file = open(local_file_name, 'w')
46 save_file.write(req.read())
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
56 def unzip_file(zip_src, dst_dir, csar_path):
57 logger.debug("unzip_file %s to %s.", zip_src, dst_dir)
58 if os.path.exists(zip_src):
59 logger.debug("unzip_file %s.", zip_src)
60 fz = zipfile.ZipFile(zip_src, 'r')
61 for file in fz.namelist():
62 fz.extract(file, dst_dir)
63 return os.path.join(dst_dir, csar_path)
68 def unzip_csar(zip_src, dst_dir):
69 if os.path.exists(zip_src):
70 fz = zipfile.ZipFile(zip_src, 'r')
71 for file in fz.namelist():
72 fz.extract(file, dst_dir)
75 logger.error("%s doesn't exist", zip_src)
79 def unzip_csar_to_tmp(zip_src):
80 dirpath = tempfile.mkdtemp()
81 zip_ref = zipfile.ZipFile(zip_src, 'r')
82 zip_ref.extractall(dirpath)
86 def get_artifact_path(vnf_path, artifact_file):
87 for root, dirs, files in os.walk(vnf_path):
88 if artifact_file in files:
89 return os.path.join(root, artifact_file)
93 def end_with(_s_in, *suffix):
94 array = map(_s_in.endswith, suffix)
100 def filter_files(search_path, suffix):
102 file_list = os.listdir(search_path)
103 for file_item in file_list:
104 if end_with(file_item, suffix):
105 f_find.append(file_item)
109 def recreate_dir(path):
110 if os.path.exists(path):
112 os.makedirs(path, mode=0o777)
115 def copy(src_file, dest_dir, new_file_name=None):
116 if not os.path.exists(dest_dir):
117 os.makedirs(dest_dir)
118 if new_file_name is None:
119 dst = os.path.join(dest_dir, os.path.basename(src_file))
121 dst = os.path.join(dest_dir, new_file_name)
122 shutil.copyfile(src_file, dst)
123 shutil.copymode(src_file, dst)