procon_bypass_man 0.2.1 → 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (99) hide show
  1. checksums.yaml +4 -4
  2. data/.circleci/config.yml +19 -6
  3. data/.github/workflows/gitleacks.yml +1 -1
  4. data/.rubocop.yml +4 -0
  5. data/.ruby-version +1 -1
  6. data/CHANGELOG.md +15 -0
  7. data/Gemfile +6 -3
  8. data/Gemfile.lock +5 -3
  9. data/README.md +28 -41
  10. data/Steepfile +0 -1
  11. data/bin/generate_default_app +10 -0
  12. data/docs/getting_started.md +102 -28
  13. data/docs/setup_raspi_by_mitamae.md +43 -2
  14. data/lib/procon_bypass_man/background/job_performer.rb +1 -2
  15. data/lib/procon_bypass_man/background/job_queue.rb +50 -0
  16. data/lib/procon_bypass_man/background/jobs/base_job.rb +1 -1
  17. data/lib/procon_bypass_man/background/jobs/concerns/has_external_api_setting.rb +2 -2
  18. data/lib/procon_bypass_man/background/jobs/concerns/job_performable.rb +16 -0
  19. data/lib/procon_bypass_man/background/jobs/post_completed_remote_macro_job.rb +1 -1
  20. data/lib/procon_bypass_man/background/jobs/report_boot_job.rb +1 -1
  21. data/lib/procon_bypass_man/background/jobs/report_completed_upgrade_pbm_job.rb +1 -1
  22. data/lib/procon_bypass_man/background/jobs/report_error_job.rb +1 -1
  23. data/lib/procon_bypass_man/background/jobs/report_error_reload_config_job.rb +1 -1
  24. data/lib/procon_bypass_man/background/jobs/report_load_config_job.rb +1 -1
  25. data/lib/procon_bypass_man/background/jobs/report_procon_performance_measurements_job.rb +43 -0
  26. data/lib/procon_bypass_man/background/jobs/report_reload_config_job.rb +1 -1
  27. data/lib/procon_bypass_man/background/jobs/report_start_reboot_job.rb +1 -1
  28. data/lib/procon_bypass_man/background/jobs/sync_device_stats_job.rb +1 -1
  29. data/lib/procon_bypass_man/background.rb +3 -4
  30. data/lib/procon_bypass_man/bypass/bypass_command.rb +16 -20
  31. data/lib/procon_bypass_man/bypass/bypass_value.rb +6 -0
  32. data/lib/procon_bypass_man/bypass/procon_to_switch.rb +99 -0
  33. data/lib/procon_bypass_man/bypass/switch_to_procon.rb +66 -0
  34. data/lib/procon_bypass_man/bypass.rb +5 -109
  35. data/lib/procon_bypass_man/commands/print_boot_message_command.rb +0 -2
  36. data/lib/procon_bypass_man/configuration.rb +18 -39
  37. data/lib/procon_bypass_man/device_connection/procon_setting_overrider.rb +12 -3
  38. data/lib/procon_bypass_man/procon/analog_stick_manipulator.rb +2 -0
  39. data/lib/procon_bypass_man/procon/layer_changer.rb +2 -0
  40. data/lib/procon_bypass_man/procon/macro.rb +3 -1
  41. data/lib/procon_bypass_man/procon/macro_builder.rb +2 -0
  42. data/lib/procon_bypass_man/procon/macro_registry.rb +2 -0
  43. data/lib/procon_bypass_man/procon/performance_measurement/last_bypass_at.rb +17 -0
  44. data/lib/procon_bypass_man/procon/performance_measurement/measurement_collection.rb +9 -0
  45. data/lib/procon_bypass_man/procon/performance_measurement/measurements_summarizer.rb +101 -0
  46. data/lib/procon_bypass_man/procon/performance_measurement/procon_performance_span_transfer_job.rb +8 -0
  47. data/lib/procon_bypass_man/procon/performance_measurement/queue_over_process.rb +38 -0
  48. data/lib/procon_bypass_man/procon/performance_measurement/span_queue.rb +42 -0
  49. data/lib/procon_bypass_man/procon/performance_measurement/span_transfer_buffer.rb +39 -0
  50. data/lib/procon_bypass_man/procon/performance_measurement.rb +110 -0
  51. data/lib/procon_bypass_man/procon/suppress_rumble.rb +2 -0
  52. data/lib/procon_bypass_man/procon/user_operation.rb +2 -0
  53. data/lib/procon_bypass_man/procon/value_objects/analog_stick.rb +2 -0
  54. data/lib/procon_bypass_man/procon/value_objects/binary/inbound_procon_binary.rb +2 -0
  55. data/lib/procon_bypass_man/procon/value_objects/binary/processing_procon_binary.rb +2 -0
  56. data/lib/procon_bypass_man/procon/value_objects/rumble_binary.rb +2 -0
  57. data/lib/procon_bypass_man/procon.rb +26 -7
  58. data/lib/procon_bypass_man/procon_display/bypass_hook.rb +12 -0
  59. data/lib/procon_bypass_man/procon_display.rb +1 -0
  60. data/lib/procon_bypass_man/remote_macro/queue_over_process.rb +26 -44
  61. data/lib/procon_bypass_man/remote_macro/remote_macro_object.rb +22 -24
  62. data/lib/procon_bypass_man/remote_macro/remote_macro_receiver.rb +1 -1
  63. data/lib/procon_bypass_man/remote_macro/remote_macro_sender.rb +1 -1
  64. data/lib/procon_bypass_man/remote_macro/task.rb +1 -5
  65. data/lib/procon_bypass_man/remote_macro/task_queue.rb +6 -10
  66. data/lib/procon_bypass_man/remote_macro.rb +2 -0
  67. data/lib/procon_bypass_man/remote_pbm_action/commands/update_remote_pbm_action_status_command.rb +1 -1
  68. data/lib/procon_bypass_man/remote_pbm_action.rb +2 -0
  69. data/lib/procon_bypass_man/runner.rb +4 -10
  70. data/lib/procon_bypass_man/scheduler.rb +15 -6
  71. data/lib/procon_bypass_man/support/callbacks.rb +79 -34
  72. data/lib/procon_bypass_man/support/can_over_process.rb +60 -0
  73. data/lib/procon_bypass_man/support/gc.rb +8 -0
  74. data/lib/procon_bypass_man/support/http_client.rb +12 -6
  75. data/lib/procon_bypass_man/support/load_agv.rb +20 -0
  76. data/lib/procon_bypass_man/support/procon_performance_http_client.rb +7 -0
  77. data/lib/procon_bypass_man/support/renice_command.rb +17 -0
  78. data/lib/procon_bypass_man/support/retryable.rb +16 -0
  79. data/lib/procon_bypass_man/support/signal_handler.rb +1 -1
  80. data/lib/procon_bypass_man/version.rb +1 -1
  81. data/lib/procon_bypass_man/websocket/client.rb +2 -2
  82. data/lib/procon_bypass_man/worker.rb +32 -0
  83. data/lib/procon_bypass_man.rb +53 -10
  84. data/procon_bypass_man.gemspec +4 -2
  85. data/project_template/README.md +0 -5
  86. data/project_template/app.rb +17 -11
  87. data/project_template/app.rb.erb +59 -0
  88. data/project_template/lib/app_generator.rb +31 -0
  89. data/project_template/web.rb +1 -1
  90. data/sig/main.rbs +10 -52
  91. data/tmp/.keep +0 -0
  92. metadata +43 -10
  93. data/lib/procon_bypass_man/background/job_runner.rb +0 -45
  94. data/lib/procon_bypass_man/background/jobs/concerns/has_internal_api_setting.rb +0 -5
  95. data/lib/procon_bypass_man/background/jobs/concerns/job_runnable.rb +0 -16
  96. data/lib/procon_bypass_man/background/jobs/report_pressed_buttons_job.rb +0 -15
  97. data/lib/procon_bypass_man/bypass/usb_hid_logger.rb +0 -47
  98. data/lib/procon_bypass_man/io_monitor.rb +0 -108
  99. data/lib/procon_bypass_man/support/server_pool.rb +0 -46
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "procon_bypass_man/procon/macro_plugin_map"
2
4
 
