Class: RSMP::SupervisorProxy

Inherits:
Proxy
  • Object
show all
Defined in:
lib/rsmp/supervisor_proxy.rb

Constant Summary

Constants inherited from Proxy

Proxy::WRAPPING_DELIMITER

Instance Attribute Summary collapse

Attributes inherited from Proxy

#archive, #collector, #connection_info, #core_version, #ip, #node, #port, #state, #sxl

Attributes included from Task

#task

Attributes included from Notifier

#listeners

Attributes included from Logging

#archive, #logger

Instance Method Summary collapse

Methods inherited from Proxy

#acknowledge, #acknowledged_first_outgoing, #author, #buffer_message, #check_ack_timeout, #check_core_version, #check_ingoing_acknowledged, #check_outgoing_acknowledged, #check_watchdog_timeout, #clear, #clock, #close, #close_socket, #close_stream, #connected?, #core_versions, #disconnect, #disconnected?, #dont_acknowledge, #dont_expect_acknowledgement, #expect_acknowledgement, #expect_version_message, #extraneous_version, #find_original_for_message, #get_schemas, #inspect, #log, #log_acknowledgement_for_original, #log_acknowledgement_for_unknown, #log_send, #notify_error, #now, #process_ack, #process_deferred, #process_not_ack, #process_packet, #process_watchdog, #read_line, #ready?, #revive, #run_reader, #run_timer, #send_and_optionally_collect, #send_message, #send_version, #send_watchdog, #set_nts_message_attributes, #set_state, #setup, #should_validate_ingoing_message?, #start_reader, #start_timer, #start_watchdog, #state_changed, #status_subscribe_acknowledged, #stop_reader, #stop_subtasks, #stop_timer, #stop_watchdog, #verify_sequence, #version_acknowledged, version_meets_requirement?, #wait_for_reader, #wait_for_state, #watchdog_send_timer, #will_not_handle, #with_watchdog_disabled

Methods included from Task

#initialize_task, #restart, #start, #stop, #stop_subtasks, #task_status, #wait, #wait_for_condition

Methods included from Inspect

#inspect, #inspector

Methods included from Notifier

#add_listener, #clear_deferred_notify, #deferred_notify, #dequeue_notify, #distribute_error, #initialize_distributor, #inspect, #notify, #notify_without_defer, #remove_listener

Methods included from Logging

#author, #initialize_logging, #log

Constructor Details

#initialize(options) ⇒ SupervisorProxy

Returns a new instance of SupervisorProxy.



10
11
12
13
14
15
16
17
18
19
# File 'lib/rsmp/supervisor_proxy.rb', line 10

def initialize options
  super options.merge(node:options[:site])
  @site = options[:site]
  @site_settings = @site.site_settings.clone
  @ip = options[:ip]
  @port = options[:port]
  @status_subscriptions = {}
  @sxl = @site_settings['sxl']
  @synthetic_id = Supervisor.build_id_from_ip_port @ip, @port
end

Instance Attribute Details

#siteObject (readonly)

Returns the value of attribute site.



8
9
10
# File 'lib/rsmp/supervisor_proxy.rb', line 8

def site
  @site
end

#supervisor_idObject (readonly)

Returns the value of attribute supervisor_id.



8
9
10
# File 'lib/rsmp/supervisor_proxy.rb', line 8

def supervisor_id
  @supervisor_id
end

Instance Method Details

#acknowledged_first_ingoing(message) ⇒ Object



130
131
132
133
134
135
# File 'lib/rsmp/supervisor_proxy.rb', line 130

def acknowledged_first_ingoing message
  case message.type
  when "Watchdog"
    handshake_complete
  end
end

#check_sxl_version(message) ⇒ Object



492
493
# File 'lib/rsmp/supervisor_proxy.rb', line 492

def check_sxl_version message
end

#connectObject

connect to the supervisor and initiate handshake supervisor



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rsmp/supervisor_proxy.rb', line 50

def connect
  log "Connecting to supervisor at #{@ip}:#{@port}", level: :info
  set_state :connecting
  connect_tcp
  @logger.unmute @ip, @port
  log "Connected to supervisor at #{@ip}:#{@port}", level: :info
rescue SystemCallError => e
  raise ConnectionError.new "Could not connect to supervisor at #{@ip}:#{@port}: Errno #{e.errno} #{e}"
