Class: Pocketknife::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/pocketknife/node.rb

Overview

Node

A node represents a remote computer that will be managed with Pocketknife and chef-solo. It can connect to a node, execute commands on it, install the stack, and upload and apply configurations to it.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, pocketknife) ⇒ Node

Initialize a new node.

Parameters:

  • name (String)

    A node name.

  • pocketknife (Pocketknife)


22
23
24
25
26
# File 'lib/pocketknife/node.rb', line 22

def initialize(name, pocketknife)
  self.name = name
  self.pocketknife = pocketknife
  self.connection_cache = nil
end

Instance Attribute Details

#connection_cacheRye::Box

Returns The Rye::Box connection, cached by #connection.

Returns:

  • (Rye::Box)

    The Rye::Box connection, cached by #connection.



13
14
15
# File 'lib/pocketknife/node.rb', line 13

def connection_cache
  @connection_cache
end

#nameString

Returns Name of the node.

Returns:

  • (String)

    Name of the node.



7
8
9
# File 'lib/pocketknife/node.rb', line 7

def name
  @name
end

#platform_cacheHash{Symbol => String, Numeric}

Returns Information about platform, cached by #platform.

Returns:

  • (Hash{Symbol => String, Numeric})

    Information about platform, cached by #platform.



16
17
18
# File 'lib/pocketknife/node.rb', line 16

def platform_cache
  @platform_cache
end

#pocketknifePocketknife

Returns The Pocketknife this node is associated with.

Returns:

  • (Pocketknife)

    The Pocketknife this node is associated with.



10
11
12
# File 'lib/pocketknife/node.rb', line 10

def pocketknife
  @pocketknife
end

Class Method Details

.cleanup_uploadvoid

This method returns an undefined value.

Cleans up cache of shared files uploaded to all nodes. This cache is created by the prepare_upload method.



237
238
239
240
241
242
243
244
245
246
# File 'lib/pocketknife/node.rb', line 237

def self.cleanup_upload
  # TODO make this an instance method so it can avoid creating a tarball if using :rsync
  [
    TMP_TARBALL,
    TMP_SOLO_RB,
    TMP_CHEF_SOLO_APPLY
  ].each do |path|
    path.unlink if path.exist?
  end
end

.prepare_upload { ... } ⇒ void

This method returns an undefined value.

Prepares an upload, by creating a cache of shared files used by all nodes.

IMPORTANT: This will create files and leave them behind. You should use the block syntax or manually call cleanup_upload when done.

If an optional block is supplied, calls cleanup_upload automatically when done. This is typically used like:

Node.prepare_upload do
  mynode.upload
end

Yields:

  • to execute the block, will prepare upload before block is invoked, and cleanup the temporary files afterwards.



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/pocketknife/node.rb', line 199

def self.prepare_upload(&block)
  # TODO make this an instance method so it can avoid creating a tarball if using :rsync
  begin
    # TODO either do this in memory or scope this to the PID to allow concurrency
    TMP_SOLO_RB.open("w") {|h| h.write(SOLO_RB_CONTENT)}
    TMP_CHEF_SOLO_APPLY.open("w") {|h| h.write(CHEF_SOLO_APPLY_CONTENT)}
    TMP_TARBALL.open("w") do |handle|
      items = [
        VAR_POCKETKNIFE_COOKBOOKS.basename,
        VAR_POCKETKNIFE_SITE_COOKBOOKS.basename,
        VAR_POCKETKNIFE_ROLES.basename,
        VAR_POCKETKNIFE_DATA_BAGS.basename,
        TMP_SOLO_RB,
        TMP_CHEF_SOLO_APPLY
      ].reject { |o| not File.exist?(o) }.map {|o| o.to_s}

      Archive::Tar::Minitar.pack(
        items,
        handle
      )
    end
  rescue Exception => e
    cleanup_upload
    raise e
  end

  if block
    begin
      yield(self)
    ensure
      cleanup_upload
    end
  end
end

Instance Method Details

#applyvoid

This method returns an undefined value.

Applies the configuration to the node. Installs Chef, Ruby and Rubygems if needed.



348
349
350
351
352
353
354
355
356
357
# File 'lib/pocketknife/node.rb', line 348