3
5
  class ProconBypassMan::Procon
@@ -7,8 +9,9 @@ class ProconBypassMan::Procon
7
9
  require "procon_bypass_man/procon/value_objects/rumble_binary"
8
10
  require "procon_bypass_man/procon/value_objects/binary"
9
11
  require "procon_bypass_man/procon/value_objects/bypass_mode"
10
-
11
12
  require "procon_bypass_man/procon/consts"
13
+ require "procon_bypass_man/procon/performance_measurement"
14
+ require "procon_bypass_man/procon/performance_measurement/queue_over_process"
12
15
  require "procon_bypass_man/procon/mode_registry"
13
16
  require "procon_bypass_man/procon/macro"
14
17
  require "procon_bypass_man/procon/macro_registry"
@@ -24,11 +27,11 @@ class ProconBypassMan::Procon
24
27
 
25
28
  def self.reset!
26
29
  @@status = {
27
- buttons: {},
28
- current_layer_key: :up,
29
30
  ongoing_macro: MacroRegistry.load(:null),
30
- ongoing_mode: ModeRegistry.load(:manual),
31
+ ongoing_mode: ModeRegistry.load(:manual), # 削除予定
31
32
  }
33
+ BlueGreenProcess::SharedVariable.instance.data["buttons"] = {}
34
+ BlueGreenProcess::SharedVariable.instance.data["current_layer_key"] = :up
32
35
  @@left_stick_tilting_power_scaler = ProconBypassMan::AnalogStickTiltingPowerScaler.new