rescue StandardError => e
  raise ConnectionError.new "Error while connecting to supervisor at #{@ip}:#{@port}: #{e}"
end

#connect_tcpObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/rsmp/supervisor_proxy.rb', line 67

def connect_tcp
  @endpoint = Async::IO::Endpoint.tcp(@ip, @port)

  error = nil
  # Async::IO::Endpoint#connect renames the current task. run in a subtask to avoid this see issue #22
  result = @task.async do |task|
    task.annotate 'socket task'
    # this timeout is a workaround for connect hanging on windows if the other side is not present yet
    timeout = @site_settings.dig('timeouts','connect') || 1.1
    task.with_timeout timeout do
      @socket = @endpoint.connect
    end
    delay = @site_settings.dig('intervals','after_connect')
    task.sleep delay if delay
  rescue Errno::ECONNREFUSED => e   # rescue to avoid log output
    log "Connection refused", level: :warning
    error = e
  end.wait
  raise error if error  # reraise any error outside task

  @stream = Async::IO::Stream.new(@socket)
  @protocol = Async::IO::Protocol::Line.new(@stream,WRAPPING_DELIMITER) # rsmp messages are json terminated with a form-feed
  set_state :connected
end

#fetch_last_sent_status(component, code, name) ⇒ Object



397
398
399
# File 'lib/rsmp/supervisor_proxy.rb', line 397

def fetch_last_sent_status component, code, name
  @last_status_sent.dig component, code, name if @last_status_sent
end

#get_status_subscribe_interval(component_id, sCI, n) ⇒ Object



370
371
372
# File 'lib/rsmp/supervisor_proxy.rb', line 370

def get_status_subscribe_interval component_id, sCI, n
  @status_subscriptions.dig component_id, sCI, n
end

#handle_alarm_acknowledge(message) ⇒ Object

handle incoming alarm acknowledge



219
220
221
222
223
224
225
226
# File 'lib/rsmp/supervisor_proxy.rb', line 219

def handle_alarm_acknowledge message
  component_id = message.attributes["cId"]
  component = @site.find_component component_id
  alarm_code = message.attribute("aCId")
  log "Received #{message.type} #{alarm_code} acknowledgement", message: message, level: :log
  acknowledge message
  component.acknowledge_alarm alarm_code
end

#handle_alarm_resume(message) ⇒ Object

handle incoming alarm resume



239
240
241
242
243
244
245
246
# File 'lib/rsmp/supervisor_proxy.rb', line 239

def handle_alarm_resume message
  component_id = message.attributes["cId"]
  component = @site.find_component component_id
  alarm_code = message.attribute("aCId")
  log "Received #{message.type} #{alarm_code} resume", message: message, level: :log
  acknowledge message
  component.resume_alarm alarm_code
end

#handle_alarm_suspend(message) ⇒ Object

handle incoming alarm suspend



229
230
231
232
233
234
235
236
# File 'lib/rsmp/supervisor_proxy.rb', line 229

def handle_alarm_suspend message
  component_id = message.attributes["cId"]
  component = @site.find_component component_id
  alarm_code = message.attribute("aCId")
  log "Received #{message.type} #{alarm_code} suspend", message: message, level: :log
  acknowledge message
  component.suspend_alarm alarm_code
end

#handshake_completeObject



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/rsmp/supervisor_proxy.rb', line 92

def handshake_complete
  sanitized_sxl_version = RSMP::Schema.sanitize_version(sxl_version)
  log "Connection to supervisor established, using core #{@core_version}, #{sxl} #{sanitized_sxl_version}", level: :info
  set_state :ready
  start_watchdog
  if @site_settings['send_after_connect']
    send_all_aggregated_status
    send_active_alarms
  end
  super
end

#mainObject



495
496
497
# File 'lib/rsmp/supervisor_proxy.rb', line 495

def main
  @site.main
end

#process_aggregated_status(message) ⇒ Object



195
196
197
198
199
200
201
# File 'lib/rsmp/supervisor_proxy.rb', line 195

def process_aggregated_status message
  se = message.attribute("se")
  validate_aggregated_status(message,se) == false
  on = set_aggregated_status se
  log "Received #{message.type} status [#{on.join(', ')}]", message: message, level: :log
  acknowledge message
end

#process_aggregated_status_request(message) ⇒ Object



260
261
262
263
264
265
266
# File 'lib/rsmp/supervisor_proxy.rb', line 260

