class Observer
Shared memory observer for utilization metrics.
Writes metrics to shared memory using a schema to define the serialization layout. The schema is required to know how to serialize values efficiently.
Definitions
def self.open(schema, path, size, offset)
Open a shared memory observer from a file.
Maps the shared memory file and creates an Observer instance. The file descriptor is closed after mapping - the memory mapping persists independently on Unix/Linux systems.
Note: mmap requires page-aligned offsets and sizes. This method handles non-page-aligned offsets by mapping from the nearest page boundary and adjusting field offsets accordingly.
Signature
-
parameter
schemaSchema The schema defining field types and layout.
-
parameter
pathString Path to the shared memory file.
-
parameter
sizeInteger Size of the shared memory region to map.
-
parameter
offsetInteger Offset into the shared memory buffer.
-
returns
Observer A new Observer instance.
Implementation
def self.open(schema, path, size, offset)
page_size = IO::Buffer::PAGE_SIZE
# Round offset down to nearest page boundary:
page_aligned_offset = (offset / page_size) * page_size
offset_adjustment = offset - page_aligned_offset
# Calculate how many pages we need to cover the segment:
segment_end = offset + size
page_aligned_end = ((segment_end + page_size - 1) / page_size) * page_size
# Ensure we map at least one full page:
map_size = [page_aligned_end - page_aligned_offset, page_size].max
buffer = File.open(path, "r+b") do |file|
mapped_buffer = IO::Buffer.map(file, map_size, page_aligned_offset)
# If we had to adjust the offset, create a view into the buffer:
if offset_adjustment > 0 || map_size > size
mapped_buffer.slice(offset_adjustment, size)
else
mapped_buffer
end
end
new(schema, buffer)
end
def initialize(schema, buffer)
Initialize a new shared memory observer.
Signature
-
parameter
schemaSchema The schema defining field types and layout.
-
parameter
bufferIO::Buffer The mapped buffer for shared memory.
Implementation
def initialize(schema, buffer)
@schema = schema
@buffer = buffer
end
attr :schema
Signature
-
attribute
Schema The schema used for serialization.
attr :buffer
Signature
-
attribute
IO::Buffer The mapped buffer for shared memory.
def set(field, value)
Set a field value.
Writes the value to shared memory at the offset defined by the schema. Only fields defined in the schema will be written.
Signature
-
parameter
fieldSymbol The field name to set.
-
parameter
valueNumeric The value to set.
Implementation
def set(field, value)
if field = @schema[field]
@buffer.set_value(field.type, field.offset, value)
end
rescue => error
Console.warn(self, "Failed to set field in shared memory!", field: field, exception: error)
end