33
36
  end
34
37
  reset!
@@ -40,10 +43,20 @@ class ProconBypassMan::Procon
40
43
  )
41
44
  end
42
45
 
43
- def status; @@status[:buttons]; end
46
+ def status
47
+ BlueGreenProcess::SharedVariable.instance.data["buttons"]
48
+ end
49
+
50
+ def current_layer_key
51
+ BlueGreenProcess::SharedVariable.instance.data["current_layer_key"].to_sym
52
+ end
53
+
54
+ def current_layer_key=(layer)
55
+ BlueGreenProcess::SharedVariable.instance.data["current_layer_key"] = layer
56
+ end
57
+
44
58
  def ongoing_macro; @@status[:ongoing_macro]; end
45
59
  def ongoing_mode; @@status[:ongoing_mode]; end
46
- def current_layer_key; @@status[:current_layer_key]; end
47
60
 
48
61
  def current_layer
49
62
  ProconBypassMan::ButtonsSettingConfiguration.instance.layers[current_layer_key]
@@ -53,7 +66,7 @@ class ProconBypassMan::Procon
53
66
  def apply!
54
67
  layer_changer = ProconBypassMan::Procon::LayerChanger.new(binary: user_operation.binary)
55
68
  if layer_changer.change_layer?
56
- @@status[:current_layer_key] = layer_changer.next_layer_key if layer_changer.pressed_next_layer?
69
+ self.current_layer_key = layer_changer.next_layer_key if layer_changer.pressed_next_layer?
57
70
  user_operation.set_no_action!
58
71
  return
59
72
  end
@@ -96,10 +109,14 @@ class ProconBypassMan::Procon
96
109
 
97
110
  # remote macro
98
111
  if task = ProconBypassMan::RemoteMacro::TaskQueueInProcess.non_blocking_shift
112
+ no_op_step = :wait_for_0_3 # マクロの最後に固まって最後の入力をし続けるので、無の状態を最後に注入する
113
+ BlueGreenProcess::SharedVariable.extend_run_on_this_process = true
99
114
  ProconBypassMan::Procon::MacroRegistry.cleanup_remote_macros!
100
115
  macro_name = task.name || "RemoteMacro-#{task.steps.join}".to_sym
116
+ task.steps << no_op_step
101
117
  ProconBypassMan::Procon::MacroRegistry.install_plugin(macro_name, steps: task.steps, macro_type: :remote)
102
118
  @@status[:ongoing_macro] = MacroRegistry.load(macro_name, macro_type: :remote) do
119
+ GC.start # NOTE: extend_run_on_this_process = true するとGCされなくなるので手動で呼び出す
103
120
  ProconBypassMan::PostCompletedRemoteMacroJob.perform_async(task.uuid)
104
121
  end
105
122
  end
@@ -109,6 +126,7 @@ class ProconBypassMan::Procon
109
126
  @@status[:ongoing_mode] = ModeRegistry.load(:manual)
110
127
  current_layer.flip_buttons.each do |button, options|
111
128
  if !options[:if_pressed]
129
+ # FIXME マルチプロセス化したので、クラス変数に状態を保持するFlipCacheは意図した挙動にならない. BlueGreenProcess.shared_variables を使って状態をプロセス間で共有すれば動く
112
130
  FlipCache.fetch(key: button, expires_in: options[:flip_interval]) do
