Top Level Namespace
Defined Under Namespace
Modules: AsyncTaskOTELPatch, DebugKeepThreadsRunning, DebugPreloadHandshake, DebugPreloadSession, DebugPreloadSources, DebugResetCdpCache, DebugResetCdpOnHandshake, DebugSkipMissingSources, Enumerable, FixedCdpUuid, FixedChromeUuid, IdempotentMigration, McpHelper, NATS, PrometheusParser, Rack, RackHelpers, RpcErrorHelpers, SSBase, Sequel, Sinatra, SkipMissingRegexBreakpoints, StackServiceBase, ToolRegistry
Classes: DProxy, FiberConnectionPool, JsonRpcError, McpProcessor, Otel, Thread, Time
Constant Summary
collapse
- QUIET =
ENV.fetch('QUIET', 'false') == 'true'
- PERFORMANCE =
ENV.fetch('PERFORMANCE', 'false') == 'true'
- CONSOLE_LOGGER =
ENV ||= ‘XTerm’ # JSON,Text,XTerm,Default
Class.new {
def <<(...) = Console.logger.info(...)
def info(...) = Console.logger.info(...)
def debug(...) = Console.logger.debug(...)
def debug1(...) = Console.logger.debug(...)
def debug2(...) = Console.logger.debug(...)
def debug3(...) = Console.logger.debug(...)
def warn(...) = Console.logger.warn(...)
def error(...) = Console.logger.error(...)
def fatal(...) = Console.logger.fatal(...)
def exception(subject, e)
Console.logger.error subject, e
end
}.new
- LOGGER =
Class.new {
def initialize = @context_list ||= {}
def add_context(name)
task = Async::Task.current?
@context_list[task.__id__] = name
end
def find_context
return '' unless Thread.current[:async_task]
t_stack = [Async::Task.current]
t_stack << t_stack.last.parent while t_stack.last.parent
task = t_stack.find { @context_list[_1.__id__] }
task ? " [#{@context_list[task.__id__]}] " : ''
end
def <<(...) = do_log(:info, ...)
def info(...) = do_log(:info, ...)
def debug(...) = do_log(:debug, ...)
def debug1(...) = do_log(:debug1, ...)
def debug2(...) = do_log(:debug2, ...)
def debug3(...) = do_log(:debug3, ...)
def warn(...) = do_log(:warn, ...)
def error(...) = do_log(:error, ...)
def fatal(...) = do_log(:fatal, ...)
def exception(subject, e)
do_log(:error, subject, e)
end
def do_log(name, prefix_, *args)
prefix = prefix_.class == String ? prefix_ : prefix_.inspect
if prefix_.kind_of? Exception
prefix = prefix_.message
args << prefix_
end
debug_level = name[/(\d+)/, 1].to_i
unless debug_level > LOG_DEPTH
if TRACE_METHODS
call_stack = Thread.current[:call_stack] ||= {}
call_stack_fiber = call_stack[Fiber.current.__id__] ||= []
last = call_stack_fiber[-3] ? call_stack_fiber[-3].join('.').gsub('Class:', '').gsub(/[#<>]/, '') : ''
last += find_context
msg = "\e[33m#{last}:\e[0m \e[38;5;254m#{prefix}"
else
msg = "#{prefix}"
end
_name = name.to_s.gsub(/\d/, '')
_name = 'info' if _name == '<<'
Console.logger.send _name.to_s.gsub(/\d/, ''), msg, *args
end
end
}.new
- LOGGER_GRAPE =
Class.new {
def method_missing(name, d)
Console.logger.send name, "REST_API: #{d[:method]} #{d[:path]} #{d[:params]} - #{d[:status]} host:#{d[:host]} time:#{d[:time]}"
end
}.new
- NATS_ENABLED =
ENV['SWARM_NATS_URL'].to_s != ''
- SWARM_NATS_URL =
|| ‘nats://nats_single:4222’
ENV['SWARM_NATS_URL']
- NATS_STACK_NAME =
ENV['STACK_NAME'] || 'undefined_stack'
- NATS_SERVICE_NAME =
ENV['STACK_SERVICE_NAME'] || 'undefined_service'
- Geometry =
Sequel::Postgres::GeoDatabaseMethods::Geometry
- MCP_PROCESSOR =
McpProcessor.new
- OTEL_ENABLED =
!ENV['OTEL_EXPORTER_OTLP_ENDPOINT'].to_s.empty?
- STACK_NAME =
ENV['STACK_NAME'] || 'undefined_stack'
- SERVICE_NAME =
ENV['STACK_SERVICE_NAME'] || 'undefined_service'
- HOSTNAME =
ENV['HOSTNAME'] || 'undefined'
Instance Method Summary
collapse
-
#async(name) ⇒ Object
Usage: async def foo(a,b,c).
-
#exec_i(cmd, input_string = nil, &block) ⇒ Object
-
#exec_o_lines(cmd) ⇒ Object
-
#flatten_hash(hash, path = [], result = {}) ⇒ Object
-
#initialize_nats_service ⇒ Object
-
#otel_initialize ⇒ Object
-
#otl_current_span {|OpenTelemetry::Trace.current_span| ... } ⇒ Object
-
#otl_def(name) ⇒ Object
-
#otl_span(name, attributes = {}, &block) ⇒ Object
-
#otl_span_thread(name, attributes = {}, &block) ⇒ Object
-
#otl_traceparent_id ⇒ Object
OpenTelemetry::Trace.current_span.tap do |span| span.record_exception(e) span.status = OpenTelemetry::Trace::Status.error(“Unhandled exception of type: #ee.class”) end.
-
#Tool(name, &block) ⇒ Object
Instance Method Details
#async(name) ⇒ Object
Usage:
async def foo(a,b,c)
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/stack-service-base/async_helpers.rb', line 18
def async(name)
original_method = self.respond_to?(:instance_method) ? instance_method(name) : method(name)
self.respond_to?(:remove_method) ? remove_method(name) : Object.send(:remove_method, name)
original_method = original_method.respond_to?(:unbind) ? original_method.unbind : original_method
define_method(name) do |*args, **kwargs, &block|
Async do
original_method.bind(self).call(*args, **kwargs, &block)
end
end
end
|
#exec_i(cmd, input_string = nil, &block) ⇒ Object
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# File 'lib/stack-service-base/command_line.rb', line 5
def exec_i(cmd, input_string = nil, &block)
puts "exec_i(inputs.size #{input_string&.size}): #{cmd}"
Open3.popen3(cmd) do |i, o, e, wait_thr|
std_out, std_err = '', ''
i.puts input_string unless input_string.nil?
i.close
while line = o.gets; puts "o: #{line}"; std_out += "#{line}\n" end
while line = e.gets; puts "o: #{line}"; std_err += "#{line}\n" end
return_value = wait_thr.value
puts "Error level was: #{return_value.exitstatus}" unless return_value.success?
if block_given?
block.call return_value, std_out, std_err
else
exit return_value.exitstatus unless return_value.success?
end
end
end
|
#exec_o_lines(cmd) ⇒ Object
24
25
26
27
28
29
30
|
# File 'lib/stack-service-base/command_line.rb', line 24
def exec_o_lines(cmd,&)
IO.popen(cmd, 'r') do |f|
f.each_line do |line|
yield line
end
end
end
|
#flatten_hash(hash, path = [], result = {}) ⇒ Object
76
77
78
79
80
81
82
83
84
|
# File 'lib/stack-service-base/open_telemetry.rb', line 76
def flatten_hash(hash, path = [], result = {})
hash.each do |k, v|
path += [k]
result[path.join('.')] = v.to_s if v.is_a?(String) || v.is_a?(Numeric)
flatten_hash(v, path, result) if v.is_a?(Hash) || v.is_a?(Array)
path.pop
end
result
end
|
#initialize_nats_service ⇒ Object
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# File 'lib/stack-service-base/nats_service.rb', line 20
def initialize_nats_service
LOGGER.info "Initializing NATS service"
$nats_client = NATS.connect SWARM_NATS_URL
service = $nats_client.services.add(
name: "#{NATS_SERVICE_NAME}_#{NATS_STACK_NAME}",
version: "1.0.0",
description: "service-base auto service"
)
service.on_stop do
puts "Service stopped at #{Time.now}"
end
service.endpoints.add("min") do |message|
min = JSON.parse(message.data).min
message.respond(min.to_json)
end
service.endpoints.add("max") do |message|
max = JSON.parse(message.data).max
message.respond(max.to_json)
end
min = $nats_client.request("min", [5, 100, -7, 34].to_json, timeout: 10)
max = $nats_client.request("max", [5, 100, -7, 34].to_json, timeout: 10)
puts "min = #{min.data}, max = #{max.data}"
end
|
#otel_initialize ⇒ Object
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
|
# File 'lib/stack-service-base/open_telemetry.rb', line 90
def otel_initialize
$stdout.puts "otl_configure: OTEL_ENABLED: #{OTEL_ENABLED}"
return unless OTEL_ENABLED
OpenTelemetry::SDK.configure do |c|
OpenTelemetry::Instrumentation::Rack
OpenTelemetry::Instrumentation::Sinatra
c.use_all({
'OpenTelemetry::Instrumentation::Sinatra' => { install_rack: false }, 'OpenTelemetry::Instrumentation::Rack' => {
use_rack_events: false, url_quantization: ->(path, env) { "HTTP #{env['REQUEST_METHOD']} #{path}" },
untraced_requests: ->(env) { env['HTTP_UPGRADE'] == 'websocket' }
}
})
end
if ENV['OTEL_LOGS_EXPORTER'] =~ /console/
processor = OpenTelemetry::SDK::Logs::Export::SimpleLogRecordProcessor.new(OpenTelemetry::SDK::Logs::Export::ConsoleLogRecordExporter.new)
OpenTelemetry.logger_provider.add_log_record_processor(processor)
end
logger = OpenTelemetry.logger_provider.logger(name: SERVICE_NAME, version: '0.1.0')
logger.on_emit( timestamp: Time.now, severity_text: 'INFO', body: 'Log provider initialized ', attributes: { 'ready' => true } )
at_exit do
OpenTelemetry.tracer_provider.force_flush
OpenTelemetry.tracer_provider.shutdown
OpenTelemetry.logger_provider.shutdown
end
$tracer_ = OpenTelemetry.tracer_provider.tracer(SERVICE_NAME)
otl_span "#{SERVICE_NAME} start", {
'stack.name': ENV['STACK_NAME'],
'stack.service.name': ENV['STACK_SERVICE_NAME'],
'org.opencontainers.image.title': ENV['ORG_OPENCONTAINERS_IMAGE_TITLE'],
'org.opencontainers.image.url': ENV['ORG_OPENCONTAINERS_IMAGE_URL'],
'org.opencontainers.image.source': ENV['ORG_OPENCONTAINERS_IMAGE_SOURCE'],
'org.opencontainers.image.created': ENV['ORG_OPENCONTAINERS_IMAGE_CREATED'],
'com.gitlab.ci.commt.timestamp': ENV['COM_GITLAB_CI_COMMIT_TIMESTAMP'],
'com.gitlab.ci.tag': ENV['COM_GITLAB_CI_TAG'],
RACK_ENV: ENV['RACK_ENV'],
NODE_ENV: ENV['NODE_ENV'],
SERVER_ENV: ENV['SERVER_ENV'],
} do |span|
span.add_event("not-working in kibana APM", attributes:{
event: 'Success',
message: 'Get data from elastic Success'
}.transform_keys(&:to_s) )
end
end
|
#otl_current_span {|OpenTelemetry::Trace.current_span| ... } ⇒ Object
213
214
215
216
|
# File 'lib/stack-service-base/open_telemetry.rb', line 213
def otl_current_span
return unless OTEL_ENABLED && Otel.enabled
yield OpenTelemetry::Trace.current_span
end
|
#otl_def(name) ⇒ Object
233
234
235
236
237
238
239
240
241
242
243
244
|
# File 'lib/stack-service-base/open_telemetry.rb', line 233
def otl_def(name)
original_method = self.respond_to?(:instance_method) ? instance_method(name) : method(name)
self.respond_to?(:remove_method) ? remove_method(name) : Object.send(:remove_method, name)
original_method = original_method.respond_to?(:unbind) ? original_method.unbind : original_method
define_method(name) do |*args, **kwargs, &block|
klass = self.respond_to?(:class_name) ? self.class_name : (self.respond_to?(:name) ? self.name : 'main')
otl_span("method: #{klass}.#{name}", {args: args.to_s, kwargs: kwargs.to_s}) do |span|
original_method.bind(self).call(*args, **kwargs, &block)
end
end
end
|
#otl_span(name, attributes = {}, &block) ⇒ Object
203
204
205
206
207
208
209
210
211
|
# File 'lib/stack-service-base/open_telemetry.rb', line 203
def otl_span(name, attributes = {}, &block)
return yield(nil) unless OTEL_ENABLED && Otel.enabled
return yield(nil) unless $tracer_
$tracer_&.in_span(name, attributes: flatten_hash(attributes.transform_keys(&:to_s).transform_values{_1 || 'n/a'}) ) do |span|
yield span
end
end
|
#otl_span_thread(name, attributes = {}, &block) ⇒ Object
194
195
196
197
198
199
200
201
|
# File 'lib/stack-service-base/open_telemetry.rb', line 194
def otl_span_thread(name, attributes = {}, &block)
ctx_ = OpenTelemetry::Context.current
Thread.new do
OpenTelemetry::Context.with_current(ctx_) do
otl_span(name, attributes, &block)
end
end
end
|
#otl_traceparent_id ⇒ Object
OpenTelemetry::Trace.current_span.tap do |span|
span.record_exception(e)
span.status = OpenTelemetry::Trace::Status.error("Unhandled exception of type: #{e.class}")
end
223
224
225
226
227
228
229
230
231
|
# File 'lib/stack-service-base/open_telemetry.rb', line 223
def otl_traceparent_id
return nil unless OTEL_ENABLED && Otel.enabled
span_context = OpenTelemetry::Trace.current_span.context
trace_id = span_context.trace_id.unpack1('H*')
span_id = span_context.span_id.unpack1('H*')
trace_flags = format('%02x', span_context.trace_flags.instance_eval{ @flags }) "00-#{trace_id}-#{span_id}-#{trace_flags}"
end
|
82
83
84
|
# File 'lib/stack-service-base/mcp/mcp_tool_registry.rb', line 82
def Tool(name, &block)
ToolRegistry.define(name, &block)
end
|