Class: Vagrantomatic::Instance

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrantomatic/instance.rb

Constant Summary collapse

VAGRANTFILE =
"Vagrantfile"
VAGRANTFILE_JSON =
"#{VAGRANTFILE}.json"
MASTER_VAGRANTFILE =

We ship our own Vagrantfile with all variables externalised inside this gem and get it into position by symlinking B-)

File.join(File.dirname(File.expand_path(__FILE__)), "../../res/#{VAGRANTFILE}")

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vagrant_vm_dir, name, logger: nil, config: nil) ⇒ Instance

Returns a new instance of Instance.



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
# File 'lib/vagrantomatic/instance.rb', line 46

def initialize(vagrant_vm_dir, name, logger: nil, config:nil)
  @name           = name
  @vagrant_vm_dir = vagrant_vm_dir
  @logger         = Logger.new(logger).logger

  # if we encounter conditions such as missing or damaged files we may need
  # to force a save that would normally not be detected - eg if we load bad
  # json it gets fixed up to an empty hash which would them be compared to a
  # fresh read of the file (also results in empty hash) - so we must supply
  # another way to force the save here
  @force_save     = false

  # use supplied config if present, otherwise load from file
  if config
    @config = config

    # validate a user-supplied config now, at the point of insertion
    # by this point we have a config either from file or supplied by user it
    # must be valid for us to proceed!
    @logger.debug "validating config for #{name}"
    validate_config

    # user may have specified relative folders at time of creation - if so
    # we must now expand all paths in them and write them forever to config
    # file
    fix_folders
  else
    @config = configfile_hash

    # this passed-in config could still be bad - we will validate it before
    # use on either save() or get_vm()
  end

  @logger.debug "initialized vagrantomatic instance for #{name}"
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



12
13
14
# File 'lib/vagrantomatic/instance.rb', line 12

def config
  @config
end

Instance Method Details

#configfileObject



90
91
92
# File 'lib/vagrantomatic/instance.rb', line 90

def configfile
  File.join(vm_instance_dir, VAGRANTFILE_JSON)
end

#configfile_hashObject

return a hash of the configfile or empty hash if error encountered



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/vagrantomatic/instance.rb', line 95

def configfile_hash

  config  = {}
  begin
    json    = File.read(configfile)
    config  = JSON.parse(json)
  rescue Errno::ENOENT
    # depending on whether the instance has been saved or not, we may not
    # yet have a configfile - allow to proceed
    @logger.debug "#{configfile} does not exist"
    @force_save = true
  rescue JSON::ParserError
    # swallow parse errors so that we can destroy and recreate automatically
    @logger.debug "JSON parse error in #{configfile}"
    @force_save = true
  end
  config
end

#configured?Boolean

Returns:

  • (Boolean)


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
# File 'lib/vagrantomatic/instance.rb', line 114

def configured?
  configured = true

  if ! Dir.exists? (vm_instance_dir)
    @logger.debug "Vagrant instance directory #{vm_instance_dir} does not exist"
    configured = false
  end

  if ! File.exists?(vagrantfile)
    @logger.debug "#{VAGRANTFILE} not found at #{vagrantfile}"
    configured = false
  end

  if ! File.exists?(configfile)
    @logger.debug "#{VAGRANTFILE_JSON} not found at #{configfile}"
    configured = false
  end

  # check config hash is valid without causing a fatal error if its damaged
  if ! validate_config(false)
    configured = false
  end

  configured
end

#ensure_configObject

Vagrant to be driven from a .json config file, all the parameters are externalised here



151
152
153
154
155
156
157
# File 'lib/vagrantomatic/instance.rb', line 151

def ensure_config
  if ! in_sync?
    File.open(configfile,"w") do |f|
      f.write(@config.to_json)
    end
  end
end

#ensure_vagrantfileObject

The Vagrantfile itself is shipped as part of this module and delivered via pluginsync, so we just need to symlink it for each directory. This gives us the benefit being to update by dropping a new module too



163
164
165
# File 'lib/vagrantomatic/instance.rb', line 163

def ensure_vagrantfile
  FileUtils.ln_sf(MASTER_VAGRANTFILE, vagrantfile)
end

#execute_and_log(op) ⇒ Object



188
189
190
191
192
193
# File 'lib/vagrantomatic/instance.rb', line 188

