3 # Copyright 2016 RIFT.IO Inc
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
24 class CloudInitExtractionError(Exception):
28 class PackageCloudInitExtractor(object):
29 """ This class is reponsible for extracting cloud_init scripts to the correct directory
32 SCRIPT_REGEX
= "{prefix}/?cloud_init/(?P<script_name>[^/]+)$"
34 def __init__(self
, log
):
38 def package_script_files(cls
, package
):
41 for file_name
in package
.files
:
43 cls
.SCRIPT_REGEX
.format(prefix
=package
.prefix
),
49 script_name
= match
.group("script_name")
50 script_file_map
[script_name
] = file_name
52 return script_file_map
54 def read_script(self
, pkg
, filename
):
55 descriptor_id
= pkg
.descriptor_id
56 script_files
= PackageCloudInitExtractor
.package_script_files(pkg
)
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
)
63 with pkg
.open(script_file
) as f
:
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
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
)