113
131
  status[button] = !status[button]
114
132
  end
@@ -145,6 +163,7 @@ class ProconBypassMan::Procon
145
163
  end
146
164
 
147
165
  if ongoing_macro.ongoing? && (step = ongoing_macro.next_step)
166
+ BlueGreenProcess::SharedVariable.extend_run_on_this_process = true
148
167
  ongoing_macro.force_neutral_buttons&.each do |force_neutral_button|
149
168
  user_operation.unpress_button(force_neutral_button)
150
169
  end
@@ -0,0 +1,12 @@
1
+ module ProconBypassMan::ProconDisplay::BypassHook
2
+ include ProconBypassMan::Callbacks
3
+
4
+ define_callbacks :run
5
+
6
+ set_callback :run, :after, :write_procon_display_status
7
+
8
+ def write_procon_display_status
9
+ return unless bypass_value.binary
10
+ ProconBypassMan::ProconDisplay::Status.instance.current = bypass_value.binary.to_procon_reader.to_hash.dup
11
+ end
12
+ end
@@ -8,3 +8,4 @@ require "procon_bypass_man/procon_display/server_app"
8
8
  require "procon_bypass_man/procon_display/status"
9
9
  require "procon_bypass_man/procon_display/http_response"
10
10
  require "procon_bypass_man/procon_display/http_request"
11
+ require "procon_bypass_man/procon_display/bypass_hook"
@@ -1,62 +1,44 @@
1
- class ProconBypassMan::QueueOverProcess
2
- attr_reader :drb
3
-
4
- @@drb_server = nil
5
- @@drb_server_thread = nil
6
-
7
- def self.start!
8
- return unless ProconBypassMan.config.enable_remote_macro?
9
- require 'drb/drb'
10
-
11
- FileUtils.rm_rf(file_path) if File.exist?(file_path)
12
- begin
13
- @@drb_server = DRb.start_service(url, Queue.new, safe_level: 1)
14
- rescue Errno::EADDRINUSE => e
15
- ProconBypassMan.logger.error e
16
- raise
17
- end
18
-
19
- @@drb_server_thread =
20
- Thread.new do
21
- DRb.thread.join
22
- end
23
- end
1
+ class ProconBypassMan::RemoteMacro::QueueOverProcess
2
+ extend ProconBypassMan::CanOverProcess
24
3
 
25
- def self.shutdown
26
- if @@drb_server
27
- @@drb_server_thread.kill
28
- @@drb_server.stop_service
29
- end
30
- end
4
+ include Singleton
31
5
 
32
- def self.push(value)
33
- return unless ProconBypassMan.config.enable_remote_macro?
6
+ attr_reader :distributed_queue
34
7
 
35
- drb.push(value)
8
+ # @override
9
+ def self.enable?
10
+ ProconBypassMan.config.enable_remote_macro?
36
11
  end
37
12
 
38
- def self.pop
39
- return unless ProconBypassMan.config.enable_remote_macro?
13
+ # @override
14
+ def self.distributed_class
15
+ Queue
16
+ end
40
17
 
41
- drb.pop
18
+ # @override
19
+ def self.socket_file_path
20
+ "/tmp/procon_bypass_man_remote_macro_queue".freeze
42
21
  end
43
22
 
44
- def self.drb
45
- return unless ProconBypassMan.config.enable_remote_macro?
23
+ def self.push(value)
24
+ return unless enable?
46
25
 
47
- @@drb ||= new.drb
26
+ instance.distributed_queue.push(value)
48
27
  end
49
28
 
50
- PROTOCOL = "drbunix"
51
- def self.url
52
- "#{PROTOCOL}:/tmp/procon_bypass_man_queue"
29
+ def self.pop
30
+ return unless enable?
31
+
32
+ instance.distributed_queue.pop
53
33
  end
54
34
 
55
- def self.file_path
56
- url.gsub("#{PROTOCOL}:", "")
35
+ def self.clear
36
+ return unless enable?
37
+
38
+ instance.distributed_queue.clear
57
39
  end
58
40
 
59
41
  def initialize
60
- @drb = DRbObject.new_with_uri(self.class.url)
42
+ @distributed_queue = DRbObject.new_with_uri(self.class.socket_path)
61
43
  end
62
44
  end
