2013-01-31 07:03:21 +00:00
|
|
|
require "log4r"
|
|
|
|
|
|
|
|
module VagrantPlugins
|
|
|
|
module ProviderVirtualBox
|
|
|
|
module Action
|
|
|
|
class SetName
|
|
|
|
def initialize(app, env)
|
|
|
|
@logger = Log4r::Logger.new("vagrant::action::vm::setname")
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
name = env[:machine].provider_config.name
|
|
|
|
|
2013-09-01 05:43:33 +00:00
|
|
|
# If we already set the name before, then don't do anything
|
|
|
|
sentinel = env[:machine].data_dir.join("action_set_name")
|
|
|
|
if !name && sentinel.file?
|
|
|
|
@logger.info("Default name was already set before, not doing it again.")
|
|
|
|
return @app.call(env)
|
|
|
|
end
|
|
|
|
|
2013-01-31 07:03:21 +00:00
|
|
|
# If no name was manually set, then use a default
|
|
|
|
if !name
|
2013-07-18 04:05:23 +00:00
|
|
|
prefix = "#{env[:root_path].basename.to_s}_#{env[:machine].name}"
|
2013-01-31 07:03:21 +00:00
|
|
|
prefix.gsub!(/[^-a-z0-9_]/i, "")
|
2014-03-11 15:48:33 +00:00
|
|
|
|
|
|
|
# milliseconds + random number suffix to allow for simultaneous
|
|
|
|
# `vagrant up` of the same box in different dirs
|
2013-11-09 20:54:46 +00:00
|
|
|
name = prefix + "_#{(Time.now.to_f * 1000.0).to_i}_#{rand(100000)}"
|
2013-01-31 07:03:21 +00:00
|
|
|
end
|
|
|
|
|
2013-01-31 07:22:45 +00:00
|
|
|
# Verify the name is not taken
|
|
|
|
vms = env[:machine].provider.driver.read_vms
|
2014-05-22 16:35:12 +00:00
|
|
|
raise Vagrant::Errors::VMNameExists, name: name if \
|
2015-01-05 23:29:01 +00:00
|
|
|
vms.key?(name) && vms[name] != env[:machine].id
|
2013-01-31 07:22:45 +00:00
|
|
|
|
2015-01-05 23:29:01 +00:00
|
|
|
if vms.key?(name)
|
2013-01-31 07:22:45 +00:00
|
|
|
@logger.info("Not setting the name because our name is already set.")
|
|
|
|
else
|
2014-01-18 02:21:55 +00:00
|
|
|
env[:ui].info(I18n.t(
|
|
|
|
"vagrant.actions.vm.set_name.setting_name", name: name))
|
2013-01-31 07:22:45 +00:00
|
|
|
env[:machine].provider.driver.set_name(name)
|
|
|
|
end
|
2013-01-31 07:03:21 +00:00
|
|
|
|
2013-09-01 05:43:33 +00:00
|
|
|
# Create the sentinel
|
|
|
|
sentinel.open("w") do |f|
|
|
|
|
f.write(Time.now.to_i.to_s)
|
|
|
|
end
|
|
|
|
|
2013-01-31 07:03:21 +00:00
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|