def apply
  self.install

  self.say("Applying configuration...", true)
  command = "chef-solo -j #{NODE_JSON.shellescape}"
  command << " -o #{self.pocketknife.runlist}" if self.pocketknife.runlist
  command << " -l debug" if self.pocketknife.verbosity == true
  self.execute(command, true)
  self.say("Finished applying!")
end

#connectionRye::Box

Returns a connection.

Caches result to #connection_cache.

Returns:

  • (Rye::Box)


33
34
35
36
37
38
39
# File 'lib/pocketknife/node.rb', line 33

def connection
  return self.connection_cache ||= begin
      rye = Rye::Box.new(self.name, :user => "root")
      rye.disable_safe_mode
      rye
    end
end

#deployvoid

This method returns an undefined value.

Deploys the configuration to the node, which calls #upload and #apply.



362
363
364
365
# File 'lib/pocketknife/node.rb', line 362

def deploy
  self.upload
  self.apply
end

#execute(commands, immediate = false) ⇒ Rye::Rap

Executes commands on the external node.

Parameters:

  • commands (String)

    Shell commands to execute.

  • immediate (Boolean) (defaults to: false)

    Display execution information immediately to STDOUT, rather than returning it as an object when done.

Returns:

  • (Rye::Rap)

    A result object describing the completed execution.

Raises:

  • (ExecutionError)

    Something went wrong with the execution, the cause is described in the exception.



373
374
375
376
377
378
379
380
381
382
383
# File 'lib/pocketknife/node.rb', line 373

def execute(commands, immediate=false)
  self.say("Executing:\n#{commands}", false)
  if immediate
    self.connection.stdout_hook {|line| puts line}
  end
  return self.connection.execute("(#{commands}) 2>&1")
rescue Rye::Err => e
  raise Pocketknife::ExecutionError.new(self.name, commands, e, immediate)
ensure
  self.connection.stdout_hook = nil
end

#has_executable?(executable) ⇒ Boolean

Does this node have the given executable?

Parameters:

  • executable (String)

    A name of an executable, e.g. chef-solo.

Returns:

  • (Boolean)

    Has executable?



61
62
63
64
65
66
67
68
# File 'lib/pocketknife/node.rb', line 61

