/
base.rb
275 lines (244 loc) · 9.47 KB
/
base.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#
# Author:: Fletcher Nichol (<fnichol@nichol.ca>)
#
# Copyright (C) 2013, Fletcher Nichol
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative "../configurable"
require_relative "../errors"
require_relative "../logging"
require_relative "../plugin_base"
module Kitchen
module Provisioner
# Base class for a provisioner.
#
# @author Fletcher Nichol <fnichol@nichol.ca>
class Base < Kitchen::Plugin::Base
include Configurable
include Logging
default_config :http_proxy, nil
default_config :https_proxy, nil
default_config :ftp_proxy, nil
default_config :retry_on_exit_code, []
default_config :max_retries, 1
default_config :wait_for_retry, 30
default_config :root_path do |provisioner|
provisioner.windows_os? ? '$env:TEMP\\kitchen' : "/tmp/kitchen"
end
default_config :sudo do |provisioner|
provisioner.windows_os? ? nil : true
end
default_config :sudo_command do |provisioner|
provisioner.windows_os? ? nil : "sudo -E"
end
default_config :command_prefix, nil
default_config :uploads, {}
default_config :downloads, {}
expand_path_for :test_base_path
# Constructs a new provisioner by providing a configuration hash.
#
# @param config [Hash] initial provided configuration
def initialize(config = {})
init_config(config)
end
# Runs the provisioner on the instance.
#
# @param state [Hash] mutable instance state
# @raise [ActionFailed] if the action could not be completed
# rubocop:disable Metrics/AbcSize
def call(state)
create_sandbox
instance.transport.connection(state) do |conn|
config[:uploads].to_h.each do |locals, remote|
debug("Uploading #{Array(locals).join(", ")} to #{remote}")
conn.upload(locals.to_s, remote)
end
conn.execute(install_command)
conn.execute(init_command)
info("Transferring files to #{instance.to_str}")
conn.upload(sandbox_dirs, config[:root_path])
debug("Transfer complete")
conn.execute(prepare_command)
conn.execute_with_retry(
run_command,
config[:retry_on_exit_code],
config[:max_retries],
config[:wait_for_retry]
)
info("Downloading files from #{instance.to_str}")
config[:downloads].to_h.each do |remotes, local|
debug("Downloading #{Array(remotes).join(", ")} to #{local}")
conn.download(remotes, local)
end
debug("Download complete")
end
rescue Kitchen::Transport::TransportFailed => ex
raise ActionFailed, ex.message
ensure
cleanup_sandbox
end
# Check system and configuration for common errors.
#
# @param state [Hash] mutable instance state
# @returns [Boolean] Return true if a problem is found.
def doctor(state)
false
end
# Certain products that Test Kitchen uses to provision require accepting
# a license to use. Overwrite this method in the specific provisioner
# to implement this check.
def check_license; end
# Generates a command string which will install and configure the
# provisioner software on an instance. If no work is required, then `nil`
# will be returned.
#
# @return [String] a command string
def install_command; end
# Generates a command string which will perform any data initialization
# or configuration required after the provisioner software is installed
# but before the sandbox has been transferred to the instance. If no work
# is required, then `nil` will be returned.
#
# @return [String] a command string
def init_command; end
# Generates a command string which will perform any commands or
# configuration required just before the main provisioner run command but
# after the sandbox has been transferred to the instance. If no work is
# required, then `nil` will be returned.
#
# @return [String] a command string
def prepare_command; end
# Generates a command string which will invoke the main provisioner
# command on the prepared instance. If no work is required, then `nil`
# will be returned.
#
# @return [String] a command string
def run_command; end
# Creates a temporary directory on the local workstation into which
# provisioner related files and directories can be copied or created. The
# contents of this directory will be copied over to the instance before
# invoking the provisioner's run command. After this method completes, it
# is expected that the contents of the sandbox is complete and ready for
# copy to the remote instance.
#
# **Note:** any subclasses would be well advised to call super first when
# overriding this method, for example:
#
# @example overriding `#create_sandbox`
#
# class MyProvisioner < Kitchen::Provisioner::Base
# def create_sandbox
# super
# # any further file copies, preparations, etc.
# end
# end
def create_sandbox
@sandbox_path = Dir.mktmpdir("#{instance.name}-sandbox-")
File.chmod(0755, sandbox_path)
info("Preparing files for transfer")
debug("Creating local sandbox in #{sandbox_path}")
end
# Returns the absolute path to the sandbox directory or raises an
# exception if `#create_sandbox` has not yet been called.
#
# @return [String] the absolute path to the sandbox directory
# @raise [ClientError] if the sandbox directory has no yet been created
# by calling `#create_sandbox`
def sandbox_path
@sandbox_path ||= raise ClientError, "Sandbox directory has not yet " \
"been created. Please run #{self.class}#create_sandox before " \
"trying to access the path."
end
# Returns the list of items in the sandbox directory
#
# @return [String] path of items in the sandbox directory
def sandbox_dirs
Util.list_directory(sandbox_path)
end
# Deletes the sandbox path. Without calling this method, the sandbox path
# will persist after the process terminates. In other words, cleanup is
# explicit. This method is safe to call multiple times.
def cleanup_sandbox
return if sandbox_path.nil?
debug("Cleaning up local sandbox in #{sandbox_path}")
FileUtils.rmtree(sandbox_path)
end
# Sets the API version for this provisioner. If the provisioner does not
# set this value, then `nil` will be used and reported.
#
# Sets the API version for this provisioner
#
# @example setting an API version
#
# module Kitchen
# module Provisioner
# class NewProvisioner < Kitchen::Provisioner::Base
#
# kitchen_provisioner_api_version 2
#
# end
# end
# end
#
# @param version [Integer,String] a version number
#
def self.kitchen_provisioner_api_version(version)
@api_version = version
end
private
# Builds a complete command given a variables String preamble and a file
# containing shell code.
#
# @param vars [String] shell variables, as a String
# @param file [String] file basename (without extension) containing
# shell code
# @return [String] command
# @api private
def shell_code_from_file(vars, file)
src_file = File.join(
File.dirname(__FILE__),
%w{.. .. .. support},
file + (powershell_shell? ? ".ps1" : ".sh")
)
wrap_shell_code([vars, "", IO.read(src_file)].join("\n"))
end
# Conditionally prefixes a command with a sudo command.
#
# @param command [String] command to be prefixed
# @return [String] the command, conditionally prefixed with sudo
# @api private
def sudo(script)
"#{sudo_command} #{script}".lstrip
end
# Returns the sudo command to use or empty string if sudo is not configured
#
# @return [String] the sudo command if sudo config is true
# @api private
def sudo_command
config[:sudo] ? config[:sudo_command].to_s : ""
end
# Conditionally prefixes a command with a command prefix.
# This should generally be done after a command has been
# conditionally prefixed by #sudo as certain platforms, such as
# Cisco Nexus, require all commands to be run with a prefix to
# obtain outbound network access.
#
# @param command [String] command to be prefixed
# @return [String] the command, conditionally prefixed with the configured prefix
# @api private
def prefix_command(script)
config[:command_prefix] ? "#{config[:command_prefix]} #{script}" : script
end
end
end
end