Class: Winter::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/winter/service/stop.rb,
lib/winter/service/build.rb,
lib/winter/service/start.rb,
lib/winter/service/status.rb,
lib/winter/service/validate.rb

Instance Method Summary collapse

Constructor Details

#initializeService

Returns a new instance of Service.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/winter/service/start.rb', line 26

def initialize
  #put defaults here
  @config = {}
  @config['java_home']   = ENV['JAVA_HOME'] 
  @config['service']     = 'default'
  @config['log.level']   = 1
  @config['64bit']       = true
  @config['jvm.mx']      = '1g'
  @config['console']     = '/dev/null'
  @config['web.port']    = 8080
  @config['osgi.port']   = 6070
  @config['jdb.port']    = 6071
  @config['jmx.port']    = 6072
  @config['service.conf.dir']    = "conf"

  #@config['log.dir'] = File.join(WINTERFELL_DIR,RUN_DIR,@config['service'],'logs')
  @directives = {}
end

Instance Method Details

#add_directives(dir) ⇒ Object



202
203
204
205
206
207
208
209
210
211
# File 'lib/winter/service/start.rb', line 202

def add_directives( dir )
  tmp = ""
  dir.each do |key, value|
    tmp << " -D"+Shellwords.escape(key)
    if value
      tmp << "="+Shellwords.escape(value.to_s)
    end
  end
  tmp
end

#build(winterfile, options) ⇒ Object



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
# File 'lib/winter/service/build.rb', line 23

def build(winterfile, options)
  #dsl = DSL.new options
  dsl = DSL.evaluate winterfile, options
  dependencies = dsl[:dependencies]
  service = dsl[:config]['service']
  service_dir = File.join(WINTERFELL_DIR,RUN_DIR,service)
  #$LOG.debug dependencies
  
  if options['clean'] and File.directory?(service_dir)
    s = Winter::Service.new
    stats = s.status
    if stats.size == 0
      FileUtils.rm_r service_dir
      $LOG.debug "Deleted service directory #{service_dir}"
    else
      stats.each do |srvs,status|
        if service == srvs && status !~ /running/i
          FileUtils.rm_r service_dir
          $LOG.debug "Deleted service directory #{service_dir}"
        end
      end
    end
  end
  
  #I hate waiting so this is going to become faster.
  max_threads = 10 #make this configurable later. 
  active_threads = 0 
  Signal.trap("CHLD") do 
    #Reap everything you possibly can.
    begin
      pid = waitpid(-1, Process::WNOHANG) 
      #puts "reaped #{pid}" if pid
      active_threads -= 1 if pid
      rescue Errno::ECHILD
        break 
    end while pid
  end

  dependencies.each do |dep|
    while (active_threads >= max_threads) do
      #puts "Total active threads: #{active_threads}"
      sleep 1 
    end
    active_threads += 1
    fork do 
      dep.getMaven
    end
  end
  #wait for stragglers
  sleep 1 while (active_threads > 0) 
end

#felix_log_level(level) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/winter/service/start.rb', line 217

def felix_log_level(level)
    if level =~ /[1-4]/
      return level
    end
    if !level.is_a? String
      return 1
    end
    case level.upcase
    when "ERROR"
      return 1
    when "WARN"
      return 2
    when "INFO"
      return 3
    when "DEBUG"
      return 4
    else
      return 1
    end
end

#find_javaObject



149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/winter/service/start.rb', line 149

def find_java
  if !@config['java_home'].nil? && File.exists?(File.join(@config['java_home'],'bin','java'))
    return File.join(@config['java_home'],'bin','java')
  end
  if !ENV['JAVA_HOME'].nil? && File.exists?(File.join(ENV['JAVA_HOME'],'bin','java'))
    return File.join(ENV['JAVA_HOME'],'bin','java')
  end
  env = `env java -version 2>&1`
  if env['version']
    return "java"
  end
  raise "JRE could not be found. Please set JAVA_HOME or configure java_home."
