genericparser seed code
[modeling/etsicatalog.git] / genericparser / pub / utils / fileutil.py
1 # Copyright 2017 ZTE Corporation.
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 #
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 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import os
15 import shutil
16 import logging
17 import tempfile
18 import traceback
19 import urllib2
20 import zipfile
21
22
23 logger = logging.getLogger(__name__)
24
25
26 def make_dirs(path):
27     if not os.path.exists(path):
28         os.makedirs(path, 0777)
29
30
31 def delete_dirs(path):
32     try:
33         if os.path.exists(path):
34             shutil.rmtree(path)
35     except Exception as e:
36         logger.error(traceback.format_exc())
37         logger.error("Failed to delete %s:%s", path, e.message)
38
39
40 def download_file_from_http(url, local_dir, file_name):
41     local_file_name = os.path.join(local_dir, file_name)
42     is_download_ok = False
43     try:
44         make_dirs(local_dir)
45         r = urllib2.Request(url)
46         req = urllib2.urlopen(r)
47         save_file = open(local_file_name, 'wb')
48         save_file.write(req.read())
49         save_file.close()
50         req.close()
51         is_download_ok = True
52     except:
53         logger.error(traceback.format_exc())
54         logger.error("Failed to download %s to %s.", url, local_file_name)
55     return is_download_ok, local_file_name
56
57
58 def unzip_file(zip_src, dst_dir, csar_path):
59     if os.path.exists(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)
64     else:
65         return ""
66
67
68 def unzip_csar_to_tmp(zip_src):
69     dirpath = tempfile.mkdtemp()
70     zip_ref = zipfile.ZipFile(zip_src, 'r')
71     zip_ref.extractall(dirpath)
72     return dirpath
73
74
75 def get_artifact_path(vnf_path, artifact_file):
76     for root, dirs, files in os.walk(vnf_path):
77         if artifact_file in files:
78             return os.path.join(root, artifact_file)
79     return None