@@ -1,30 +1,28 @@
1
- module ProconBypassMan
2
- class RemoteMacroObject
3
- # valueobjectがvalidatorの責務も持っている. 今度分離する
4
- class ValidationError < StandardError; end
5
- class MustBeNotNilError < ValidationError; end
6
- class NonSupportAction < ValidationError; end
1
+ class ProconBypassMan::RemoteMacro::RemoteMacroObject
2
+ # valueobjectがvalidatorの責務も持っている. 今度分離する
3
+ class ValidationError < StandardError; end
4
+ class MustBeNotNilError < ValidationError; end
5
+ class NonSupportAction < ValidationError; end
7
6
 
8
- attr_accessor :name, :uuid, :steps
7
+ attr_accessor :name, :uuid, :steps
9
8
 
10
- # @param [String] name
11
- # @param [String] uuid
12
- # @param [Array] steps
13
- def initialize(name: , uuid:, steps: )
14
- @name = name
15
- @uuid = uuid
16
- @steps = steps
17
- freeze
18
- end
9
+ # @param [String] name
10
+ # @param [String] uuid
11
+ # @param [Array] steps
12
+ def initialize(name: , uuid:, steps: )
13
+ @name = name
14
+ @uuid = uuid
15
+ @steps = steps
16
+ freeze
17
+ end
19
18
 
20
- # @raise [MustBeNotNilError]
21
- # @raise [NonSupportAction]
22
- # @return [void]
23
- def validate!
24
- self.uuid or raise MustBeNotNilError, "uuidは値が必須です"
25
- unless self.steps.is_a?(Array)
26
- raise ValidationError, "stepsは配列です"
27
- end
19
+ # @raise [MustBeNotNilError]
20
+ # @raise [NonSupportAction]
21
+ # @return [void]
22
+ def validate!
23
+ self.uuid or raise MustBeNotNilError, "uuidは値が必須です"
24
+ unless self.steps.is_a?(Array)
25
+ raise ValidationError, "stepsは配列です"
28
26
  end
29
27
  end
30
28
  end
@@ -15,7 +15,7 @@ class ProconBypassMan::RemoteMacroReceiver
15
15
  end
16
16
 
17
17
  def self.run
18
- while(task = ProconBypassMan::QueueOverProcess.pop)
18
+ while(task = ProconBypassMan::RemoteMacro::QueueOverProcess.pop)
19
19
  receive(task)
20
20
  end
21
21
  shutdown
@@ -1,7 +1,7 @@
1
1
  class ProconBypassMan::RemoteMacroSender
2
2
  def self.execute(name: , uuid: , steps: )
3
3
  ProconBypassMan.logger.info "[remote macro][sender] name: #{name}, uuid: #{uuid}, steps: #{steps}"