end

#generate_java_invocationObject



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/winter/service/start.rb', line 163

def generate_java_invocation
  java_bin = find_java

  felix_jar = File.join(@felix.destination,"#{@felix.artifact}-#{@felix.version}.#{@felix.package}")

  # start building the command
  cmd = [ "#{java_bin.shellescape} -server" ]
  cmd << (@config["64bit"]==true ? " -d64 -XX:+UseCompressedOops":'')
  cmd << " -XX:MaxPermSize=256m -XX:NewRatio=3"
  cmd << " -Xmx#{@config['jvm.mx']}" 
  cmd << opt("felix.fileinstall.dir", "#{@service_dir}/#{BUNDLES_DIR}")

  config_properties = File.join(@service_dir, "conf", F_CONFIG_PROPERTIES)
  cmd << opt("felix.config.properties", "file:" + config_properties)
  cmd << opt("felix.log.level", felix_log_level(@config['log.level']))

  # TODO remove these options when the logger bundle is updated to use the classpath
  logger_properties = File.join(@service_dir, "conf", F_LOGGER_PROPERTIES)
  logback_xml       = File.join(@service_dir, "conf", F_LOGBACK_XML)
  cmd << opt("log4j.configuration",       logger_properties)
  cmd << opt("logback.configurationFile", logback_xml)

  cmd << opt("web.port",         @config["web.port"])
  cmd << opt("osgi.port",        @config["osgi.port"])
  cmd << opt("log.dir",          @config['log.dir'])
  cmd << opt("service.conf.dir", File.join(@service_dir, "conf"))
  cmd << opt(OPT_BUNDLE_DIR,     "#{@service_dir}/bundles")
  cmd << add_directives( @directives )
  cmd << @config["osgi.shell.telnet.ip"]?" -Dosgi.shell.telnet.ip=#{@config["osgi.shell.telnet.ip"]}":''
  #cmd.push(add_code_coverage())
  cmd << (@config["jdb.port"] ? " -Xdebug -Xrunjdwp:transport=dt_socket,address=#{@config["jdb.port"]},server=y,suspend=n" : '')
  cmd << (@config["jmx.port"] ? " -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=#{@config["jmx.port"]} -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false" : '')
  cmd << " -cp #{@service_dir}/conf:#{felix_jar.to_s.shellescape} org.apache.felix.main.Main"
  cmd << " -b #{@service_dir}/libs"
  cmd << " #{@service_dir}/felix_cache"
    
  return cmd.join(" \\\n ")
end

#opt(key, value) ⇒ Object



213
214
215
# File 'lib/winter/service/start.rb', line 213

def opt(key, value)
  " -D#{Shellwords.escape(key.to_s)}=#{Shellwords.escape(value.to_s)}"
end

#start(winterfile, options) ⇒ Object



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
# File 'lib/winter/service/start.rb', line 45

def start(winterfile, options)
  dsl = DSL.evaluate winterfile, options
  dsl[:dependencies].each do |dep|
    $LOG.debug "dependency: #{dep.group}.#{dep.artifact}"
  end
  @felix = dsl[:felix]

  @config.merge! dsl[:config] # add Winterfile 'directive' commands
  @config.merge! options # overwrite @config with command-line options
  @config.each do |k,v|
    k = k.shellescape if k.is_a? String
    v = v.shellescape if v.is_a? String
  end
  $LOG.debug @config

  @service_dir = File.join(File.split(winterfile)[0],RUN_DIR,@config['service']).shellescape

  @config['log.dir'] = File.join(@service_dir,'logs')

  @directives.merge! dsl[:directives]

  java_cmd = generate_java_invocation
  java_cmd << " > #{@config['console']} 2>&1"
  $LOG.debug java_cmd

  # execute
  if( File.exists?(File.join(@service_dir, "pid")) )
    $LOG.error "PID file already exists. Is the process running?"
    exit
  end
  pid_file = File.open(File.join(@service_dir, "pid"), "w")

  # Normally, we'd just use Process.daemon for ruby 1.9, but for some
  # reason the OSGi container we're using crashes when the CWD is changed
  # to '/'. So, we'll just leave the CWD alone.
  #Process.daemon(Dir.getwd,nil)

  java_pid = fork do
    exec(java_cmd)
  end

  pid = java_pid
  pid = Process.pid if @config['daemonize'] 
  pid_file.write(pid)
  pid_file.close      

  $LOG.info "Started #{@config['service']} (#{pid})"

  if( @config['daemonize'] )
    stay_resident(java_pid,winterfile)
  end
