Class: Vagrant::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/environment.rb

Overview

Represents a single Vagrant environment. A "Vagrant environment" is defined as basically a folder with a "Vagrantfile." This class allows access to the VMs, CLI, etc. all in the scope of this environment.

Constant Summary collapse

ROOTFILE_NAME =
"Vagrantfile"
HOME_SUBDIRS =
["tmp", "boxes", "logs"]
DEFAULT_VM =
:default
DEFAULT_HOME =
"~/.vagrant"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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).



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/vagrant/environment.rb', line 56

def initialize(opts=nil)
  opts = {
    :parent => nil,
    :vm => nil,
    :cwd => nil,
  }.merge(opts || {})

  opts[:cwd] ||= Dir.pwd
  opts[:cwd] = Pathname.new(opts[:cwd])

  opts.each do |key, value|
    instance_variable_set("@#{key}".to_sym, opts[key])
  end

  @loaded = false
end

Instance Attribute Details

#config_loaderObject (readonly)

The Config object representing the Vagrantfile loader



28
29
30
# File 'lib/vagrant/environment.rb', line 28

def config_loader
  @config_loader
end

#cwdObject (readonly)

The cwd that this environment represents



18
19
20
# File 'lib/vagrant/environment.rb', line 18

def cwd
  @cwd
end

#parentObject (readonly)

Parent environment (in the case of multi-VMs)



15
16
17
# File 'lib/vagrant/environment.rb', line 15

def parent
  @parent
end

#uiUI

Returns the UI for the environment, which is responsible for talking with the outside world.

Returns:



197
198
199
200
201
202
203
204
205
# File 'lib/vagrant/environment.rb', line 197

def ui
  @ui ||= if parent
    result = parent.ui.clone
    result.env = self
    result
  else
    UI.new(self)
  end
end

#vmObject

The single VM that this environment represents, in the case of multi-VM.



22
23
24
# File 'lib/vagrant/environment.rb', line 22

def vm
  @vm
end

Class Method Details

.check_virtualbox!Object

Verifies that VirtualBox is installed and that the version of VirtualBox installed is high enough.



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/vagrant/environment.rb', line 36

def check_virtualbox!
  version = VirtualBox.version
  raise Errors::VirtualBoxNotDetected if version.nil?
  raise Errors::VirtualBoxInvalidVersion, :version => version.to_s if version.to_f < 4.0
rescue Errors::VirtualBoxNotDetected
  # On 64-bit Windows, show a special error. This error is a subclass
  # of VirtualBoxNotDetected, so libraries which use Vagrant can just
  # rescue VirtualBoxNotDetected.
  raise Errors::VirtualBoxNotDetected_Win64 if Util::Platform.windows? && Util::Platform.bit64?

  # Otherwise, reraise the old error
  raise
end

Instance Method Details

#actionsAction

Returns the Action class for this environment which allows actions to be executed (middleware chains) in the context of this environment.

Returns:



218
219
220
# File 'lib/vagrant/environment.rb', line 218

def actions
  @actions ||= Action.new(self)
end

#boxBox

Returns the box that this environment represents.

Returns:



134
135
136
# File 'lib/vagrant/environment.rb', line 134

def box
  boxes.find(config.vm.box)
end

#boxesBoxCollection

Returns the collection of boxes for the environment.

Returns:



126
127
128
129
# File 'lib/vagrant/environment.rb', line 126

def boxes
  return parent.boxes if parent
  @_boxes ||= BoxCollection.new(self)
end

#boxes_pathPathname

The path to the Vagrant boxes directory

Returns:

  • (Pathname)


102
103
104
# File 'lib/vagrant/environment.rb', line 102

def boxes_path
  home_path.join("boxes")
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")


189
190
191
# File 'lib/vagrant/environment.rb', line 189

def cli(*args)
  CLI.start(args.flatten, :env => self)
end

#configConfig::Top

The configuration object represented by this environment. This will trigger the environment to load if it hasn't loaded yet (see #load!).

Returns:



281
282
283
284
# File 'lib/vagrant/environment.rb', line 281

def config
  load! if !loaded?
  @config
end

#dotfile_pathPathname

The path to the dotfile, which contains the persisted UUID of the VM if it exists.

