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.


81
82
83
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
# File 'lib/openc3/microservices/microservice.rb', line 81

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

  @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)

  # Create temp folder for this microservice
  @temp_dir = Dir.mktmpdir

  # 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}"

  # 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
    temp_dir = Dir.mktmpdir
    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 = 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 = 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(:allow_nan => true), scope: @scope) unless @cancel_thread
        break if @microservice_status_sleeper.sleep(@microservice_status_period_seconds)
      end
    rescue Exception => e
      @logger.error "#{@name} status thread died: #{e.formatted}"
      raise e
    end
  end
end

Instance Attribute Details

#countObject

Returns the value of attribute count.


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

def count
  @count
end

#customObject

Returns the value of attribute custom.


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

def custom
  @custom
end

#errorObject

Returns the value of attribute error.


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

def error
  @error
end

#loggerObject

Returns the value of attribute logger.


46
47
48
# File 'lib/openc3/microservices/microservice.rb', line 46

def logger
  @logger
end

#microservice_status_threadObject

Returns the value of attribute microservice_status_thread.


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

def microservice_status_thread
  @microservice_status_thread
end

#nameObject

Returns the value of attribute name.


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

def name
  @name
end

#scopeObject

Returns the value of attribute scope.


45
46
47
# File 'lib/openc3/microservices/microservice.rb', line 45

def scope
  @scope
end

#secretsObject

Returns the value of attribute secrets.


47
48
49
# File 'lib/openc3/microservices/microservice.rb', line 47

def secrets
  @secrets
end

#stateObject

Returns the value of attribute state.


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

def state
  @state
end

Class Method Details

.run(name = nil) ⇒ Object


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/openc3/microservices/microservice.rb', line 49

def self.run(name = nil)
  name = ENV['OPENC3_MICROSERVICE_NAME'] unless name
  microservice = self.new(name)
  begin
    MicroserviceStatusModel.set(microservice.as_json(:allow_nan => true), scope: microservice.scope)
    microservice.state = 'RUNNING'
    microservice.run
    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
  ensure
    MicroserviceStatusModel.set(microservice.as_json(:allow_nan => true), scope: microservice.scope)
  end
end

Instance Method Details

#as_json(*a) ⇒ Object


70
71
72
73
74
75
76
77
78
79
# File 'lib/openc3/microservices/microservice.rb', line 70

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


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

def microservice_cmd(topic, msg_id, msg_hash, _redis)
  command = msg_hash['command']
  case command
  when '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)
    return true
  end
  Topic.trim_topic(topic, msg_id)
  return false
end

#runObject

Must be implemented by a subclass


199
200
201
# File 'lib/openc3/microservices/microservice.rb', line 199

def run
  shutdown()
end

#setup_microservice_topicObject


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

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

#shutdownObject


203
204
205
206
207
208
209
210
211
212
213
# File 'lib/openc3/microservices/microservice.rb', line 203

def shutdown
  return if @shutdown_complete
  @logger.info("Shutting down microservice: #{@name}")
  @cancel_thread = true
  @microservice_status_sleeper.cancel if @microservice_status_sleeper
  MicroserviceStatusModel.set(as_json(:allow_nan => true), scope: @scope)
  FileUtils.remove_entry(@temp_dir) if File.exist?(@temp_dir)
  @metric.shutdown
  @logger.debug("Shutting down microservice complete: #{@name}")
  @shutdown_complete = true
end