def process_aggregated_status_request message
  log "Received #{message.type}", message: message, level: :log
  component_id = message.attributes["cId"]
  component = @site.find_component component_id
  acknowledge message
  send_aggregated_status component
end

#process_alarm(message) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rsmp/supervisor_proxy.rb', line 203

def process_alarm message
  case message
  when AlarmAcknowledge
    handle_alarm_acknowledge message
  when AlarmSuspend
    handle_alarm_suspend message
  when AlarmResume
    handle_alarm_resume message
  when AlarmRequest
    handle_alarm_request message
  else
    dont_acknowledge message, "Invalid alarm message type"
  end
end

#process_command_request(message) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/rsmp/supervisor_proxy.rb', line 268

def process_command_request message
  component_id = message.attributes["cId"]

  rvs = message.attributes["arg"].map do |item|
    item = item.dup.merge('age'=>'recent')
    item.delete 'cO'
    item
  end

  begin
    component = @site.find_component component_id
    commands = simplify_command_requests message.attributes["arg"]
    commands.each_pair do |command_code,arg|
      component.handle_command command_code,arg
    end
    log "Received #{message.type}", message: message, level: :log
  rescue UnknownComponent
    log "Received #{message.type} with unknown component id '#{component_id}' and cannot infer type", message: message, level: :warning
    # If the component is unknown, we must set age=undefined for all items,
    # while still acknowledge the message.
    # See https://github.com/rsmp-nordic/rsmp_validator/issues/271
    rvs.map do |item|
      item['age'] = 'undefined'
    end
  end

  response = CommandResponse.new({
    "cId"=>component_id,
    "cTS"=>clock.to_s,
    "rvs"=>rvs
  })
  set_nts_message_attributes response
  acknowledge message
  send_message response
end

#process_message(message) ⇒ Object



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
# File 'lib/rsmp/supervisor_proxy.rb', line 104

def process_message message
  case message
  when StatusResponse, StatusUpdate, AggregatedStatus, AlarmIssue
    will_not_handle message
  when AggregatedStatusRequest
    process_aggregated_status_request message
  when CommandRequest
    process_command_request message
  when CommandResponse
    process_command_response message
  when StatusRequest
    process_status_request message
  when StatusSubscribe
    process_status_subcribe message
  when StatusUnsubscribe
    process_status_unsubcribe message
  when Alarm, AlarmAcknowledged, AlarmSuspend, AlarmResume, AlarmRequest
    process_alarm message
  else
    super message
  end
rescue UnknownComponent, UnknownCommand, UnknownStatus,
       MessageRejected, MissingAttribute => e
  dont_acknowledge message, '', e.to_s
end

#process_status_request(message, options = {}) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/rsmp/supervisor_proxy.rb', line 309

def process_status_request message, options={}
  sS = []
  begin
    component_id = message.attributes["cId"]
    component = @site.find_component component_id
    sS = message.attributes["sS"].map do |arg|
      value, quality =  component.get_status arg['sCI'], arg['n'], {sxl_version: sxl_version}
      { "s" => rsmpify_value(value), "q" => quality.to_s }.merge arg
    end
    log "Received #{message.type}", message: message, level: :log

  rescue UnknownComponent
    log "Received #{message.type} with unknown component id '#{component_id}' and cannot infer type", message: message, level: :warning
    # If the component is unknown, we must set q=undefined and s=nil for all items,
    # while still acknowledge the message.
    sS = message.attributes["sS"].map do |arg|
      arg.dup.merge('q'=>'undefined','s'=>nil)
    end
  end

  response = StatusResponse.new({
    "cId"=>component_id,
    "sTs"=>clock.to_s,
    "sS"=>sS,
    "mId" => options[:m_id]
  })

  set_nts_message_attributes response
  acknowledge message
  send_message response
end

#process_status_subcribe(message) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/rsmp/supervisor_proxy.rb', line 341

