Class: OpenC3::Microservice

Inherits:
Object show all
Defined in:
lib/openc3/microservices/microservice.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, is_plugin: false) ⇒ Microservice

Returns a new instance of Microservice.



84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
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
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
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/openc3/microservices/microservice.rb', line 84

def initialize(name, is_plugin: false)
  @shutdown_complete = false
  raise "Microservice must be named" unless name

  @name = name
  split_name = name.split("__")
  raise "Name #{name} doesn't match convention of SCOPE__TYPE__NAME" if split_name.length != 3
  microservice_type = split_name[1].to_s.upcase

  @scope = split_name[0]
  $openc3_scope = @scope
  @cancel_thread = false
  @metric = Metric.new(microservice: @name, scope: @scope)
  Logger.scope = @scope
  Logger.microservice_name = @name
  @logger = Logger.new
  @logger.scope = @scope
  @logger.microservice_name = @name
  @secrets = Secrets.getClient

  OpenC3.setup_open_telemetry(@name, false)

  @temp_dir = OpenC3.sanitize_path(File.join(Dir.tmpdir, @name))

  # Create temp folder for this microservice
  # This will already have been setup by plugin_microservice.rb if USER
  if is_plugin or microservice_type != 'USER'
    FileUtils.remove_entry_secure(@temp_dir, true)
    Dir.mkdir(@temp_dir)
  end

  # Get microservice configuration from Redis
  @config = MicroserviceModel.get(name: @name, scope: @scope)
  if @config
    @topics = @config['topics']
    @plugin = @config['plugin']
    if @config['secrets']
      @secrets.setup(@config['secrets'])
    end
  else
    @config = {}
    @plugin = nil
  end
  @logger.info("Microservice initialized with config:\n#{@config}")
  @topics ||= []
  @microservice_topic = "MICROSERVICE__#{@name}"
  @db_shard = (@config['db_shard'] || 0).to_i

  # Get configuration for any targets
  @target_names = @config["target_names"]
  @target_names ||= []
  # NOTE: setup_targets doesn't do anything if @target_names is empty
  System.setup_targets(@target_names, @temp_dir, scope: @scope) unless is_plugin

  # Use at_exit to shutdown cleanly no matter how we die
  at_exit do
    shutdown()
  end

  @count = 0
  @error = nil
  @custom = nil
  @state = 'INITIALIZED'
  @work_dir = @config["work_dir"]

  if is_plugin
    cmd_array = @config["cmd"]

    # Get Microservice files from bucket storage
    bucket = ENV['OPENC3_CONFIG_BUCKET']
    client = Bucket.getClient()

    prefix = "#{@scope}/microservices/#{@name}/"
    file_count = 0
    client.list_objects(bucket: bucket, prefix: prefix).each do |object|
      response_target = OpenC3.sanitize_path(File.join(@temp_dir, object.key.split(prefix)[-1]))
      FileUtils.mkdir_p(File.dirname(response_target))
      client.get_object(bucket: bucket, key: object.key, path: response_target)
      file_count += 1
    end

    # Adjust @work_dir to microservice files downloaded if files and a relative path
    if file_count > 0 and @work_dir[0] != '/'
      @work_dir = OpenC3.sanitize_path(File.join(@temp_dir, @work_dir))
    end

    # Check Syntax on any ruby files
    ruby_filename = nil
    cmd_array.each do |part|
      if /\.rb$/.match?(part)
        ruby_filename = part
        break
      end
    end
    if ruby_filename
      OpenC3.set_working_dir(@work_dir) do
        if File.exist?(ruby_filename)
          # Run ruby syntax so we can log those
          syntax_check, _ = Open3.capture2e("ruby -c #{ruby_filename}")
          if /Syntax OK/.match?(syntax_check)
            @logger.debug("Ruby microservice #{@name} file #{ruby_filename} passed syntax check\n", scope: @scope)
          else
            @logger.error("Ruby microservice #{@name} file #{ruby_filename} failed syntax check\n#{syntax_check}", scope: @scope)
          end
        else
          @logger.error("Ruby microservice #{@name} file #{ruby_filename} does not exist", scope: @scope)
        end
      end
    end
  else
    @microservice_status_sleeper = Sleeper.new
    @microservice_status_period_seconds = 5
    @microservice_status_thread = Thread.new do
      until @cancel_thread
        MicroserviceStatusModel.set(as_json(), scope: @scope) unless @cancel_thread
        break if @microservice_status_sleeper.sleep(@microservice_status_period_seconds)
      end
    rescue Exception => e
      begin
        @logger.error "#{@name} status thread died: #{e.formatted}"
      rescue Exception
        # If logging also fails (e.g. Redis unavailable), print to stderr
        $stderr.puts "#{@name} status thread died: #{e.formatted}"
      end
      raise e
    end
    ThreadManager.instance.register(@microservice_status_thread)
  end
end

Instance Attribute Details

#countObject

Returns the value of attribute count.



38
39
40
# File 'lib/openc3/microservices/microservice.rb', line 38

def count
  @count
end

