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



124
125
126
127
128
129
130
131
132
133
134
# File 'ext/windows/service/daemon.rb', line 124

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



119
120
121
122
# File 'ext/windows/service/daemon.rb', line 119

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

#parse_log_level(puppet_path, cmdline_debug) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'ext/windows/service/daemon.rb', line 169

def parse_log_level(puppet_path,cmdline_debug)
  begin
    loglevel = %x{ "#{puppet_path}" agent --configprint log_level}.chomp
    unless 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



154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'ext/windows/service/daemon.rb', line 154

def parse_runinterval(puppet_path)
  begin
    runinterval = %x{ "#{puppet_path}" agent --configprint 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



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'ext/windows/service/daemon.rb', line 136

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 => e
    # Ignore all errors
  ensure
    if (!eventlog.nil?)
      eventlog.close
    end
  end
end

#service_initObject



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

def service_init
end

#service_main(*argsv) ⇒ Object



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

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
  basedir = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # 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(basedir, 'bin', 'puppet.bat')
  unless File.exists?(puppet)
    log_err("File not found: '#{puppet}'")
    return
  end
  log_debug("Using '#{puppet}'")

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

  service = self
  @run_thread = Thread.new do
    begin
      while service.running? do
        runinterval = service.parse_runinterval(puppet)
        if service.state == RUNNING or service.state == IDLE
          service.log_notice("Executing agent with arguments: #{args}")
          pid = Process.create(:command_line => "\"#{puppet}\" 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



102
103
104
# File 'ext/windows/service/daemon.rb', line 102

def service_pause
  log_notice('Service pausing')
end

#service_resumeObject



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

def service_resume
  log_notice('Service resuming')
end

#service_shutdownObject



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

def service_shutdown
  log_notice('Host shutting down')
end

#service_stopObject



97
98
99
100
# File 'ext/windows/service/daemon.rb', line 97

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