def execute_and_log(op)
  get_vm.execute(op) { |stdout, stderr|
    # only one of these will ever be set at a time, other one is nil
    @logger.debug "#{stdout}#{stderr}".strip
  }.success?
end

#fix_foldersObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/vagrantomatic/instance.rb', line 27

def fix_folders()
  # can't use dig() might not be ruby 2.3
  if @config.has_key?("folders")
    @config["folders"] = Array(@config["folders"])

    # all paths must be fully qualified.  If we were asked to do a relative path, change
    # it to the current directory since that's probably what the user wanted.  Not right?
    # user supply correct path!
    @config["folders"] = @config["folders"].map { |folder|
      if ! folder.start_with? '/'
        folder = "#{Dir.pwd}/#{folder}"
      end
      folder
    }
  else
    @config["folders"] = []
  end
end

#get_vmObject



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/vagrantomatic/instance.rb', line 168

def get_vm
  # Create an instance (represents a Vagrant **installation**)
  if ! in_sync?
    raise "get_vm called for instance but it is not in_sync! (call save() first?)"
  end

  validate_config

  vagrant_installation = Derelict.instance(Vagrantomatic::DEFAULT_VAGRANT_DIR)
  result = vagrant_installation.execute('--version') # Derelict::Executer object (vagrant --version)
  if result.success?
    # vagrant present and working, connect to our vm INSTANCE
    vm = vagrant_installation.connect(vm_instance_dir)
  else
    raise "Error connecting to vagrant! (vagrant --version failed)"
  end

  vm
end

#in_sync?Boolean

Returns:

  • (Boolean)


195
196
197
198
199
200
201
202
203
204
# File 'lib/vagrantomatic/instance.rb', line 195

def in_sync?
  configured  = false
  have_config = configfile_hash

  if (! @force_save) and (have_config == @config )
    configured = true
  end

  configured
end

#purgeObject



214
215
216
217
218
219
# File 'lib/vagrantomatic/instance.rb', line 214

def purge
  execute_and_log(:destroy)
  if Dir.exists? vm_instance_dir
    FileUtils::rm_rf(vm_instance_dir)
  end
end

#reloadObject



221
222
223
# File 'lib/vagrantomatic/instance.rb', line 221

def reload
  execute_and_log(:reload)
end

#resetObject



225
226
227
228
# File 'lib/vagrantomatic/instance.rb', line 225

def reset
  execute_and_log(:destroy)
  execute_and_log(:up)
end

#run(command) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/vagrantomatic/instance.rb', line 230

def run(command)
  # arrayify
  command = [command]
  command.unshift("-c")

  messages = []
  vm = get_vm
  # throw the command over the wall to derelect whatever the state of instance
  # for now just support ssh - for windows we could do `powershell -c` or
  # maybe even winRM
  executor = vm.execute(:ssh, command) { |stdout,stderr|
    line = "#{stdout}#{stderr}".strip
    @logger.debug line
    messages << line
  }
  @logger.info("command '#{command}' resulted in #{messages.size} lines")
  return executor.status, messages
end

#saveObject



140
141
142
143
144
145
146
147
# File 'lib/vagrantomatic/instance.rb', line 140

def save
  @logger.debug("validating settings for save...")
  validate_config
  @logger.debug("saving vm settings...")
  FileUtils.mkdir_p(vm_instance_dir)
  ensure_config
  ensure_vagrantfile
end

#startObject



206
207
208
# File 'lib/vagrantomatic/instance.rb', line 206

def start
  execute_and_log(:up)
end

#stopObject



210
211
212
# File 'lib/vagrantomatic/instance.rb', line 210

def stop
  execute_and_log(:suspend)
end

#vagrantfileObject



86
87
88
# File 'lib/vagrantomatic/instance.rb', line 86

def vagrantfile
  File.join(vm_instance_dir, VAGRANTFILE)
end

#validate_config(fatal = true) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/vagrantomatic/instance.rb', line 14

def validate_config(fatal = true)
  valid = true
  if ! @config.has_key?("box")
    valid = false
    if fatal
      raise "Node #{@name} must specify box"
    end
  end

  valid
end

#vm_instance_dirObject



82
83
84
# File 'lib/vagrantomatic/instance.rb', line 82

def vm_instance_dir
  File.join(@vagrant_vm_dir, @name)
end