4
- ProconBypassMan::QueueOverProcess.push(
4
+ ProconBypassMan::RemoteMacro::QueueOverProcess.push(
5
5
  ProconBypassMan::RemoteMacro::Task.new(name, uuid, steps)
6
6
  )
7
7
  end
@@ -1,6 +1,2 @@
1
- module ProconBypassMan
2
- module RemoteMacro
3
- class Task < Struct.new(:name, :uuid, :steps)
4
- end
5
- end
1
+ class ProconBypassMan::RemoteMacro::Task < ::Struct.new(:name, :uuid, :steps)
6
2
  end
@@ -1,13 +1,9 @@
1
- module ProconBypassMan
2
- module RemoteMacro
3
- class TaskQueue < ::Queue
4
- def present?
5
- not empty?
6
- end
1
+ class ProconBypassMan::RemoteMacro::TaskQueue < ::Queue
2
+ def present?
3
+ not empty?
4
+ end
7
5
 
8
- def non_blocking_shift
9
- present? && shift
10
- end
11
- end
6
+ def non_blocking_shift
7
+ present? && shift
12
8
  end
13
9
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ProconBypassMan
2
4
  module RemoteMacro
3
5
  require "procon_bypass_man/remote_macro/remote_macro_object"
@@ -10,7 +10,7 @@ module ProconBypassMan
10
10
  def execute(to_status: )
11
11
  ProconBypassMan::UpdateRemotePbmActionStatusHttpClient.new(
12
12
  path: path,
13
- server_pool: ProconBypassMan.config.server_pool,
13
+ server: ProconBypassMan.config.api_server,
14
14
  ).put(to_status: to_status)
15
15
  end
16
16
 
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ProconBypassMan
2
4
  module RemotePbmAction
3
5
  require "procon_bypass_man/remote_pbm_action/base_action"
@@ -1,8 +1,4 @@
1
- require_relative "io_monitor"
2
-
3
1
  class ProconBypassMan::Runner
4
- class InterruptForRestart < StandardError; end
5
-
6
2
  include ProconBypassMan::SignalHandler
7
3
 
8
4
  def initialize(gadget: , procon: )
@@ -24,14 +20,12 @@ class ProconBypassMan::Runner
24
20
 
25
21
  loop do
26
22
  # NOTE メインプロセスではThreadをいくつか起動しているので念のためパフォーマンスを優先するためにforkしていく
27
- child_pid = Kernel.fork {
23
+ child_pid = Kernel.fork do
28
24
  $will_terminate_token = false
29
- DRb.start_service if defined?(DRb)
30
- ProconBypassMan::RemoteMacroReceiver.start!
31
- ProconBypassMan::ProconDisplay::Server.start!
25
+ ProconBypassMan.after_fork_on_bypass_process
32
26
  ProconBypassMan::BypassCommand.new(gadget: @gadget, procon: @procon).execute # ここでblockingする
33
27
  next
34
- }
28
+ end
35
29
 
36
30
  begin
37
31
  # TODO 子プロセスが消滅した時に、メインプロセスは生き続けてしまい、何もできなくなる問題がある
@@ -39,7 +33,7 @@ class ProconBypassMan::Runner
39
33
  signal = readable_io.first[0].gets.strip
40
34
  handle_signal(signal)
41
35
  end
42
- rescue InterruptForRestart
36
+ rescue ProconBypassMan::InterruptForRestart
43
37
  ProconBypassMan::PrintMessageCommand.execute(text: "設定ファイルの再読み込みを開始します")
44
38
  Process.kill("USR2", child_pid)
45
39
  Process.wait
@@ -68,13 +68,22 @@ module ProconBypassMan
68
68
  end
69
69
 
70
70
  def self.register_schedules
71
- register(
72
- schedule: Schedule.new(
73
- klass: ProconBypassMan::SyncDeviceStatsJob,
74
- args: [->{ ProconBypassMan::DeviceStatus.current }],
75
- interval: 60,
71
+ if ProconBypassMan.config.has_api_server?
72
+ register(
73
+ schedule: Schedule.new(
74
+ klass: ProconBypassMan::SyncDeviceStatsJob,
75
+ args: [->{ ProconBypassMan::DeviceStatus.current }],
76
+ interval: 60,
77
+ )
76
78
  )
77
- ) if ProconBypassMan.config.has_api_server?
79
+ register(
80
+ schedule: Schedule.new(
81
+ klass: ProconBypassMan::ReportProconPerformanceMeasurementsJob,
82
+ args: [->{ ProconBypassMan::Procon::PerformanceMeasurement.pop_measurement_collection }],
83
+ interval: 60,
84
+ )
85
+ )
86
+ end
78
87
  end
79
88
 
80
89
  # @param [Schedule] schedule
@@ -1,21 +1,17 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module ProconBypassMan
2
- module Callbacks
3
- class CallbacksChain
4
- attr_accessor :filter, :chain_method
5
- def initialize(filter: , chain_method: , block: )
6
- @filter = filter
7
- @chain_method = chain_method
8
- @block = block
9
- end
10
- end
4
+ module CallbacksRegisterable
5
+ attr_accessor :callbacks
11
6
 
12
- # TODO __callbacksをincludeしたクラス側で保持する. 今はnemespaceがない
13
- module M
14
- class << self
15
- attr_accessor :__callbacks
16
- end
7
+ def register_callback_module(mod)
8
+ self.callbacks ||= []
9
+ callbacks << mod
10
+ self.include(mod)
17
11
  end
12
+ end
18
13
 
14
+ module Callbacks
19
15
  module ClassMethods
20
16
  def define_callbacks(name)
21
17
  self.singleton_class.attr_accessor "_#{name}_callbacks"
@@ -29,8 +25,9 @@ module ProconBypassMan
29
25
  end
30
26
 
31
27
  def set_callback(kind, filter, chain_method, &block)
32
- ProconBypassMan::Callbacks::M.__callbacks ||= {}
33
- ProconBypassMan::Callbacks::M.__callbacks[kind] = CallbacksChain.new(
28
+ self.__callbacks ||= {}
29
+ self.__callbacks[kind] ||= CallbackChain.new
30
+ self.__callbacks[kind].append Callback.new(
34
31
  filter: filter,
35
32
  chain_method: chain_method,
36
33
  block: block,
@@ -38,33 +35,81 @@ module ProconBypassMan
38
35
  end
39
36
  end
40
37
 
38
+ def self.included(mod)
39
+ mod.singleton_class.attr_accessor :__callbacks
40
+ mod.extend(ClassMethods)
41
+ end
42
+
43
+ class CallbackChain
44
+ attr_accessor :callbacks
45
+
46
+ def initialize
47
+ self.callbacks = {}
48
+ end
49
+
50
+ def empty?
51
+ callbacks.empty?
52
+ end
53
+
54
+ def append(callback)
55
+ self.callbacks[callback.filter] ||= []
56
+ self.callbacks[callback.filter] << callback
57
+ end
58
+
59
+ def [](filter)
60
+ self.callbacks[filter]
61
+ end
62
+ end
63
+
64
+ class Callback
65
+ attr_accessor :filter, :chain_method
66
+
67
+ def initialize(filter: , chain_method: , block: )
68
+ @filter = filter
69
+ @chain_method = chain_method
70
+ @block = block
71
+ end
72
+ end
73
+
41
74
  # TODO haltしたらcallbackを止める
42
- # TODO 複数をチェインできるようにする
43
75
  def run_callbacks(kind, &block)
44
- chain = get_callbacks(kind) or raise("unknown callback")
45
- case chain.filter
46
- when :before
76
+ chains = get_callbacks(kind) or raise("unknown callback")
77
+ if chains.nil? || chains.empty?
78
+ return block.call
79
+ end
80
+
81
+ chains[:before]&.each do |chain|
47
82
  send chain.chain_method
48
- block.call
49
- when :after
50
- block.call
83
+ end
84
+ result = block.call
85
+ chains[:after]&.each do |chain|
51
86
  send chain.chain_method
52
- else
53
- raise("unknown filter")
54
87
  end
55
- end
56
88
 
57
- # def __run_callbacks__(name, &block)
58
- # puts "called"
59
- # end
89
+ return result
90
+ end
60
91
 
61
92
  def get_callbacks(kind) # :nodoc:
62
- ProconBypassMan::Callbacks::M.__callbacks[kind.to_sym]
63
- end
93
+ # classに直接moduleをincludeしている場合
94
+ if defined?(self.class.__callbacks) && !self.class.respond_to?(:callbacks)
95
+ return self.class.__callbacks[kind.to_sym]
96
+ end
64
97
 
65
- def set_callbacks(name, callbacks) # :nodoc:
66
- send "_#{name}_callbacks=", callbacks
67
- ProconBypassMan::Callbacks::M.__callbacks[kind.to_sym] = callbacks
98
+ list =
99
+ if self.class.callbacks.nil?
100
+ []
101
+ else
102
+ self.class.callbacks.flat_map { |callback_mod|
103
+ callback_mod.__callbacks && callback_mod.__callbacks[kind.to_sym]
104
+ }.compact
105
+ end
106
+ if(self.class.respond_to?(:__callbacks) && chain = self.class.__callbacks[kind.to_sym])
107
+ list << chain
108
+ end
109
+ table = {}
110
+ table[:before] = list.flat_map { |x| x[:before] }.compact
111
+ table[:after] = list.flat_map { |x| x[:after] }.compact
112
+ table
68
113
  end
69
114
  end
70
115
  end
@@ -0,0 +1,60 @@
1
+ require 'drb/drb'
2
+
3
+ # NOTE マスタープロセスでstart_distributed_object!をコールする必要がある
4
+ # forkをしたらそのさきでDRb.start_serviceをコールする必要がある
5
+ module ProconBypassMan::CanOverProcess
6
+ PROTOCOL = "drbunix".freeze
7
+
8
+ def self.extended(mod)
9
+ mod.singleton_class.attr_accessor :drb_server, :drb_server_thread
10
+ end
11
+
12
+ # @return [void]
13
+ def start_distributed_object!
14
+ return unless enable?
15
+
16
+ FileUtils.rm_rf(socket_file_path) if File.exist?(socket_file_path)
17
+ begin
18
+ self.drb_server = DRb.start_service(socket_path, distributed_class.new, safe_level: 1)
19
+ rescue Errno::EADDRINUSE => e
20
+ ProconBypassMan.logger.error e
21
+ raise
22
+ end
23
+
24
+ self.drb_server_thread =
25
+ Thread.new do
26
+ DRb.thread.join
27
+ end
28
+ end
29
+ alias start! start_distributed_object!
30
+
31
+ # @return [void]
32
+ def shutdown_distributed_object
33
+ if self.drb_server
34
+ self.drb_server_thread&.kill
35
+ self.drb_server_thread = nil
36
+ self.drb_server.stop_service
37
+ end
38
+ end
39
+ alias shutdown shutdown_distributed_object
40
+
41
+ # @return [Boolean]
42
+ def enable?
43
+ raise NotImplementedError
44
+ end
45
+
46
+ # @return [String]
47
+ def socket_file_path
48
+ raise NotImplementedError
49
+ end
50
+
51
+ # @return [any]
52
+ def distributed_class
53
+ raise NotImplementedError
54
+ end
55
+
56
+ # @return [String]
57
+ def socket_path
58
+ "#{PROTOCOL}:#{socket_file_path}".freeze
59
+ end
60
+ end
@@ -0,0 +1,8 @@
1
+ class ProconBypassMan::GC
2
+ def self.stop_gc_in(&block)
3
+ ::GC.disable
4
+ result = block.call
5
+ ::GC.enable
6
+ return result
7
+ end
8
+ end
@@ -26,14 +26,15 @@ module ProconBypassMan
26
26
  end
27
27
  end
28
28
 
29
- def initialize(path: , server_pool: , retry_on_connection_error: false)
30
- @server_pool = server_pool
31
- @uri = URI.parse("#{server_pool.server}#{path}")
29
+ def initialize(path: , server: , retry_on_connection_error: false)
30
+ @server = server
31
+ @uri = URI.parse("#{server}#{path}")
32
32
  @retry_on_connection_error = retry_on_connection_error
33
33
  end
34
34
 
35
35
  def get
36
36
  handle_request do
37
+ ProconBypassMan.logger.info "[HTTP] GET #{@uri}"
37
38
  response = HttpRequest::Get.request!(
38
39
  uri: @uri,
39
40
  )
@@ -44,6 +45,7 @@ module ProconBypassMan
44
45
  def post(request_body: )
45
46
  handle_request do
46
47
  body = {}.merge!(request_body)
48
+ ProconBypassMan.logger.info "[HTTP] POST #{@uri}"
47
49
  response = HttpRequest::Post.request!(
48
50
  uri: @uri,
49
51
  request_body: body,
@@ -57,6 +59,7 @@ module ProconBypassMan
57
59
  body = {
58
60
  hostname: `hostname`.chomp,
59
61
  }.merge!(request_body)
62
+ ProconBypassMan.logger.info "[HTTP] PUT #{@uri}"
60
63
  response = HttpRequest::Put.request!(
61
64
  uri: @uri,
62
65
  request_body: body,
@@ -76,14 +79,13 @@ module ProconBypassMan
76
79
  return response.body
77
80
  end
78
81
  else
79
- @server_pool.next!
80
82
  ProconBypassMan.logger.error("#{@uri}から200以外(#{response.code})が帰ってきました. #{response.body}")
81
83
  end
82
84
  end
83
85
 
84
86
  def handle_request
85
87
  raise "need block" unless block_given?
86
- if @server_pool.server.nil?
88
+ if @server.nil?
87
89
  ProconBypassMan.logger.info('送信先が未設定なのでスキップしました')
88
90
  return
89
91
  end
@@ -94,6 +96,10 @@ module ProconBypassMan
94
96
  sleep(10)
95
97
  retry
96
98
  end
99
+ rescue Timeout::Error
100
+ ProconBypassMan.logger.error(e)
101
+ sleep(10)
102
+ retry
97
103
  rescue => e
98
104
  puts e
99
105
  ProconBypassMan.logger.error(e)
@@ -102,5 +108,5 @@ module ProconBypassMan
102
108
  end
103
109
 
104
110
  if $0 == __FILE__
105
- ProconBypassMan::HttpClient.new(path: '/', server_pool: nil, retry_on_connection_error: false).get(response_body: '')
111
+ ProconBypassMan::HttpClient.new(path: '/', server: nil, retry_on_connection_error: false).get(response_body: '')
106
112
  end