[RIFT 16413, 16414] Unittest failures fixed for utest_package, utest_publisher_dts
[osm/SO.git] / rwlaunchpad / plugins / rwlaunchpadtasklet / rift / package / cloud_init.py
1
2 #
3 # Copyright 2016 RIFT.IO Inc
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17
18 import re
19 import os.path
20
21 from . import package
22
23
24 class CloudInitExtractionError(Exception):
25 pass
26
27
28 class PackageCloudInitExtractor(object):
29 """ This class is reponsible for extracting cloud_init scripts to the correct directory
30 """
31
32 SCRIPT_REGEX = "{prefix}/?cloud_init/(?P<script_name>[^/]+)$"
33
34 def __init__(self, log):
35 self._log = log
36
37 @classmethod
38 def package_script_files(cls, package):
39 script_file_map = {}
40
41 for file_name in package.files:
42 match = re.match(
43 cls.SCRIPT_REGEX.format(prefix=package.prefix),
44 file_name,
45 )
46 if match is None:
47 continue
48
49 script_name = match.group("script_name")
50 script_file_map[script_name] = file_name
51
52 return script_file_map
53
54 def read_script(self, pkg, filename):
55 descriptor_id = pkg.descriptor_id
56 script_files = PackageCloudInitExtractor.package_script_files(pkg)
57
58 for script_name, script_file in script_files.items():
59 if script_name == filename:
60 self._log.debug("Found %s script file in package at %s", filename, script_file)
61
62 try:
63 with pkg.open(script_file) as f:
64 userdata = f.read()
65 self._log.info("cloud_init read from file %s", userdata)
66 # File contents are read in binary string, decode to regular string and return
67 return userdata.decode()
68 except package.ExtractError as e:
69 raise CloudInitExtractionError("Failed to extract script %s" % script_name) from e
70
71 # If we've reached this point but not found a matching cloud_init script,
72 # raise an Exception, since we got here only because there was supposed
73 # to be a cloud_init_file in the VDU
74 errmsg = "No cloud-init config file found in the descriptor package"
75 self._log.error(errmsg)
76 raise CloudInitExtractionError(errmsg)