Class: OpenStackTaster
- Inherits:
-
Object
- Object
- OpenStackTaster
- Defined in:
- lib/openstack_taster.rb
Constant Summary collapse
- INSTANCE_FLAVOR_NAME =
'm1.tiny'- INSTANCE_NETWORK_NAME =
'public'- INSTANCE_NAME_PREFIX =
'taster'- INSTANCE_VOLUME_MOUNT_POINT =
'/mnt/taster_volume'- VOLUME_TEST_FILE_NAME =
'info'- VOLUME_TEST_FILE_CONTENTS =
Contents would be something like ‘test-vol-1 on openpower8.osuosl.bak’
nil- TIMEOUT_INSTANCE_CREATE =
20- TIMEOUT_VOLUME_ATTACH =
10- TIMEOUT_VOLUME_PERSIST =
20- TIMEOUT_INSTANCE_TO_BE_CREATED =
20- TIMEOUT_INSTANCE_STARTUP =
30- TIMEOUT_SSH_RETRY =
15- MAX_SSH_RETRY =
3- TIME_SLUG_FORMAT =
'%Y%m%d_%H%M%S'
Instance Method Summary collapse
-
#create_image(instance) ⇒ Fog::Image::OpenStack::Image
Create an image of an instance.
-
#error_log(logger, level, message, dup_stdout = false, context = nil) ⇒ Object
Write an error message to the log and optionally stdout.
-
#get_image_name(instance) ⇒ String
Get the name of the image from which an instance was created.
-
#initialize(compute_service, volume_service, image_service, network_service, ssh_keys, log_dir) ⇒ OpenStackTaster
constructor
A new instance of OpenStackTaster.
-
#log_partitions(instance, username) ⇒ Object
Log instance’s partition listing.
-
#taste(image_name, settings) ⇒ Boolean
Taste a specified image.
-
#taste_security(instance, username) ⇒ Boolean
Runs the security test suite using inspec.
-
#taste_volumes(instance, username) ⇒ Boolean
Run the set of tests for each available volume on an instance.
-
#volume_attach?(instance, volume) ⇒ Boolean
Test volume attachment for a given instance and volume.
-
#volume_detach?(instance, volume) ⇒ Boolean
Detach volume from instance.
-
#volume_mount_unmount?(instance, username, volume) ⇒ Boolean
Test volume mounting and unmounting for an instance and a volume.
-
#with_ssh(instance, username, &block) ⇒ Object
A helper method to execute a series of commands remotely on an instance.
Constructor Details
#initialize(compute_service, volume_service, image_service, network_service, ssh_keys, log_dir) ⇒ OpenStackTaster
Returns a new instance of OpenStackTaster.
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 |
# File 'lib/openstack_taster.rb', line 30 def initialize( compute_service, volume_service, image_service, network_service, ssh_keys, log_dir ) @compute_service = compute_service @volume_service = volume_service @image_service = image_service @network_service = network_service @volumes = @volume_service.volumes @ssh_keypair = ssh_keys[:keypair] @ssh_private_key = ssh_keys[:private_key] @ssh_public_key = ssh_keys[:public_key] # REVIEW @session_id = object_id @log_dir = log_dir + "/#{@session_id}" @instance_flavor = @compute_service.flavors .select { |flavor| flavor.name == INSTANCE_FLAVOR_NAME }.first @instance_network = @network_service.networks .select { |network| network.name == INSTANCE_NETWORK_NAME }.first end |
Instance Method Details
#create_image(instance) ⇒ Fog::Image::OpenStack::Image
This method blocks until snapshot creation is complete on the server.
Create an image of an instance.
235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/openstack_taster.rb', line 235 def create_image(instance) image_name = [ instance.name, get_image_name(instance) ].join('_') response = instance.create_image(image_name) image_id = response.body['image']['id'] @image_service.images .find_by_id(image_id) .wait_for { status == 'active' } end |
#error_log(logger, level, message, dup_stdout = false, context = nil) ⇒ Object
Write an error message to the log and optionally stdout.
208 209 210 211 212 213 214 215 216 217 218 219 220 |
# File 'lib/openstack_taster.rb', line 208 def error_log(logger, level, , dup_stdout = false, context = nil) puts if dup_stdout begin logger.add(Logger.const_get(level.upcase), , context) rescue NameError puts puts "\e[31m#{level} is not a severity. Make sure that you use the correct string for logging severity!\e[0m" puts logger.error('Taster Source Code') { "#{level} is not a logging severity name. Defaulting to INFO." } logger.info(context) { } end end |
#get_image_name(instance) ⇒ String
Get the name of the image from which an instance was created.
225 226 227 228 229 |
# File 'lib/openstack_taster.rb', line 225 def get_image_name(instance) @image_service .get_image_by_id(instance.image['id']) .body['name'] end |
#log_partitions(instance, username) ⇒ Object
Log instance’s partition listing.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 |
# File 'lib/openstack_taster.rb', line 404 def log_partitions(instance, username) puts 'Logging partition list and dmesg...' record_info_commands = [ 'cat /proc/partitions', 'dmesg | tail -n 20' ] with_ssh(instance, username) do |ssh| record_info_commands.each do |command| result = ssh.exec!(command) error_log(instance.logger, 'info', "Ran '#{command}' and got '#{result}'") end end end |
#taste(image_name, settings) ⇒ Boolean
Reduce Percieved and Cyclomatic complexity
Images over compute service is deprecated
The testing section could be further streamlined by: creating a naming standard for test functions (i.e. taste_<name>) limiting the parameters of each test to be: instance, distro_username Adding a ‘suites’ subhash to the settings hash Then that subhash can be iterated over, use eval to call each function, appending the suite name to ‘taste_’ for the function name and passing the standardized parameters
Taste a specified image
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 |
# File 'lib/openstack_taster.rb', line 71 def taste(image_name, settings) image = @compute_service.images .select { |i| i.name == image_name }.first abort("#{image_name} is not an available image.") if image.nil? distro_user_name = image.name.downcase.gsub(/[^a-z].*$/, '') # truncate downcased name at first non-alpha char distro_arch = image.name.downcase.slice(-2, 2) instance_name = format( '%s-%s-%s-%s', INSTANCE_NAME_PREFIX, Time.new.strftime(TIME_SLUG_FORMAT), distro_user_name, distro_arch ) FileUtils.mkdir_p(@log_dir) unless Dir.exist?(@log_dir) instance_logger = Logger.new("#{@log_dir}/#{instance_name}.log") error_log( instance_logger, 'info', "Tasting #{image.name} as '#{instance_name}' with username '#{distro_user_name}'.\nBuilding...", true ) instance = @compute_service.servers.create( name: instance_name, flavor_ref: @instance_flavor.id, image_ref: image.id, nics: [{ net_id: @instance_network.id }], key_name: @ssh_keypair ) if instance.nil? error_log(instance_logger, 'error', 'Failed to create instance.', true) return false end instance.class.send(:attr_accessor, 'logger') instance.logger = instance_logger instance.wait_for(TIMEOUT_INSTANCE_TO_BE_CREATED) { ready? } error_log(instance.logger, 'info', "Sleeping #{TIMEOUT_INSTANCE_STARTUP} seconds for OS startup...", true) sleep TIMEOUT_INSTANCE_STARTUP error_log(instance.logger, 'info', "Testing for instance '#{instance.id}'.", true) # Run tests return_values = [] return_values.push taste_security(instance, distro_user_name) if settings[:security] return_values.push taste_volumes(instance, distro_user_name) if settings[:volumes] if settings[:create_snapshot] && !return_values.all? error_log(instance.logger, 'info', "Tests failed for instance '#{instance.id}'. Creating image...", true) create_image(instance) # Create image here since it is destroyed before scope returns to taste function end return return_values.all? rescue Fog::Errors::TimeoutError puts 'Instance creation timed out.' error_log(instance.logger, 'error', "Instance fault: #{instance.fault}") return false rescue Interrupt puts "\nCaught interrupt" puts "Exiting session #{@session_id}" raise ensure if instance puts "Destroying instance for session #{@session_id}.\n\n" instance.destroy end end |
#taste_security(instance, username) ⇒ Boolean
Don’t crash when connection refused.
Runs the security test suite using inspec
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 |
# File 'lib/openstack_taster.rb', line 152 def taste_security(instance, username) opts = { 'backend' => 'ssh', 'host' => instance.addresses['public'].first['addr'], 'port' => 22, 'user' => username, 'sudo' => true, 'keys_only' => true, 'key_files' => @ssh_private_key, 'logger' => instance.logger } tries = 0 begin runner = Inspec::Runner.new(opts) runner.add_target(File.dirname(__FILE__) + '/../tests') runner.run rescue RuntimeError => e puts "Encountered error \"#{e.message}\" while testing the instance." if tries < MAX_SSH_RETRY tries += 1 puts "Initiating SSH attempt #{tries} in #{TIMEOUT_SSH_RETRY} seconds" sleep TIMEOUT_SSH_RETRY retry end error_log(instance.logger, 'error', e.backtrace, false, 'Inspec Runner') error_log(instance.logger, 'error', e., false, 'Inspec Runner') return true rescue StandardError => e puts "Encountered error \"#{e.message}\". Aborting test." return true end error_log( instance.logger, 'info', "Inspec Test Results\n" + runner.report[:controls].map do |test| "#{test[:status].upcase}: #{test[:code_desc]}\n#{test[:message]}" end.join("\n") ) if runner.report[:controls].any? { |test| test[:status] == 'failed' } error_log(instance.logger, 'warn', 'Image failed security test suite') return false end true end |
#taste_volumes(instance, username) ⇒ Boolean
Run the set of tests for each available volume on an instance.
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 |
# File 'lib/openstack_taster.rb', line 253 def taste_volumes(instance, username) mount_failures = @volumes.reject do |volume| if volume..any? error_log(instance.logger, 'info', "Volume '#{volume.name}' is already in an attached state; skipping.", true) next end unless volume_attach?(instance, volume) error_log(instance.logger, 'error', "Volume '#{volume.name}' failed to attach.", true) next end volume_mount_unmount?(instance, username, volume) end detach_failures = @volumes.reject do |volume| volume_detach?(instance, volume) end if mount_failures.empty? && detach_failures.empty? error_log(instance.logger, 'info', "\nEncountered 0 failures.", true) true else error_log( instance.logger, 'error', "\nEncountered #{mount_failures.count} mount failures and #{detach_failures.count} detach failures.", true ) error_log(instance.logger, 'error', "\nEncountered failures.", true) false end end |
#volume_attach?(instance, volume) ⇒ Boolean
Test volume attachment for a given instance and volume.
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
# File 'lib/openstack_taster.rb', line 323 def volume_attach?(instance, volume) volume_attached = lambda do |_| .any? do || ['volumeId'] == volume.id end end error_log(instance.logger, 'info', "Attaching volume '#{volume.name}' (#{volume.id})...", true) @compute_service.attach_volume(volume.id, instance.id, nil) instance.wait_for(TIMEOUT_VOLUME_ATTACH, &volume_attached) error_log(instance.logger, 'info', "Sleeping #{TIMEOUT_VOLUME_PERSIST} seconds for attachment persistance...", true) sleep TIMEOUT_VOLUME_PERSIST # In the off chance that the volume host goes down, catch it. if instance.instance_eval(&volume_attached) return true if volume.reload..first error_log(instance.logger, 'error', "Failed to attach '#{volume.name}': Volume host might be down.", true) else error_log(instance.logger, 'error', "Failed to attach '#{volume.name}': Volume was unexpectedly detached.", true) end false rescue Excon::Error => e puts 'Error attaching volume, check log for details.' error_log(instance.logger, 'error', e.) false rescue Fog::Errors::TimeoutError error_log(instance.logger, 'error', "Failed to attach '#{volume.name}': Operation timed out.", true) false end |
#volume_detach?(instance, volume) ⇒ Boolean
Detach volume from instance.
424 425 426 427 428 429 430 431 |
# File 'lib/openstack_taster.rb', line 424 def volume_detach?(instance, volume) error_log(instance.logger, 'info', "Detaching #{volume.name}.", true) instance.detach_volume(volume.id) rescue Excon::Error => e puts 'Failed to detach. check log for details.' error_log(instance.logger, 'error', e.) false end |
#volume_mount_unmount?(instance, username, volume) ⇒ Boolean
Test volume mounting and unmounting for an instance and a volume.
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# File 'lib/openstack_taster.rb', line 360 def volume_mount_unmount?(instance, username, volume) mount = INSTANCE_VOLUME_MOUNT_POINT file_name = VOLUME_TEST_FILE_NAME file_contents = VOLUME_TEST_FILE_CONTENTS vdev = @volume_service.volumes.find_by_id(volume.id) ..first['device'] vdev << '1' log_partitions(instance, username) commands = [ ["echo -e \"127.0.0.1\t$HOSTNAME\" | sudo tee -a /etc/hosts", nil], # to fix problems with sudo and DNS resolution ['sudo partprobe -s', nil], ["[ -d '#{mount}' ] || sudo mkdir #{mount}", ''], ["sudo mount #{vdev} #{mount}", ''], ["sudo cat #{mount}/#{file_name}", file_contents], ["sudo umount #{mount}", ''] ] error_log(instance.logger, 'info', "Mounting volume '#{volume.name}' (#{volume.id})...", true) error_log(instance.logger, 'info', 'Mounting from inside the instance...', true) with_ssh(instance, username) do |ssh| commands.each do |command, expected| result = ssh.exec!(command).chomp if expected.nil? error_log(instance.logger, 'info', "#{command} yielded '#{result}'") elsif result != expected error_log( instance.logger, 'error', "Failure while running '#{command}':\n\texpected '#{expected}'\n\tgot '#{result}'", true ) return false # returns from volume_mount_unmount? end end end true end |
#with_ssh(instance, username, &block) ⇒ Object
Don’t crash when connection refused.
A helper method to execute a series of commands remotely on an instance. This helper passes its block directly to ‘Net::SSH#start()`.
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# File 'lib/openstack_taster.rb', line 292 def with_ssh(instance, username, &block) tries = 0 instance.logger.progname = 'SSH' begin Net::SSH.start( instance.addresses['public'].first['addr'], username, verbose: :info, paranoid: false, logger: instance.logger, keys: [@ssh_private_key], &block ) rescue Errno::ECONNREFUSED => e puts "Encountered #{e.message} while connecting to the instance." if tries < MAX_SSH_RETRY tries += 1 puts "Initiating SSH attempt #{tries} in #{TIMEOUT_SSH_RETRY} seconds" sleep TIMEOUT_SSH_RETRY retry end error_log(instance.logger, 'error', e.backtrace, false, 'SSH') error_log(instance.logger, 'error', e., false, 'SSH') exit 1 end end |