Returns:

  • (Pathname)


81
82
83
# File 'lib/vagrant/environment.rb', line 81

def dotfile_path
  root_path.join(config.vagrant.dotfile_name) rescue nil
end

#global_dataDataStore

Loads on initial access and reads data from the global data store. The global data store is global to Vagrant everywhere (in every environment), so it can be used to store system-wide information. Note that "system-wide" typically means "for this user" since the location of the global data store is in the home directory.

Returns:



229
230
231
232
# File 'lib/vagrant/environment.rb', line 229

def global_data
  return parent.global_data if parent
  @global_data ||= DataStore.new(File.expand_path("global_data.json", home_path))
end

#home_pathPathname

The path to the home directory and converted into a Pathname object.

Returns:

  • (Pathname)


88
89
90
# File 'lib/vagrant/environment.rb', line 88

def home_path
  @_home_path ||= Pathname.new(File.expand_path(ENV["VAGRANT_HOME"] || DEFAULT_HOME))
end

#hostHosts::Base

Returns the host object associated with this environment.

Returns:



210
211
212
# File 'lib/vagrant/environment.rb', line 210

def host
  @host ||= Hosts::Base.load(self, config.vagrant.host)
end

#load!Object

Loads this entire environment, setting up the instance variables such as vm, config, etc. on this environment. The order this method calls its other methods is very particular.



301
302
303
304
305
306
307
308
309
# File 'lib/vagrant/environment.rb', line 301

def load!
  if !loaded?
    @loaded = true
    self.class.check_virtualbox!
    load_config!
  end

  self
end

#load_config!Object

Loads this environment's configuration and stores it in the #config variable. The configuration loaded by this method is specified to this environment, meaning that it will use the given root directory to load the Vagrantfile into that context.



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
354
# File 'lib/vagrant/environment.rb', line 323

def load_config!
  first_run = @config.nil?

  # First load the initial, non config-dependent Vagrantfiles
  @config_loader ||= Config.new(parent ? parent.config_loader : nil)
  @config_loader.load_order = [:default, :box, :home, :root, :sub_vm]
  @config_loader.set(:default, File.expand_path("config/default.rb", Vagrant.source_root))
  @config_loader.set(:box, File.join(box.directory, ROOTFILE_NAME)) if !first_run && vm && box
  @config_loader.set(:home, File.join(home_path, ROOTFILE_NAME)) if !first_run && home_path
  @config_loader.set(:root, File.join(root_path, ROOTFILE_NAME)) if root_path

  # If this environment is representing a sub-VM, then we push that
  # proc on as the last configuration.
  if vm
    subvm = parent.config.vm.defined_vms[vm.name]
    @config_loader.set(:sub_vm, subvm.proc_stack) if subvm
  end

  # Execute the configuration stack and store the result as the final
  # value in the config ivar.
  @config = @config_loader.load(self)

  # (re)load the logger
  @logger = nil

  if first_run
    # After the first run we want to load the configuration again since
    # it can change due to box Vagrantfiles and home directory Vagrantfiles
    load_home_directory!
    load_config!
  end
end

#load_home_directory!Object

Loads the home directory path and creates the necessary subdirectories within the home directory if they're not already created.



358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/vagrant/environment.rb', line 358

def load_home_directory!
  # Setup the array of necessary home directories
  dirs = [home_path]
  dirs += HOME_SUBDIRS.collect { |subdir| home_path.join(subdir) }

  # Go through each required directory, creating it if it doesn't exist
  dirs.each do |dir|
    next if File.directory?(dir)

    ui.info I18n.t("vagrant.general.creating_home_dir", :directory => dir)
    FileUtils.mkdir_p(dir)
  end
end

#load_vms!Object

Loads the persisted VM (if it exists) for this environment.



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/vagrant/environment.rb', line 373

def load_vms!
  result = {}

  # Load the VM UUIDs from the local data store
  (local_data[:active] || {}).each do |name, uuid|
    result[name.to_sym] = Vagrant::VM.find(uuid, self, name.to_sym)
  end

  # For any VMs which aren't created, create a blank VM instance for
  # them
  all_keys = config.vm.defined_vm_keys
  all_keys = [DEFAULT_VM] if all_keys.empty?
  all_keys.each do |name|
    result[name] = Vagrant::VM.new(:name => name, :env => self) if !result.has_key?(name)
  end

  result