def has_executable?(executable)
  begin
    self.connection.execute(%{which #{executable.shellescape} && test -x `which #{executable.shellescape}`})
    return true
  rescue Rye::Err
    return false
  end
end

#installvoid

This method returns an undefined value.

Installs Chef and its dependencies on a node if needed.

Raises:



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
# File 'lib/pocketknife/node.rb', line 109

def install
  unless self.has_executable?("chef-solo")
    case self.pocketknife.can_install
    when nil
      # Prompt for installation
      print "? #{self.name}: Chef not found. Install it and its dependencies? (Y/n) "
      STDOUT.flush
      answer = STDIN.gets.chomp
      case answer
      when /^y/i, ''
        # Continue with install
      else
        raise NotInstalling.new("Chef isn't installed on node '#{self.name}', but user doesn't want to install it.", self.name)
      end
    when true
      # User wanted us to install
    else
      # Don't install
      raise NotInstalling.new("Chef isn't installed on node '#{self.name}', but user doesn't want to install it.", self.name)
    end

    unless self.has_executable?("ruby")
      self.install_ruby
    end

    unless self.has_executable?("gem")
      self.install_rubygems
    end

    self.install_chef
  end
end

#install_chefvoid

This method returns an undefined value.

Installs Chef on the remote node.



145
146
147
148
149
# File 'lib/pocketknife/node.rb', line 145

def install_chef
  self.say("Installing chef...")
  self.execute("gem install --no-rdoc --no-ri chef", true)
  self.say("Installed chef", false)
end

#install_rubyvoid

This method returns an undefined value.

Installs Ruby on the remote node.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/pocketknife/node.rb', line 171

def install_ruby
  command = \
    case self.platform[:distributor].downcase
    when /ubuntu/, /debian/, /gnu\/linux/
      "DEBIAN_FRONTEND=noninteractive apt-get --yes install ruby ruby-dev libopenssl-ruby irb build-essential wget ssl-cert"
    when /centos/, /red hat/, /scientific linux/
      "yum -y install ruby ruby-shadow gcc gcc-c++ ruby-devel wget"
    else
      raise UnsupportedInstallationPlatform.new("Can't install on node '#{self.name}' with unknown distrubtor: `#{self.platform[:distrubtor]}`", self.name)
    end

  self.say("Installing ruby...")
  self.execute(command, true)
  self.say("Installed ruby", false)
end

#install_rubygemsvoid

This method returns an undefined value.

Installs Rubygems on the remote node.



154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/pocketknife/node.rb', line 154

def install_rubygems
  self.say("Installing rubygems...")
  self.execute(<<-HERE, true)
cd /root &&
  rm -rf rubygems-1.3.7 rubygems-1.3.7.tgz &&
  wget http://production.cf.rubygems.org/rubygems/rubygems-1.3.7.tgz &&
  tar zxf rubygems-1.3.7.tgz &&
  cd rubygems-1.3.7 &&
  ruby setup.rb --no-format-executable &&
  rm -rf rubygems-1.3.7 rubygems-1.3.7.tgz
  HERE
  self.say("Installed rubygems", false)
end

#local_node_json_pathnamePathname

Returns path to this node’s nodes/NAME.json file, used as node.json by chef-solo.

Returns:

  • (Pathname)


53
54
55
# File 'lib/pocketknife/node.rb', line 53

def local_node_json_pathname
  return Pathname.new("nodes") + "#{self.name}.json"
end

#platformHash{Symbol => String, Numeric}

Returns information describing the node.

The information is formatted similar to this:

{
  :distributor => "Ubuntu", # String with distributor name
  :codename => "maverick", # String with release codename
  :release => "10.10", # String with release number
  :version => 10.1 # Float with release number
}

Returns:

  • (Hash{Symbol => String, Numeric})

    Return a hash describing the node, see above.

Raises:



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/pocketknife/node.rb', line 82

def platform
  return self.platform_cache ||= begin
    lsb_release = "/etc/lsb-release"
    begin
      output = self.connection.cat(lsb_release).to_s
      result = {}
      result[:distributor] = output[/DISTRIB_ID\s*=\s*(.+?)$/, 1]
      result[:release] = output[/DISTRIB_RELEASE\s*=\s*(.+?)$/, 1]
      result[:codename] = output[/DISTRIB_CODENAME\s*=\s*(.+?)$/, 1]
      result[:version] = result[:release].to_f

      if result[:distributor] && result[:release] && result[:codename] && result[:version]
        return result
      else
        raise UnsupportedInstallationPlatform.new("Can't install on node '#{self.name}' with invalid '#{lsb_release}' file", self.name)
      end
    rescue Rye::Err
      raise UnsupportedInstallationPlatform.new("Can't install on node '#{self.name}' without '#{lsb_release}'", self.name)
    end
  end
end

#rsync(*args) ⇒ void

This method returns an undefined value.

Rsync files to a node.

Parameters:

  • args (Array)

    Arguments to sent to rsync, e.g. options, filenames, and target.

Raises:

  • (RsyncError)

    Something went wrong with the rsync.



253
254
255
256
257
258
# File 'lib/pocketknife/node.rb', line 253

def rsync(*args)
  command = ['rsync', *args.map{|o| o.shellescape}]
  unless system *command
    raise Pocketknife::RsyncError.new(command.join(' '), self.name)
  end
end

#rsync_directory(*args) ⇒ void

This method returns an undefined value.

Rsync directory to a node with options: --recursive --update --copy-links --delete

Parameters:

  • args (Array)

    Arguments to sent to rsync, e.g. options, directory name, and target.

Raises:

  • (RsyncError)

    Something went wrong with the rsync.



274
275
276
# File 'lib/pocketknife/node.rb', line 274

def rsync_directory(*args)
  self.rsync("-ruL", "--delete", *args)
end

#rsync_file(*args) ⇒ void

This method returns an undefined value.

Rsync a file to a node with options: --update --copy-links

Parameters:

  • args (Array)

    Arguments to sent to rsync, e.g. options, filename, and target.

Raises:

  • (RsyncError)

    Something went wrong with the rsync.



265
266
267
# File 'lib/pocketknife/node.rb', line 265

def rsync_file(*args)
  self.rsync("-uL", *args)
end

#say(message, importance = nil) ⇒ void

This method returns an undefined value.

Displays status message.

Parameters:

  • message (String)

    The message to display.

  • importance (Boolean) (defaults to: nil)

    How important is this? true means important, nil means normal, false means unimportant.



46
47
48
# File 'lib/pocketknife/node.rb', line 46

def say(message, importance=nil)
  self.pocketknife.say("* #{self.name}: #{message}", importance)
end

#uploadvoid

This method returns an undefined value.

Uploads configuration information to node.

IMPORTANT: You must first call prepare_upload to create the shared files that will be uploaded.



283
284
285
286
287
288
289
290
291
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/pocketknife/node.rb', line 283

def upload
  self.say("Uploading configuration...")

  self.say("Removing old files...", false)
  self.execute <<-HERE
umask 0377 &&
  rm -rf #{ETC_CHEF.shellescape} #{VAR_POCKETKNIFE.shellescape} #{VAR_POCKETKNIFE_CACHE.shellescape} #{CHEF_SOLO_APPLY.shellescape} #{CHEF_SOLO_APPLY_ALIAS.shellescape} &&
  mkdir -p #{ETC_CHEF.shellescape} #{VAR_POCKETKNIFE.shellescape} #{VAR_POCKETKNIFE_CACHE.shellescape} #{CHEF_SOLO_APPLY.dirname.shellescape}
  HERE

  case self.pocketknife.transfer_mechanism
  when :tar
    self.say("Uploading new files...", false)
    self.connection.file_upload(self.local_node_json_pathname.to_s, NODE_JSON.to_s)
    self.connection.file_upload(TMP_TARBALL.to_s, VAR_POCKETKNIFE_TARBALL.to_s)

    self.say("Installing new files...", false)
    self.execute <<-HERE, true
cd #{VAR_POCKETKNIFE_CACHE.shellescape} &&
  tar xf #{VAR_POCKETKNIFE_TARBALL.shellescape} &&
  chmod -R u+rwX,go= . &&
  chown -R root:root . &&
  mv #{TMP_SOLO_RB.shellescape} #{SOLO_RB.shellescape} &&
  mv #{TMP_CHEF_SOLO_APPLY.shellescape} #{CHEF_SOLO_APPLY.shellescape} &&
  chmod u+x #{CHEF_SOLO_APPLY.shellescape} &&
  ln -s #{CHEF_SOLO_APPLY.basename.shellescape} #{CHEF_SOLO_APPLY_ALIAS.shellescape} &&
  rm #{VAR_POCKETKNIFE_TARBALL.shellescape} &&
  mv * #{VAR_POCKETKNIFE.shellescape}
    HERE

  when :rsync
    self.say("Uploading new files...", false)

    self.rsync_file("#{self.local_node_json_pathname}", "root@#{self.name}:#{NODE_JSON}")

    %w[SOLO_RB CHEF_SOLO_APPLY].each do |fragment|
      source = self.class.const_get("TMP_#{fragment}")
      target = self.class.const_get(fragment)
      self.rsync_file("#{source}", "root@#{self.name}:#{target}")
    end

    %w[COOKBOOKS SITE_COOKBOOKS ROLES DATA_BAGS].each do |fragment|
      target = self.class.const_get("VAR_POCKETKNIFE_#{fragment}")
      source = target.basename
      next unless source.exist?
      self.rsync_directory("#{source}/", "root@#{self.name}:#{target}")
    end

    self.say("Modifying new files...", false)
    self.execute <<-HERE, true
cd #{VAR_POCKETKNIFE_CACHE.shellescape} &&
  chmod u+x #{CHEF_SOLO_APPLY.shellescape} &&
  ln -s #{CHEF_SOLO_APPLY.basename.shellescape} #{CHEF_SOLO_APPLY_ALIAS.shellescape}
    HERE

  else
    raise InvalidTransferMechanism.new(self.pocketknife.transfer_mechanism)
  end

  self.say("Finished uploading!", false)
end