Class: WindowsDaemon

Inherits:
Win32::Daemon
  • Object
show all
Defined in:
ext/windows/service/daemon.rb

Constant Summary collapse

CREATE_NEW_CONSOLE =
0x00000010
LOG_FILE =
File.expand_path(File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'puppet', 'var', 'log', 'windows.log'))
LEVELS =
[:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit]

Instance Method Summary collapse

Instance Method Details

#log(msg, level) ⇒ Object


131
132
133
134
135
136
137
138
139
140
141
# File 'ext/windows/service/daemon.rb', line 131

def log(msg, level)
  if LEVELS.index(level) >= @loglevel
    if (@LOG_TO_FILE)
      # without this change its possible that we get Encoding errors trying to write UTF-8 messages in current codepage
      File.open(LOG_FILE, 'a:UTF-8') { |f| f.puts("#{Time.now} Puppet (#{level}): #{msg}") }
    end

    native_type, native_id = Puppet::Util::Windows::EventLog.to_native(level)
    report_windows_event(native_type, native_id, msg.to_s)
  end
end

#log_exception(e) ⇒ Object

Interrogation handler is just for debug. Can be commented out or removed entirely. def service_interrogate

log_debug('Service is being interrogated')

end


126
127
128
129
# File 'ext/windows/service/daemon.rb', line 126

def log_exception(e)
  log_err(e.message)
  log_err(e.backtrace.join("\n"))
end

#parse_log_level(puppet_path, cmdline_debug) ⇒ Object


176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'ext/windows/service/daemon.rb', line 176

def parse_log_level(puppet_path,cmdline_debug)
  begin
    loglevel = %x{ #{puppet_path} config --section agent --log_level notice print log_level }.chomp
    unless loglevel && respond_to?("log_#{loglevel}")
      loglevel = :notice
      log_err("Failed to determine loglevel, defaulting to #{loglevel}")
    end
  rescue Exception => e
    log_exception(e)
    loglevel = :notice
  end

  LEVELS.index(cmdline_debug ? cmdline_debug : loglevel.to_sym)
end

#parse_runinterval(puppet_path) ⇒ Object


161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'ext/windows/service/daemon.rb', line 161

def parse_runinterval(puppet_path)
  begin
    runinterval = %x{ #{puppet_path} config --section agent --log_level notice print runinterval }.to_i
    if runinterval == 0
      runinterval = 1800
      log_err("Failed to determine runinterval, defaulting to #{runinterval} seconds")
    end
  rescue Exception => e
    log_exception(e)
    runinterval = 1800
  end

  runinterval
end

#report_windows_event(type, id, message) ⇒ Object


143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'ext/windows/service/daemon.rb', line 143

def report_windows_event(type,id,message)
  begin
    eventlog = nil
    eventlog = Puppet::Util::Windows::EventLog.open("Puppet")
    eventlog.report_event(
      :event_type  => type,   # EVENTLOG_ERROR_TYPE, etc
      :event_id    => id,     # 0x01 or 0x02, 0x03 etc.
      :data        => message # "the message"
    )
  rescue Exception
    # Ignore all errors
  ensure
    if (!eventlog.nil?)
      eventlog.close
    end
  end
end

#service_initObject


27
28
# File 'ext/windows/service/daemon.rb', line 27

def service_init
end

#service_main(*argsv) ⇒ Object


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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'ext/windows/service/daemon.rb', line 30

def service_main(*argsv)
  argsv = (argsv << ARGV).flatten.compact
  args = argsv.join(' ')
  @loglevel = LEVELS.index(argsv.index('--debug') ? :debug : :notice)

  @LOG_TO_FILE = (argsv.index('--logtofile') ? true : false)

  if (@LOG_TO_FILE)
    FileUtils.mkdir_p(File.dirname(LOG_FILE))
    args = args.gsub("--logtofile","")
  end

  base_dir = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  load_env(base_dir)

  # The puppet installer registers a 'Puppet' event source.  For the moment events will be logged with this key, but
  # it may be a good idea to split the Service and Puppet events later so it's easier to read in the windows Event Log.
  #
  # Example code to register an event source;
  # eventlogdll =  File.expand_path(File.join(basedir, 'puppet', 'ext', 'windows', 'eventlog', 'puppetres.dll'))
  # if (File.exists?(eventlogdll))
  #   Win32::EventLog.add_event_source(
  #      'source' => "Application",
  #      'key_name' => "Puppet Agent",
  #      'category_count' => 3,
  #      'event_message_file' => eventlogdll,
  #      'category_message_file' => eventlogdll
  #   )
  # end

  puppet = File.join(base_dir, 'puppet', 'bin', 'puppet')
  ruby = File.join(base_dir, 'puppet', 'bin', 'ruby.exe')
  ruby_puppet_cmd = "\"#{ruby}\" \"#{puppet}\""

  unless File.exist?(puppet)
    log_err("File not found: '#{puppet}'")
    return
  end
  log_debug("Using '#{puppet}'")

  cmdline_debug = argsv.index('--debug') ? :debug : nil
  @loglevel = parse_log_level(ruby_puppet_cmd, cmdline_debug)
  log_notice('Service started')

  service = self
  @run_thread = Thread.new do
    begin
      while service.running? do
        runinterval = service.parse_runinterval(ruby_puppet_cmd)

        if service.state == RUNNING or service.state == IDLE
          service.log_notice("Executing agent with arguments: #{args}")
          pid = Process.create(:command_line => "#{ruby_puppet_cmd} agent --onetime #{args}", :creation_flags => CREATE_NEW_CONSOLE).process_id
          service.log_debug("Process created: #{pid}")
        else
          service.log_debug("Service is paused.  Not invoking Puppet agent")
        end

        service.log_debug("Service worker thread waiting for #{runinterval} seconds")
        sleep(runinterval)
        service.log_debug('Service worker thread woken up')
      end
    rescue Exception => e
      service.log_exception(e)
    end
  end
  @run_thread.join

rescue Exception => e
  log_exception(e)
ensure
  log_notice('Service stopped')
end

#service_pauseObject


109
110
111
# File 'ext/windows/service/daemon.rb', line 109

def service_pause
  log_notice('Service pausing')
end

#service_resumeObject


113
114
115
# File 'ext/windows/service/daemon.rb', line 113

def service_resume
  log_notice('Service resuming')
end

#service_shutdownObject


117
118
119
# File 'ext/windows/service/daemon.rb', line 117

def service_shutdown
  log_notice('Host shutting down')
end

#service_stopObject


104
105
106
107
# File 'ext/windows/service/daemon.rb', line 104

def service_stop
  log_notice('Service stopping / killing worker thread')
  @run_thread.kill if @run_thread
end