end

#statusObject



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
# File 'lib/winter/service/status.rb', line 21

def status
  pid_files = Dir.glob(File.join(WINTERFELL_DIR,RUN_DIR, "**", "pid"))
  if( pid_files.length == 0 )
    #$LOG.info "No services are running."
    return {}
  end

  services = {}
  
  pid_files.each do |f_pid|
    service = f_pid.sub( %r{#{WINTERFELL_DIR}/#{RUN_DIR}/([^/]+)/pid}, '\1')
    pid_file = File.open(f_pid, "r")
    pid = pid_file.read().to_i
  
    begin
      Process.getpgid( pid )
      running = "Running"
    rescue Errno::ESRCH
      running = "Dangling pid file : #{f_pid}"
    end

    services["#{service} (#{pid})"] = "#{running}"
  end

  return services
end

#stay_resident(child_pid, winterfile) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
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
141
142
143
144
145
146
147
# File 'lib/winter/service/start.rb', line 98

def stay_resident( child_pid, winterfile )
  interrupted = false

  #TERM, CONT STOP HUP ALRM INT and KILL
  Signal.trap("EXIT") do
    $LOG.debug "EXIT Terminating... #{$$}"
    interrupted = true
    begin
      stop winterfile
     # not working...
     # Process.getpgid child_pid 
     # Process.kill child_pid #skipped if process is alredy dead
    rescue
      $LOG.debug "Child pid (#{child_pid}) is already gone."
    end
  end
  Signal.trap("HUP") do
    $LOG.debug "HUP Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("TERM") do
    $LOG.debug "TERM Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("KILL") do
    $LOG.debug "KILL Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("CONT") do
    $LOG.debug "CONT Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("ALRM") do
    $LOG.debug "ALRM Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("INT") do
    $LOG.debug "INT Terminating... #{$$}"
    interrupted = true
  end
  Signal.trap("CHLD") do
    $LOG.debug "CHLD Terminating... #{$$}"
    interrupted = true
  end
  #Process.detach(pid)

  while 1
    exit 0 if interrupted
  end
end

#stop(winterfile = 'Winterfile', options = {}) ⇒ Object

stop winterfell service



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
# File 'lib/winter/service/stop.rb', line 22

def stop(winterfile='Winterfile', options={})
  tmp = DSL.evaluate winterfile, options
  config = tmp[:config]
  service = config['service']

  @service_dir = File.join(File.split(winterfile)[0],RUN_DIR,service)
  f_pid = File.join(@service_dir, "pid")

  if File.exists?(f_pid)
    pid = nil;
    File.open(f_pid, "r") do |f|
      pid = f.read().to_i
    end

    begin
      Process.getpgid pid
      Process.kill("TERM", -Process.getpgid(pid))
    rescue
      $LOG.info( "Process #{pid} does not exist. Removing pid file." )
    end

    begin
      File.unlink(f_pid)
    rescue
      $LOG.error( "Error deleting PID file." )
    end
  else
    $LOG.error("Failed to find process Id file: #{f_pid}")
    false
  end
  true
end

#validate(winterfile = 'Winterfile', options = {}) ⇒ Object



21
22
23
# File 'lib/winter/service/validate.rb', line 21

def validate( winterfile='Winterfile', options={} )
  DSL.evaluate winterfile, options
end