Get original vendor package under the ONBOARDING_PACKAGE directory from SDC resource...
[modeling/etsicatalog.git] / catalog / 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 urllib
20 import zipfile
21
22 logger = logging.getLogger(__name__)
23
24
25 def make_dirs(path):
26     if not os.path.exists(path):
27         os.makedirs(path, 0o777)
28
29
30 def delete_dirs(path):
31     try:
32         if os.path.exists(path):
33             shutil.rmtree(path)
34     except Exception as e:
35         logger.error(traceback.format_exc())
36         logger.error("Failed to delete %s:%s", path, e.args[0])
37
38
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
42     try:
43         make_dirs(local_dir)
44         req = urllib.request.urlopen(url)
45         save_file = open(local_file_name, 'w')
46         save_file.write(req.read())
47         save_file.close()
48         req.close()
49         is_download_ok = True
50     except:
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
54
55
56 def unzip_file(zip_src, dst_dir, csar_path):
57     if os.path.exists(zip_src):
58         fz = zipfile.ZipFile(zip_src, 'r')
59         for file in fz.namelist():
60             fz.extract(file, dst_dir)
61         return os.path.join(dst_dir, csar_path)
62     else:
63         return ""
64
65
66 def unzip_csar(zip_src, dst_dir):
67     if os.path.exists(zip_src):
68         fz = zipfile.ZipFile(zip_src, 'r')
69         for file in fz.namelist():
70             fz.extract(file, dst_dir)
71         return dst_dir
72     else:
73         logger.error("%s doesn't exist", zip_src)
74         return ""
75
76
77 def unzip_csar_to_tmp(zip_src):
78     dirpath = tempfile.mkdtemp()
79     zip_ref = zipfile.ZipFile(zip_src, 'r')
80     zip_ref.extractall(dirpath)
81     return dirpath
82
83
84 def get_artifact_path(vnf_path, artifact_file):
85     for root, dirs, files in os.walk(vnf_path):
86         if artifact_file in files:
87             return os.path.join(root, artifact_file)
88     return None