def process_status_subcribe message
  log "Received #{message.type}", message: message, level: :log

  # @status_subscriptions is organized by component/code/name, for example:
  #
  # {"AA+BBCCC=DDDEE002"=>{"S001"=>["number"]}}
  #
  # This is done to make it easy to send a single status update
  # for each component, containing all the requested statuses

  update_list = {}
  component_id = message.attributes["cId"]
  @status_subscriptions[component_id] ||= {}
  update_list[component_id] ||= {}
  now = Time.now  # internal timestamp
  subs = @status_subscriptions[component_id]

  message.attributes["sS"].each do |arg|
    sCI = arg["sCI"]
    subcription = {interval: arg["uRt"].to_i, last_sent_at: now}
    subs[sCI] ||= {}
    subs[sCI][arg["n"]] = subcription
    update_list[component_id][sCI] ||= []
    update_list[component_id][sCI] << arg["n"]
  end
  acknowledge message
  send_status_updates update_list   # send status after subscribing is accepted
end

#process_status_unsubcribe(message) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/rsmp/supervisor_proxy.rb', line 374

def process_status_unsubcribe message
  log "Received #{message.type}", message: message, level: :log
  component = message.attributes["cId"]

  subs = @status_subscriptions[component]
  if subs
    message.attributes["sS"].each do |arg|
      sCI = arg["sCI"]
      if subs[sCI]
        subs[sCI].delete arg["n"]
        subs.delete(sCI) if subs[sCI].empty?
      end
    end
    @status_subscriptions.delete(component) if subs.empty?
  end
  acknowledge message
end

#process_version(message) ⇒ Object



484
485
486
487
488
489
490
# File 'lib/rsmp/supervisor_proxy.rb', line 484

def process_version message
  return extraneous_version message if @version_determined
  check_core_version message
  check_sxl_version message
  @site_id = Supervisor.build_id_from_ip_port @ip, @port
  version_accepted message
end

#reconnect_delayObject



156
157
158
159
160
161
162
163
# File 'lib/rsmp/supervisor_proxy.rb', line 156

def reconnect_delay
  return false if @site_settings['intervals']['reconnect'] == :no
  interval = @site_settings['intervals']['reconnect']
  log "Will try to reconnect again every #{interval} seconds...", level: :info
  @logger.mute @ip, @port
  @task.sleep interval
  true
end

#rsmpify_value(v) ⇒ Object



304
305
306
307
# File 'lib/rsmp/supervisor_proxy.rb', line 304

def rsmpify_value v
  return v if v.is_a?(Array) || v.is_a?(Set)
  v.to_s
end

#runObject

handle communication if disconnected, then try to reconnect



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rsmp/supervisor_proxy.rb', line 23

def run
  loop do
    connect
    start_reader
    start_handshake
    wait_for_reader   # run until disconnected
    break if reconnect_delay == false
  rescue Restart
    @logger.mute @ip, @port
    raise
  rescue RSMP::ConnectionError => e
    log e, level: :error
    break if reconnect_delay == false
  rescue StandardError => e
    notify_error e, level: :internal
    break if reconnect_delay == false
  ensure
    close
    stop_subtasks
  end
end

#send_active_alarmsObject



145
146
147
148
149
150
151
152
153
154
# File 'lib/rsmp/supervisor_proxy.rb', line 145

def send_active_alarms
  @site.components.each_pair do |c_id,component|
    component.alarms.each_pair do |alarm_code, alarm_state|
      if alarm_state.active
        alarm = AlarmIssue.new( alarm_state.to_hash.merge('aSp' => 'Issue') )
        send_message alarm
      end
    end
  end
end

#send_aggregated_status(component, options = {}) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/rsmp/supervisor_proxy.rb', line 173

def send_aggregated_status component, options={}
  m_id = options[:m_id] || RSMP::Message.make_m_id
  message = AggregatedStatus.new({
    "aSTS" => clock.to_s,
    "cId" =>  component.c_id,
    "fP" => nil,
    "fS" => nil,
    "se" => component.aggregated_status_bools,
    "mId" => m_id,
  })
  set_nts_message_attributes message
  send_and_optionally_collect message, options do |collect_options|
    Collector.new self, collect_options.merge(task:@task, type: 'MessageAck')
  end
end

#send_alarm(component, alarm, options = {}) ⇒ Object



189
190
191
192
193
# File 'lib/rsmp/supervisor_proxy.rb', line 189

def send_alarm component, alarm, options={}
  send_and_optionally_collect alarm, options do |collect_options|
    Collector.new self, collect_options.merge(task:@task, type: 'MessageAck')
  end
end

#send_all_aggregated_statusObject



137
138
139
140
141
142
143
# File 'lib/rsmp/supervisor_proxy.rb', line 137

def send_all_aggregated_status
  @site.components.each_pair do |c_id,component|
    if component.grouped
      send_aggregated_status component
    end
  end
