Class: Vagrant::Environment
- Inherits:
-
Object
- Object
- Vagrant::Environment
- Defined in:
- lib/vagrant/environment.rb,
lib/vagrant/environment/remote.rb
Overview
A "Vagrant environment" represents a configuration of how Vagrant
should behave: data directories, working directory, UI output,
etc. In day-to-day usage, every vagrant
invocation typically
leads to a single Vagrant environment.
Defined Under Namespace
Modules: Remote
Constant Summary collapse
- CURRENT_SETUP_VERSION =
This is the current version that this version of Vagrant is compatible with in the home directory.
"1.5"
- DEFAULT_LOCAL_DATA =
".vagrant"
Instance Attribute Summary collapse
-
#aliases_path ⇒ Object
readonly
File where command line aliases go.
-
#boxes_path ⇒ Object
readonly
The directory where boxes are stored.
-
#cwd ⇒ Object
readonly
The
cwd
that this environment represents. -
#data_dir ⇒ Pathname
readonly
The persistent data directory where global data can be stored.
-
#default_private_key_paths ⇒ Object
readonly
The paths for each of the default private keys.
-
#default_private_keys_directory ⇒ Object
readonly
The path to the default private keys directory.
-
#gems_path ⇒ Object
readonly
The path where the plugins are stored (gems).
-
#home_path ⇒ Object
readonly
The directory to the "home" folder that Vagrant will use to store global state.
-
#local_data_path ⇒ Object
readonly
The directory to the directory where local, environment-specific data is stored.
-
#tmp_path ⇒ Object
readonly
The directory where temporary files for Vagrant go.
-
#ui ⇒ Object
readonly
The UI object to communicate with the outside world.
-
#ui_class ⇒ Object
readonly
This is the UI class to use when creating new UIs.
-
#vagrantfile_name ⇒ Object
readonly
The valid name for a Vagrantfile for this environment.
Instance Method Summary collapse
-
#action_runner ⇒ Action::Runner
Action runner for executing actions in the context of this environment.
-
#active_machines ⇒ Array<String, Symbol>
Returns a list of machines that this environment is currently managing that physically have been created.
-
#batch(parallel = true) ⇒ Object
This creates a new batch action, yielding it, and then running it once the block is called.
-
#boxes ⇒ BoxCollection
Returns the collection of boxes for the environment.
-
#can_install_provider?(name) ⇒ Boolean
Returns whether or not we know how to install the provider with the given name.
-
#cli(*args) ⇒ Object
Makes a call to the CLI with the given arguments as if they came from the real command line (sometimes they do!).
-
#config_loader ⇒ Config::Loader
Returns the Config::Loader that can be used to load Vagrantfiles given the settings of this environment.
-
#default_private_key_path ⇒ Object
The path to the default private key NOTE: deprecated, used default_private_keys_directory instead.
-
#default_provider(**opts) ⇒ Symbol
This returns the provider name for the default provider for this environment.
-
#environment(vagrantfile, **opts) ⇒ Environment
Loads another environment for the given Vagrantfile, sharing as much useful state from this Environment as possible (such as UI and paths).
-
#hook(name, opts = nil) ⇒ Object
This defines a hook point where plugin action hooks that are registered against the given name will be run in the context of this environment.
-
#host ⇒ Class
Returns the host object associated with this environment.
-
#initialize(opts = nil) ⇒ Environment
constructor
Initializes a new environment with the given options.
-
#inspect ⇒ String
Return a human-friendly string for pretty printed or inspected instances.
-
#install_provider(name) ⇒ Object
Installs the provider with the given name.
-
#lock(name = "global", **opts) ⇒ Object
This acquires a process-level lock with the given name.
-
#machine(name, provider, refresh = false) ⇒ Machine
This returns a machine with the proper provider for this environment.
-
#machine_index ⇒ MachineIndex
The MachineIndex to store information about the machines.
-
#machine_names ⇒ Array<Symbol>
This returns a list of the configured machines for this environment.
-
#primary_machine_name ⇒ Symbol
This returns the name of the machine that is the "primary." In the case of a single-machine environment, this is just the single machine name.
-
#push(name, manager: Vagrant.plugin("2").manager) ⇒ Object
This executes the push with the given name, raising any exceptions that occur.
-
#pushes ⇒ Array<Symbol>
The list of pushes defined in this Vagrantfile.
-
#root_path ⇒ String
The root path is the path where the top-most (loaded last) Vagrantfile resides.
-
#setup_home_path ⇒ Pathname
This sets the
@home_path
variable properly. -
#setup_local_data_path(force = false) ⇒ Object
This creates the local data directory and show an error if it couldn't properly be created.
-
#unload ⇒ Object
Unload the environment, running completion hooks.
-
#vagrantfile ⇒ Vagrantfile
Represents the default Vagrantfile, or the Vagrantfile that is in the working directory or a parent of the working directory of this environment.
Constructor Details
#initialize(opts = nil) ⇒ Environment
Initializes a new environment with the given options. The options
is a hash where the main available key is cwd
, which defines where
the environment represents. There are other options available but
they shouldn't be used in general. If cwd
is nil, then it defaults
to the Dir.pwd
(which is the cwd of the executing process).
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 |
# File 'lib/vagrant/environment.rb', line 85 def initialize(opts=nil) opts = { cwd: nil, home_path: nil, local_data_path: nil, ui_class: nil, ui_opts: nil, vagrantfile_name: nil, }.merge(opts || {}) # Set the default working directory to look for the vagrantfile opts[:cwd] ||= ENV["VAGRANT_CWD"] if ENV.key?("VAGRANT_CWD") opts[:cwd] ||= Dir.pwd opts[:cwd] = Pathname.new(opts[:cwd]) if !opts[:cwd].directory? raise Errors::EnvironmentNonExistentCWD, cwd: opts[:cwd].to_s end opts[:cwd] = opts[:cwd]. # Set the default ui class opts[:ui_class] ||= UI::Silent # Set the Vagrantfile name up. We append "Vagrantfile" and "vagrantfile" so that # those continue to work as well, but anything custom will take precedence. opts[:vagrantfile_name] ||= ENV["VAGRANT_VAGRANTFILE"] if \ ENV.key?("VAGRANT_VAGRANTFILE") opts[:vagrantfile_name] = [opts[:vagrantfile_name]] if \ opts[:vagrantfile_name] && !opts[:vagrantfile_name].is_a?(Array) # Set instance variables for all the configuration parameters. @cwd = opts[:cwd] @home_path = opts[:home_path] @vagrantfile_name = opts[:vagrantfile_name] @ui = opts.fetch(:ui, opts[:ui_class].new) @ui_class = opts[:ui_class] if @ui.nil? if opts[:ui_opts].nil? @ui = opts[:ui_class].new else @ui = opts[:ui_class].new(*opts[:ui_opts]) end end # This is the batch lock, that enforces that only one {BatchAction} # runs at a time from {#batch}. @batch_lock = Mutex.new @locks = {} @logger = Log4r::Logger.new("vagrant::environment") @logger.info("Environment initialized (#{self})") @logger.info(" - cwd: #{cwd}") # Setup the home directory @home_path ||= Vagrant.user_data_path @home_path = Util::Platform.fs_real_path(@home_path) @boxes_path = @home_path.join("boxes") @data_dir = @home_path.join("data") @gems_path = Vagrant::Bundler.instance.plugin_gem_path @tmp_path = @home_path.join("tmp") @machine_index_dir = @data_dir.join("machine-index") @aliases_path = Pathname.new(ENV["VAGRANT_ALIAS_FILE"]). if ENV.key?("VAGRANT_ALIAS_FILE") @aliases_path ||= @home_path.join("aliases") # Prepare the directories setup_home_path # Setup the local data directory. If a configuration path is given, # it is expanded relative to the root path. Otherwise, we use the # default (which is also expanded relative to the root path). if !root_path.nil? if !ENV["VAGRANT_DOTFILE_PATH"].to_s.empty? && !opts[:child] opts[:local_data_path] ||= Pathname.new(File.(ENV["VAGRANT_DOTFILE_PATH"], root_path)) else opts[:local_data_path] ||= root_path.join(DEFAULT_LOCAL_DATA) end end if opts[:local_data_path] @local_data_path = Pathname.new(File.(opts[:local_data_path], @cwd)) end @logger.debug("Effective local data path: #{@local_data_path}") # If we have a root path, load the ".vagrantplugins" file. if root_path plugins_file = root_path.join(".vagrantplugins") if plugins_file.file? @logger.info("Loading plugins file: #{plugins_file}") load plugins_file end end setup_local_data_path # Setup the default private key @default_private_key_path = @home_path.join("insecure_private_key") @default_private_keys_directory = @home_path.join("insecure_private_keys") if !@default_private_keys_directory.directory? @default_private_keys_directory.mkdir end @default_private_key_paths = [] copy_insecure_private_keys # Initialize localized plugins plugins = Vagrant::Plugin::Manager.instance.localize!(self) # Load any environment local plugins Vagrant::Plugin::Manager.instance.load_plugins(plugins) # Initialize globalize plugins plugins = Vagrant::Plugin::Manager.instance.globalize! # Load any global plugins Vagrant::Plugin::Manager.instance.load_plugins(plugins) plugins = process_configured_plugins # Call the hooks that does not require configurations to be loaded # by using a "clean" action runner hook(:environment_plugins_loaded, runner: Action::PrimaryRunner.new(env: self)) # Call the environment load hooks hook(:environment_load, runner: Action::PrimaryRunner.new(env: self)) end |
Instance Attribute Details
#aliases_path ⇒ Object (readonly)
File where command line aliases go.
66 67 68 |
# File 'lib/vagrant/environment.rb', line 66 def aliases_path @aliases_path end |
#boxes_path ⇒ Object (readonly)
The directory where boxes are stored.
69 70 71 |
# File 'lib/vagrant/environment.rb', line 69 def boxes_path @boxes_path end |
#cwd ⇒ Object (readonly)
The cwd
that this environment represents
36 37 38 |
# File 'lib/vagrant/environment.rb', line 36 def cwd @cwd end |
#data_dir ⇒ Pathname (readonly)
The persistent data directory where global data can be stored. It is up to the creator of the data in this directory to properly remove it when it is no longer needed.
43 44 45 |
# File 'lib/vagrant/environment.rb', line 43 def data_dir @data_dir end |
#default_private_key_paths ⇒ Object (readonly)
The paths for each of the default private keys
78 79 80 |
# File 'lib/vagrant/environment.rb', line 78 def default_private_key_paths @default_private_key_paths end |
#default_private_keys_directory ⇒ Object (readonly)
The path to the default private keys directory
75 76 77 |
# File 'lib/vagrant/environment.rb', line 75 def default_private_keys_directory @default_private_keys_directory end |
#gems_path ⇒ Object (readonly)
The path where the plugins are stored (gems)
72 73 74 |
# File 'lib/vagrant/environment.rb', line 72 def gems_path @gems_path end |
#home_path ⇒ Object (readonly)
The directory to the "home" folder that Vagrant will use to store global state.
56 57 58 |
# File 'lib/vagrant/environment.rb', line 56 def home_path @home_path end |
#local_data_path ⇒ Object (readonly)
The directory to the directory where local, environment-specific data is stored.
60 61 62 |
# File 'lib/vagrant/environment.rb', line 60 def local_data_path @local_data_path end |
#tmp_path ⇒ Object (readonly)
The directory where temporary files for Vagrant go.
63 64 65 |
# File 'lib/vagrant/environment.rb', line 63 def tmp_path @tmp_path end |
#ui ⇒ Object (readonly)
The UI object to communicate with the outside world.
49 50 51 |
# File 'lib/vagrant/environment.rb', line 49 def ui @ui end |
#ui_class ⇒ Object (readonly)
This is the UI class to use when creating new UIs.
52 53 54 |
# File 'lib/vagrant/environment.rb', line 52 def ui_class @ui_class end |
#vagrantfile_name ⇒ Object (readonly)
The valid name for a Vagrantfile for this environment.
46 47 48 |
# File 'lib/vagrant/environment.rb', line 46 def vagrantfile_name @vagrantfile_name end |
Instance Method Details
#action_runner ⇒ Action::Runner
Action runner for executing actions in the context of this environment.
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/vagrant/environment.rb', line 228 def action_runner @action_runner ||= Action::PrimaryRunner.new do { action_runner: action_runner, box_collection: boxes, hook: method(:hook), host: host, machine_index: machine_index, gems_path: gems_path, home_path: home_path, root_path: root_path, tmp_path: tmp_path, ui: @ui, env: self } end end |
#active_machines ⇒ Array<String, Symbol>
Returns a list of machines that this environment is currently managing that physically have been created.
An "active" machine is a machine that Vagrant manages that has been created. The machine itself may be in any state such as running, suspended, etc. but if a machine is "active" then it exists.
Note that the machines in this array may no longer be present in the Vagrantfile of this environment. In this case the machine can be considered an "orphan." Determining which machines are orphan and which aren't is not currently a supported feature, but will be in a future version.
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 286 287 288 289 290 291 292 |
# File 'lib/vagrant/environment.rb', line 260 def active_machines # We have no active machines if we have no data path return [] if !@local_data_path machine_folder = @local_data_path.join("machines") # If the machine folder is not a directory then we just return # an empty array since no active machines exist. return [] if !machine_folder.directory? # Traverse the machines folder accumulate a result result = [] machine_folder.children(true).each do |name_folder| # If this isn't a directory then it isn't a machine next if !name_folder.directory? name = name_folder.basename.to_s.to_sym name_folder.children(true).each do |provider_folder| # If this isn't a directory then it isn't a provider next if !provider_folder.directory? # If this machine doesn't have an ID, then ignore next if !provider_folder.join("id").file? provider = provider_folder.basename.to_s.to_sym result << [name, provider] end end # Return the results result end |
#batch(parallel = true) ⇒ Object
This creates a new batch action, yielding it, and then running it once the block is called.
This handles the case where batch actions are disabled by the VAGRANT_NO_PARALLEL environmental variable.
299 300 301 302 303 304 305 306 307 308 309 310 311 |
# File 'lib/vagrant/environment.rb', line 299 def batch(parallel=true) parallel = false if ENV["VAGRANT_NO_PARALLEL"] @batch_lock.synchronize do BatchAction.new(parallel).tap do |b| # Yield it so that the caller can setup actions yield b # And run it! b.run end end end |
#boxes ⇒ BoxCollection
Returns the collection of boxes for the environment.
498 499 500 501 502 503 |
# File 'lib/vagrant/environment.rb', line 498 def boxes @_boxes ||= BoxCollection.new( boxes_path, hook: method(:hook), temp_dir_root: tmp_path) end |
#can_install_provider?(name) ⇒ Boolean
Returns whether or not we know how to install the provider with the given name.
479 480 481 |
# File 'lib/vagrant/environment.rb', line 479 def can_install_provider?(name) host.capability?(provider_install_key(name)) end |
#cli(*args) ⇒ Object
Makes a call to the CLI with the given arguments as if they came from the real command line (sometimes they do!). An example:
env.cli("package", "--vagrantfile", "Vagrantfile")
318 319 320 |
# File 'lib/vagrant/environment.rb', line 318 def cli(*args) CLI.new(args.flatten, self).execute end |
#config_loader ⇒ Config::Loader
Returns the Config::Loader that can be used to load Vagrantfiles given the settings of this environment.
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/vagrant/environment.rb', line 509 def config_loader return @config_loader if @config_loader home_vagrantfile = nil root_vagrantfile = nil home_vagrantfile = find_vagrantfile(home_path) if home_path if root_path root_vagrantfile = find_vagrantfile(root_path, @vagrantfile_name) end @config_loader = Config::Loader.new( Config::VERSIONS, Config::VERSIONS_ORDER) @config_loader.set(:home, home_vagrantfile) if home_vagrantfile @config_loader.set(:root, root_vagrantfile) if root_vagrantfile @config_loader end |
#default_private_key_path ⇒ Object
The path to the default private key NOTE: deprecated, used default_private_keys_directory instead
212 213 214 215 |
# File 'lib/vagrant/environment.rb', line 212 def default_private_key_path # TODO(spox): Add deprecation warning @default_private_key_path end |
#default_provider(**opts) ⇒ Symbol
This returns the provider name for the default provider for this environment.
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 |
# File 'lib/vagrant/environment.rb', line 332 def default_provider(**opts) opts[:exclude] = Set.new(opts[:exclude]) if opts[:exclude] opts[:force_default] = true if !opts.key?(:force_default) opts[:check_usable] = true if !opts.key?(:check_usable) # Implement the algorithm from # https://www.vagrantup.com/docs/providers/basic_usage.html#default-provider # with additional steps 2.5 and 3.5 from # https://bugzilla.redhat.com/show_bug.cgi?id=1444492 # to allow system-configured provider priorities. # # 1. The --provider flag on a vagrant up is chosen above all else, if it is # present. # # (Step 1 is done by the caller; this method is only called if --provider # wasn't given.) # # 2. If the VAGRANT_DEFAULT_PROVIDER environmental variable is set, it # takes next priority and will be the provider chosen. default = ENV["VAGRANT_DEFAULT_PROVIDER"].to_s if default.empty? default = nil else default = default.to_sym @logger.debug("Default provider: `#{default}`") end # If we're forcing the default, just short-circuit and return # that (the default behavior) if default && opts[:force_default] @logger.debug("Using forced default provider: `#{default}`") return default end # Determine the config to use to look for provider definitions. By # default it is the global but if we're targeting a specific machine, # then look there. root_config = vagrantfile.config if opts[:machine] machine_info = vagrantfile.machine_config(opts[:machine], nil, nil, nil) root_config = machine_info[:config] end # Get the list of providers within our configuration, in order. config = root_config.vm.__providers # Get the list of usable providers with their internally-declared # priorities. usable = [] Vagrant.plugin("2").manager.providers.each do |key, data| impl = data[0] popts = data[1] # Skip excluded providers next if opts[:exclude] && opts[:exclude].include?(key) # Skip providers that can't be defaulted, unless they're in our # config, in which case someone made our decision for us. if !config.include?(key) next if popts.key?(:defaultable) && !popts[:defaultable] end # Skip providers that aren't usable. next if opts[:check_usable] && !impl.usable?(false) # Each provider sets its own priority, defaulting to 5 so we can trust # it's always set. usable << [popts[:priority], key] end @logger.debug("Initial usable provider list: #{usable}") # Sort the usable providers by priority. Higher numbers are higher # priority, otherwise alpha sort. usable = usable.sort {|a, b| a[0] == b[0] ? a[1] <=> b[1] : b[0] <=> a[0]} .map {|prio, key| key} @logger.debug("Priority sorted usable provider list: #{usable}") # If we're not forcing the default, but it's usable and hasn't been # otherwise excluded, return it now. if usable.include?(default) @logger.debug("Using default provider `#{default}` as it was found in usable list.") return default end # 2.5. Vagrant will go through all of the config.vm.provider calls in the # Vagrantfile and try each in order. It will choose the first # provider that is usable and listed in VAGRANT_PREFERRED_PROVIDERS. preferred = ENV.fetch('VAGRANT_PREFERRED_PROVIDERS', '') .split(',') .map {|s| s.strip} .select {|s| !s.empty?} .map {|s| s.to_sym} @logger.debug("Preferred provider list: #{preferred}") config.each do |key| if usable.include?(key) && preferred.include?(key) @logger.debug("Using preferred provider `#{key}` detected in configuration and usable.") return key end end # 3. Vagrant will go through all of the config.vm.provider calls in the # Vagrantfile and try each in order. It will choose the first provider # that is usable. For example, if you configure Hyper-V, it will never # be chosen on Mac this way. It must be both configured and usable. config.each do |key| if usable.include?(key) @logger.debug("Using provider `#{key}` detected in configuration and usable.") return key end end # 3.5. Vagrant will go through VAGRANT_PREFERRED_PROVIDERS and find the # first plugin that reports it is usable. preferred.each do |key| if usable.include?(key) @logger.debug("Using preferred provider `#{key}` found in usable list.") return key end end # 4. Vagrant will go through all installed provider plugins (including the # ones that come with Vagrant), and find the first plugin that reports # it is usable. There is a priority system here: systems that are known # better have a higher priority than systems that are worse. For # example, if you have the VMware provider installed, it will always # take priority over VirtualBox. if !usable.empty? @logger.debug("Using provider `#{usable[0]}` as it is the highest priority in the usable list.") return usable[0] end # 5. If Vagrant still has not found any usable providers, it will error. # No providers available is a critical error for Vagrant. raise Errors::NoDefaultProvider end |
#environment(vagrantfile, **opts) ⇒ Environment
Loads another environment for the given Vagrantfile, sharing as much useful state from this Environment as possible (such as UI and paths). Any initialization options can be overidden using the opts hash.
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/vagrant/environment.rb', line 532 def environment(vagrantfile, **opts) path = File.(vagrantfile, root_path) file = File.basename(path) path = File.dirname(path) Util::SilenceWarnings.silence! do Environment.new({ child: true, cwd: path, home_path: home_path, ui_class: ui_class, vagrantfile_name: file, }.merge(opts)) end end |
#hook(name, opts = nil) ⇒ Object
This defines a hook point where plugin action hooks that are registered against the given name will be run in the context of this environment.
553 554 555 556 557 558 559 560 561 562 |
# File 'lib/vagrant/environment.rb', line 553 def hook(name, opts=nil) @logger.info("Running hook: #{name}") opts ||= {} opts[:callable] ||= Action::Builder.new opts[:runner] ||= action_runner opts[:action_name] = name opts[:env] = self opts.delete(:runner).run(opts.delete(:callable), opts) end |
#host ⇒ Class
Returns the host object associated with this environment.
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 |
# File 'lib/vagrant/environment.rb', line 567 def host return @host if defined?(@host) # Determine the host class to use. ":detect" is an old Vagrant config # that shouldn't be valid anymore, but we respect it here by assuming # its old behavior. No need to deprecate this because I thin it is # fairly harmless. host_klass = vagrantfile.config.vagrant.host host_klass = nil if host_klass == :detect begin @host = Host.new( host_klass, Vagrant.plugin("2").manager.hosts, Vagrant.plugin("2").manager.host_capabilities, self) rescue Errors::CapabilityHostNotDetected # If the auto-detect failed, then we create a brand new host # with no capabilities and use that. This should almost never happen # since Vagrant works on most host OS's now, so this is a "slow path" klass = Class.new(Vagrant.plugin("2", :host)) do def detect?(env); true; end end hosts = { generic: [klass, nil] } host_caps = {} @host = Host.new(:generic, hosts, host_caps, self) rescue Errors::CapabilityHostExplicitNotDetected => e raise Errors::HostExplicitNotDetected, e.extra_data end end |
#inspect ⇒ String
Return a human-friendly string for pretty printed or inspected instances.
221 222 223 |
# File 'lib/vagrant/environment.rb', line 221 def inspect "#<#{self.class}: #{@cwd}>".encode('external') end |
#install_provider(name) ⇒ Object
Installs the provider with the given name.
This will raise an exception if we don't know how to install the
provider with the given name. You should guard this call with
can_install_provider?
for added safety.
An exception will be raised if there are any failures installing the provider.
491 492 493 |
# File 'lib/vagrant/environment.rb', line 491 def install_provider(name) host.capability(provider_install_key(name)) end |
#lock(name = "global", **opts) ⇒ Object
This acquires a process-level lock with the given name.
The lock file is held within the data directory of this environment, so make sure that all environments that are locking are sharing the same data directory.
This will raise Errors::EnvironmentLockedError if the lock can't be obtained.
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 |
# File 'lib/vagrant/environment.rb', line 611 def lock(name="global", **opts) f = nil # If we don't have a block, then locking is useless, so ignore it return if !block_given? # This allows multiple locks in the same process to be nested return yield if @locks[name] || opts[:noop] # The path to this lock lock_path = data_dir.join("lock.#{name}.lock") @logger.debug("Attempting to acquire process-lock: #{name}") lock("dotlock", noop: name == "dotlock", retry: true) do f = File.open(lock_path, "w+") end # The file locking fails only if it returns "false." If it # succeeds it returns a 0, so we must explicitly check for # the proper error case. while f.flock(File::LOCK_EX | File::LOCK_NB) === false @logger.warn("Process-lock in use: #{name}") if !opts[:retry] raise Errors::EnvironmentLockedError, name: name end sleep 0.2 end @logger.info("Acquired process lock: #{name}") result = nil begin # Mark that we have a lock @locks[name] = true result = yield ensure # We need to make sure that no matter what this is always # reset to false so we don't think we have a lock when we # actually don't. @locks.delete(name) @logger.info("Released process lock: #{name}") end # Clean up the lock file, this requires another lock if name != "dotlock" lock("dotlock", retry: true) do f.close begin File.delete(lock_path) rescue @logger.error( "Failed to delete lock file #{lock_path} - some other thread " + "might be trying to acquire it. ignoring this error") end end end # Return the result return result ensure begin f.close if f rescue IOError end end |
#machine(name, provider, refresh = false) ⇒ Machine
This returns a machine with the proper provider for this environment.
The machine named by name
must be in this environment.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 |
# File 'lib/vagrant/environment.rb', line 733 def machine(name, provider, refresh=false) @logger.info("Getting machine: #{name} (#{provider})") # Compose the cache key of the name and provider, and return from # the cache if we have that. cache_key = [name, provider] @machines ||= {} if refresh @logger.info("Refreshing machine (busting cache): #{name} (#{provider})") @machines.delete(cache_key) end if @machines.key?(cache_key) @logger.info("Returning cached machine: #{name} (#{provider})") return @machines[cache_key] end @logger.info("Uncached load of machine.") # Determine the machine data directory and pass it to the machine. machine_data_path = @local_data_path.join( "machines/#{name}/#{provider}") # Create the machine and cache it for future calls. This will also # return the machine from this method. @machines[cache_key] = vagrantfile.machine( name, provider, boxes, machine_data_path, self) end |
#machine_index ⇒ MachineIndex
The MachineIndex to store information about the machines.
765 766 767 |
# File 'lib/vagrant/environment.rb', line 765 def machine_index @machine_index ||= MachineIndex.new(@machine_index_dir) end |
#machine_names ⇒ Array<Symbol>
This returns a list of the configured machines for this environment. Each of the names returned by this method is valid to be used with the #machine method.
774 775 776 |
# File 'lib/vagrant/environment.rb', line 774 def machine_names vagrantfile.machine_names end |
#primary_machine_name ⇒ Symbol
This returns the name of the machine that is the "primary." In the case of a single-machine environment, this is just the single machine name. In the case of a multi-machine environment, then this can potentially be nil if no primary machine is specified.
784 785 786 |
# File 'lib/vagrant/environment.rb', line 784 def primary_machine_name vagrantfile.primary_machine_name end |
#push(name, manager: Vagrant.plugin("2").manager) ⇒ Object
This executes the push with the given name, raising any exceptions that occur.
defaults to the primary one registered but parameterized so it can be overridden in server mode
Precondition: the push is not nil and exists.
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 |
# File 'lib/vagrant/environment.rb', line 692 def push(name, manager: Vagrant.plugin("2").manager) @logger.info("Getting push: #{name}") name = name.to_sym pushes = self.vagrantfile.config.push.__compiled_pushes if !pushes.key?(name) raise Vagrant::Errors::PushStrategyNotDefined, name: name, pushes: pushes.keys end strategy, config = pushes[name] push_registry = manager.pushes klass, _ = push_registry.get(strategy) if klass.nil? raise Vagrant::Errors::PushStrategyNotLoaded, name: strategy, pushes: push_registry.keys end klass.new(self, config).push end |
#pushes ⇒ Array<Symbol>
The list of pushes defined in this Vagrantfile.
719 720 721 |
# File 'lib/vagrant/environment.rb', line 719 def pushes self.vagrantfile.config.push.__compiled_pushes.keys end |
#root_path ⇒ String
The root path is the path where the top-most (loaded last) Vagrantfile resides. It can be considered the project root for this environment.
793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
# File 'lib/vagrant/environment.rb', line 793 def root_path return @root_path if defined?(@root_path) root_finder = lambda do |path| # Note: To remain compatible with Ruby 1.8, we have to use # a `find` here instead of an `each`. vf = find_vagrantfile(path, @vagrantfile_name) return path if vf return nil if path.root? || !File.exist?(path) root_finder.call(path.parent) end @root_path = root_finder.call(cwd) end |
#setup_home_path ⇒ Pathname
This sets the @home_path
variable properly.
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 |
# File 'lib/vagrant/environment.rb', line 845 def setup_home_path @logger.info("Home path: #{@home_path}") # Setup the list of child directories that need to be created if they # don't already exist. dirs = [ @home_path, @home_path.join("rgloader"), @boxes_path, @data_dir, @gems_path, @tmp_path, @machine_index_dir, ] # Go through each required directory, creating it if it doesn't exist dirs.each do |dir| next if File.directory?(dir) begin @logger.info("Creating: #{dir}") FileUtils.mkdir_p(dir) rescue Errno::EACCES, Errno::EROFS raise Errors::HomeDirectoryNotAccessible, home_path: @home_path.to_s end end # Attempt to write into the home directory to verify we can begin # Append a random suffix to avoid race conditions if Vagrant # is running in parallel with other Vagrant processes. suffix = (0...32).map { (65 + rand(26)).chr }.join path = @home_path.join("perm_test_#{suffix}") path.open("w") do |f| f.write("hello") end path.unlink rescue Errno::EACCES raise Errors::HomeDirectoryNotAccessible, home_path: @home_path.to_s end # Create the version file that we use to track the structure of # the home directory. If we have an old version, we need to explicitly # upgrade it. Otherwise, we just mark that its the current version. version_file = @home_path.join("setup_version") if version_file.file? version = version_file.read.chomp if version > CURRENT_SETUP_VERSION raise Errors::HomeDirectoryLaterVersion end case version when CURRENT_SETUP_VERSION # We're already good, at the latest version. when "1.1" # We need to update our directory structure upgrade_home_path_v1_1 # Delete the version file so we put our latest version in version_file.delete else raise Errors::HomeDirectoryUnknownVersion, path: @home_path.to_s, version: version end end if !version_file.file? @logger.debug( "Creating home directory version file: #{CURRENT_SETUP_VERSION}") version_file.open("w") do |f| f.write(CURRENT_SETUP_VERSION) end end # Create the rgloader/loader file so we can use encoded files. loader_file = @home_path.join("rgloader", "loader.rb") if !loader_file.file? source_loader = Vagrant.source_root.join("templates/rgloader.rb") FileUtils.cp(source_loader.to_s, loader_file.to_s) end end |
#setup_local_data_path(force = false) ⇒ Object
This creates the local data directory and show an error if it couldn't properly be created.
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 |
# File 'lib/vagrant/environment.rb', line 930 def setup_local_data_path(force=false) if @local_data_path.nil? @logger.warn("No local data path is set. Local data cannot be stored.") return end @logger.info("Local data path: #{@local_data_path}") # If the local data path is a file, then we are probably seeing an # old (V1) "dotfile." In this case, we upgrade it. The upgrade process # will remove the old data file if it is successful. if @local_data_path.file? upgrade_v1_dotfile(@local_data_path) end # If we don't have a root path, we don't setup anything return if !force && root_path.nil? begin @logger.debug("Creating: #{@local_data_path}") FileUtils.mkdir_p(@local_data_path) # Create the rgloader/loader file so we can use encoded files. loader_file = @local_data_path.join("rgloader", "loader.rb") if !loader_file.file? source_loader = Vagrant.source_root.join("templates/rgloader.rb") FileUtils.mkdir_p(@local_data_path.join("rgloader").to_s) FileUtils.cp(source_loader.to_s, loader_file.to_s) end rescue Errno::EACCES raise Errors::LocalDataDirectoryNotAccessible, local_data_path: @local_data_path.to_s end end |
#unload ⇒ Object
Unload the environment, running completion hooks. The environment
should not be used after this (but CAN be, technically). It is
recommended to always immediately set the variable to nil
after
running this so you can't accidentally run any more methods. Example:
env.unload
env = nil
816 817 818 |
# File 'lib/vagrant/environment.rb', line 816 def unload hook(:environment_unload) end |
#vagrantfile ⇒ Vagrantfile
Represents the default Vagrantfile, or the Vagrantfile that is in the working directory or a parent of the working directory of this environment.
The existence of this function is primarily a convenience. There is nothing stopping you from instantiating your own Vagrantfile and loading machines in any way you see fit. Typical behavior of Vagrant, however, loads this Vagrantfile.
This Vagrantfile is comprised of two major sources: the Vagrantfile in the user's home directory as well as the "root" Vagrantfile or the Vagrantfile in the working directory (or parent).
834 835 836 |
# File 'lib/vagrant/environment.rb', line 834 def vagrantfile @vagrantfile ||= Vagrantfile.new(config_loader, [:home, :root]) end |