summaryrefslogtreecommitdiffstats
path: root/lib/puppet/run.rb
blob: 150e644a012ed27271823e510f25f8784d837495 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
require 'puppet/agent'
require 'puppet/configurer'
require 'puppet/indirector'

# A basic class for running the agent.  Used by
# puppetrun to kick off agents remotely.
class Puppet::Run
  extend Puppet::Indirector
  indirects :run, :terminus_class => :local

  attr_reader :status, :background, :options

  def agent
    Puppet::Agent.new(Puppet::Configurer)
  end

  def background?
    background
  end

  def initialize(options = {})
    if options.include?(:background)
      @background = options[:background]
      options.delete(:background)
    end

    valid_options = [:tags, :ignoreschedules]
    options.each do |key, value|
      raise ArgumentError, "Run does not accept #{key}" unless valid_options.include?(key)
    end

    @options = options
  end

  def log_run
    msg = ""
    msg += "triggered run" % if options[:tags]
      msg += " with tags #{options[:tags].inspect}"
    end

    msg += " ignoring schedules" if options[:ignoreschedules]

    Puppet.notice msg
  end

  def run
    if agent.running?
      @status = "running"
      return self
    end

    log_run

    if background?
      Thread.new { agent.run(options) }
    else
      agent.run(options)
    end

    @status = "success"

    self
  end

  def self.from_pson( pson )
    options = {}
    pson.each do |key, value|
      options[key.to_sym] = value
    end

    new(options)
  end

  def to_pson
    @options.merge(:background => @background).to_pson
  end
end