end

#loaded?Bool

Returns a boolean representing if the environment has been loaded or not.

Returns:

  • (Bool)


294
295
296
# File 'lib/vagrant/environment.rb', line 294

def loaded?
  !!@loaded
end

#local_dataDataStore

Loads (on initial access) and reads data from the local data store. This file is always at the root path as the file "~/.vagrant" and contains a JSON dump of a hash. See DataStore for more information.

Returns:



240
241
242
243
# File 'lib/vagrant/environment.rb', line 240

def local_data
  return parent.local_data if parent
  @local_data ||= DataStore.new(dotfile_path)
end

#log_pathPathname

Path to the Vagrant logs directory

Returns:

  • (Pathname)


109
110
111
# File 'lib/vagrant/environment.rb', line 109

def log_path
  home_path.join("logs")
end

#loggerLogger

Accesses the logger for Vagrant. This logger is a detailed logger which should be used to log internals only. For outward facing information, use #ui.

Returns:

  • (Logger)


250
251
252
253
# File 'lib/vagrant/environment.rb', line 250

def logger
  return parent.logger if parent
  @logger ||= Util::ResourceLogger.new(resource, self)
end

#multivm?Bool

Returns a boolean whether this environment represents a multi-VM environment or not. This will work even when called on child environments.

Returns:

  • (Bool)


176
177
178
179
180
181
182
# File 'lib/vagrant/environment.rb', line 176

def multivm?
  if parent
    parent.multivm?
  else
    vms.length > 1 || vms.keys.first != DEFAULT_VM
  end
end

#primary_vmVM

Returns the primary VM associated with this environment. This method is only applicable for multi-VM environments. This can potentially be nil if no primary VM is specified.

Returns:



160
161
162
163
164
165
166
167
168
169
# File 'lib/vagrant/environment.rb', line 160

def primary_vm
  return vms.values.first if !multivm?
  return parent.primary_vm if parent

  config.vm.defined_vms.each do |name, subvm|
    return vms[name] if subvm.options[:primary]
  end

  nil
end

#reload_config!Object

Reloads the configuration of this environment.



312
313
314
315
316
317
# File 'lib/vagrant/environment.rb', line 312

def reload_config!
  @config = nil
  @config_loader = nil
  load_config!
  self
end

#resourceString

Returns the name of the resource which this environment represents. The resource is the VM name if there is a VM it represents, otherwise it defaults to "vagrant"

Returns:

  • (String)


118
119
120
121
# File 'lib/vagrant/environment.rb', line 118

def resource
  result = vm.name rescue nil
  result || "vagrant"
end

#root_pathString

The root path is the path where the top-most (loaded last) Vagrantfile resides. It can be considered the project root for this environment.

Returns:

  • (String)


260
261
262
263
264
265
266
267
268
269
270
# File 'lib/vagrant/environment.rb', line 260

def root_path
  return @root_path if defined?(@root_path)

  root_finder = lambda do |path|
    return path if File.exist?(File.join(path.to_s, ROOTFILE_NAME))
    return nil if path.root? || !File.exist?(path)
    root_finder.call(path.parent)
  end

  @root_path = root_finder.call(cwd)
end

#tmp_pathPathname

The path to the Vagrant tmp directory

Returns:

  • (Pathname)


95
96
97
# File 'lib/vagrant/environment.rb', line 95

def tmp_path
  home_path.join("tmp")
end

#vmsHash<Symbol,VM>

Returns the VMs associated with this environment.

Returns:

  • (Hash<Symbol,VM>)


141
142
143
144
145
# File 'lib/vagrant/environment.rb', line 141

def vms
  return parent.vms if parent
  load! if !loaded?
  @vms ||= load_vms!
end

#vms_orderedArray<VM>

Returns the VMs associated with this environment, in the order that they were defined.

Returns:

  • (Array<VM>)


151
152
153
# File 'lib/vagrant/environment.rb', line 151

def vms_ordered
  @vms_enum ||= config.vm.defined_vm_keys.map { |name| @vms[name] }
end