end

#send_status_updates(update_list) ⇒ Object



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/rsmp/supervisor_proxy.rb', line 451

def send_status_updates update_list
  now = clock.to_s
  update_list.each_pair do |component_id,by_code|
    component = @site.find_component component_id
    sS = []
    by_code.each_pair do |code,names|
      names.map do |status_name,value|
        if value
          quality = 'recent'
        else
          value,quality = component.get_status code, status_name
        end
        sS << { "sCI" => code,
                 "n" => status_name,
                 "s" => rsmpify_value(value),
                 "q" => quality }
      end
    end
    update = StatusUpdate.new({
      "cId"=>component_id,
      "sTs"=>now,
      "sS"=>sS
    })
    set_nts_message_attributes update
    send_message update
    store_last_sent_status update
  end
end

#simplify_command_requests(arg) ⇒ Object

reorganize rmsp command request arg attribute:

“cCI”:“M0002”,“cO”:“setPlan”,“n”:“status”,“v”:“True”,“cCI”:“M0002”,“cO”:“setPlan”,“n”:“securityCode”,“v”:“5678”,“cCI”:“M0002”,“cO”:“setPlan”,“n”:“timeplan”,“v”:“3”

into the simpler, but equivalent: “securityCode”=>“5678”, “timeplan”=>“3”}



251
252
253
254
255
256
257
258
# File 'lib/rsmp/supervisor_proxy.rb', line 251

def simplify_command_requests arg
  sorted = {}
  arg.each do |item|
    sorted[item['cCI']] ||= {}
    sorted[item['cCI']][item['n']] = item['v']
  end
  sorted
end

#start_handshakeObject



45
46
47
# File 'lib/rsmp/supervisor_proxy.rb', line 45

def start_handshake
  send_version @site_settings['site_id'], @site_settings["core_versions"]
end

#status_update_timer(now) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/rsmp/supervisor_proxy.rb', line 412

def status_update_timer now
  update_list = {}
  # go through subscriptons and build a similarly organized list,
  # that only contains what should be send

  @status_subscriptions.each_pair do |component,by_code|
    component_object = @site.find_component component
    by_code.each_pair do |code,by_name|
      by_name.each_pair do |name,subscription|
        current = nil
        should_send = false
        if subscription[:interval] == 0
          # send as soon as the data changes
          if component_object
            current, age = *(component_object.get_status code, name)
            current = rsmpify_value(current)
          end
          last_sent = fetch_last_sent_status component, code, name
          if current != last_sent
            should_send = true
          end
        else
          # send at regular intervals
          if subscription[:last_sent_at] == nil || (now - subscription[:last_sent_at]) >= subscription[:interval]
            should_send = true
          end
        end
        if should_send
          subscription[:last_sent_at] = now
          update_list[component] ||= {}
          update_list[component][code] ||= {}
          update_list[component][code][name] = current
       end
      end
    end
  end
  send_status_updates update_list
end

#stop_taskObject



62
63
64
65
# File 'lib/rsmp/supervisor_proxy.rb', line 62

def stop_task
  super
  @last_status_sent = nil
end

#store_last_sent_status(message) ⇒ Object



401
402
403
404
405
406
407
408
409
410
# File 'lib/rsmp/supervisor_proxy.rb', line 401

def store_last_sent_status message
  component_id = message.attribute('cId')
  @last_status_sent ||= {}
  @last_status_sent[component_id] ||= {}
  message.attribute('sS').each do |item|
    sCI, n, s = item['sCI'], item['n'], item['s']
    @last_status_sent[component_id][sCI] ||= {}
    @last_status_sent[component_id][sCI][n] = s
  end
end

#sxl_versionObject



480
481
482
# File 'lib/rsmp/supervisor_proxy.rb', line 480

def sxl_version
  @site_settings['sxl_version'].to_s
end

#timer(now) ⇒ Object



392
393
394
395
# File 'lib/rsmp/supervisor_proxy.rb', line 392

def timer now
  super
  status_update_timer now if ready?
end

#version_accepted(message) ⇒ Object



165
166
167
168
169
170
171
# File 'lib/rsmp/supervisor_proxy.rb', line 165

def version_accepted message
  log "Received Version message, using RSMP #{@core_version}", message: message, level: :log
  start_timer
  acknowledge message
  @version_determined = true
  send_watchdog
end