#customObject

Returns the value of attribute custom.



40
41
42
# File 'lib/openc3/microservices/microservice.rb', line 40

def custom
  @custom
end

#errorObject

Returns the value of attribute error.



39
40
41
# File 'lib/openc3/microservices/microservice.rb', line 39

def error
  @error
end

#loggerObject

Returns the value of attribute logger.



42
43
44
# File 'lib/openc3/microservices/microservice.rb', line 42

def logger
  @logger
end

#microservice_status_threadObject

Returns the value of attribute microservice_status_thread.



35
36
37
# File 'lib/openc3/microservices/microservice.rb', line 35

def microservice_status_thread
  @microservice_status_thread
end

#nameObject

Returns the value of attribute name.



36
37
38
# File 'lib/openc3/microservices/microservice.rb', line 36

def name
  @name
end

#scopeObject

Returns the value of attribute scope.



41
42
43
# File 'lib/openc3/microservices/microservice.rb', line 41

def scope
  @scope
end

#secretsObject

Returns the value of attribute secrets.



43
44
45
# File 'lib/openc3/microservices/microservice.rb', line 43

def secrets
  @secrets
end

#stateObject

Returns the value of attribute state.



37
38
39
# File 'lib/openc3/microservices/microservice.rb', line 37

def state
  @state
end

Class Method Details

.run(name = nil) ⇒ 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
# File 'lib/openc3/microservices/microservice.rb', line 45

def self.run(name = nil)
  name = ENV['OPENC3_MICROSERVICE_NAME'] unless name
  microservice = self.new(name)
  thread = Thread.new do
    begin
      MicroserviceStatusModel.set(microservice.as_json(), scope: microservice.scope)
      microservice.state = 'RUNNING'
      microservice.run
      Logger.info("Microservice #{name} run method returned cleanly and will now shutdown.")
      microservice.state = 'FINISHED'
    rescue Exception => e
      if SystemExit === e or SignalException === e
        microservice.state = 'KILLED'
      else
        microservice.error = e
        microservice.state = 'DIED_ERROR'
        Logger.fatal("Microservice #{name} dying from exception\n#{e.formatted}")
      end
      microservice.shutdown # Dying in crash so should try to shutdown
    ensure
      MicroserviceStatusModel.set(microservice.as_json(), scope: microservice.scope)
    end
  end
  ThreadManager.instance.register(thread, shutdown_object: microservice)
  ThreadManager.instance.monitor
  ThreadManager.instance.shutdown
end

Instance Method Details

#as_json(*a) ⇒ Object



73
74
75
76
77
78
79
80
81
82
# File 'lib/openc3/microservices/microservice.rb', line 73

def as_json(*a)
  {
    'name' => @name,
    'state' => @state,
    'count' => @count,
    'error' => @error.as_json(*a),
    'custom' => @custom.as_json(*a),
    'plugin' => @plugin,
  }
end

#microservice_cmd(topic, msg_id, msg_hash, _redis) ⇒ Object

Returns if the command was handled



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/openc3/microservices/microservice.rb', line 252

def microservice_cmd(topic, msg_id, msg_hash, _redis)
  command = msg_hash['command']
  if command == 'ADD_TOPICS'
    topics = JSON.parse(msg_hash['topics'])
    if topics and Array === topics
      topics.each do |new_topic|
        @topics << new_topic unless @topics.include?(new_topic)
      end
    else
      raise "Invalid topics given to microservice_cmd: #{topics}"
    end
    Topic.trim_topic(topic, msg_id, db_shard: @db_shard)
    return true
  end
  Topic.trim_topic(topic, msg_id, db_shard: @db_shard)
  return false
end

#runObject

Must be implemented by a subclass



215
216
217
# File 'lib/openc3/microservices/microservice.rb', line 215

def run
  shutdown()
end

#setup_microservice_topicObject



244
245
246
247
248
249
# File 'lib/openc3/microservices/microservice.rb', line 244

def setup_microservice_topic
  @topics.append(@microservice_topic)
  Thread.current[:topic_offsets] ||= {}
  topic_offsets = Thread.current[:topic_offsets]
  topic_offsets[@microservice_topic] = "0-0" # Always get all available
end

#shutdown(state = 'STOPPED') ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/openc3/microservices/microservice.rb', line 219

def shutdown(state = 'STOPPED')
  return if @shutdown_complete
  begin
    @logger.info("Shutting down microservice: #{@name}")
  rescue Exception
    # Ignore logging failures during shutdown (e.g. Redis unavailable)
  end
  @state = state
  @cancel_thread = true
  @microservice_status_sleeper.cancel if @microservice_status_sleeper
  begin
    MicroserviceStatusModel.set(as_json(), scope: @scope)
  rescue Exception
    # Ignore Redis failures during shutdown
  end
  FileUtils.remove_entry_secure(@temp_dir, true)
  @metric.shutdown
  begin
    @logger.debug("Shutting down microservice complete: #{@name}")
  rescue Exception
    # Ignore logging failures during shutdown
  end
  @shutdown_complete = true
end