Method: Fancybox2::Module::Base#on_shutdown

Defined in:
lib/fancybox2/module/base.rb

#on_shutdown(do_exit = true, &block) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/fancybox2/module/base.rb', line 132

def on_shutdown(do_exit = true, &block)
  if block_given?
    @on_shutdown = block
    return
  end

  @status = :on_shutdown

  shutdown_ok = true
  logger.debug "Received 'shutdown' command"
  # Stop sending alive messages
  @alive_task.shutdown if @alive_task

  begin
    # Call user code if any
    @on_shutdown.call if @on_shutdown
  rescue StandardError => e
    logger.error "Error during shutdown: #{e.message}"
    shutdown_ok = false
  end

  # Signal core that we've executed shutdown operations.
  # This message is not mandatory, so keep it simple
  shutdown_message = shutdown_ok ? 'ok' : 'nok'
  logger.debug "Sending shutdown message to core with status '#{shutdown_message}'"
  message_to :core, :shutdown, { status: shutdown_message }
  sleep 0.05 # Wait some time in order to be sure that the message has been published (message is not mandatory)

  Thread.new do
    if mqtt_client && mqtt_client.connected?
      # Gracefully disconnect from broker and exit
      logger.debug 'Disconnecting from broker, bye'
      mqtt_client.disconnect
      @mqtt_client = nil
    end

    if do_exit
      # Exit from process
      status_code = shutdown_ok ? 0 : 1
      logger.debug "Exiting with status code #{status_code}"
      exit status_code
    end
  end
end