1 # SPDX-License-Identifier: MIT
3 # Copyright (C) 2019 Philippe Proulx <pproulx@efficios.com>
6 # pyright: strict, reportTypeCommentUsage=false, reportMissingTypeStubs=false
17 from typing
import Dict
, Union
, Iterable
, Optional
, Sequence
, overload
22 from typing
import Any
, Callable
# noqa: F401
27 class UnexpectedInput(RuntimeError):
31 # An entry within the index of an LTTng data stream.
32 class _LttngDataStreamIndexEntry
:
37 content_size_bits
: int,
40 events_discarded
: int,
43 self
._offset
_bytes
= offset_bytes
44 self
._total
_size
_bits
= total_size_bits
45 self
._content
_size
_bits
= content_size_bits
46 self
._timestamp
_begin
= timestamp_begin
47 self
._timestamp
_end
= timestamp_end
48 self
._events
_discarded
= events_discarded
49 self
._stream
_class
_id
= stream_class_id
52 def offset_bytes(self
):
53 return self
._offset
_bytes
56 def total_size_bits(self
):
57 return self
._total
_size
_bits
60 def total_size_bytes(self
):
61 return self
._total
_size
_bits
// 8
64 def content_size_bits(self
):
65 return self
._content
_size
_bits
68 def content_size_bytes(self
):
69 return self
._content
_size
_bits
// 8
72 def timestamp_begin(self
):
73 return self
._timestamp
_begin
76 def timestamp_end(self
):
77 return self
._timestamp
_end
80 def events_discarded(self
):
81 return self
._events
_discarded
84 def stream_class_id(self
):
85 return self
._stream
_class
_id
88 # An entry within the index of an LTTng data stream. While a stream beacon entry
89 # is conceptually unrelated to an index, it is sent as a reply to a
90 # LttngLiveViewerGetNextDataStreamIndexEntryCommand
91 class _LttngDataStreamBeaconIndexEntry
:
92 def __init__(self
, stream_class_id
: int, timestamp
: int):
93 self
._stream
_class
_id
= stream_class_id
94 self
._timestamp
= timestamp
98 return self
._timestamp
101 def stream_class_id(self
):
102 return self
._stream
_class
_id
105 _LttngIndexEntryT
= Union
[_LttngDataStreamIndexEntry
, _LttngDataStreamBeaconIndexEntry
]
108 class _LttngLiveViewerCommand
:
109 def __init__(self
, version
: int):
110 self
._version
= version
117 class _LttngLiveViewerConnectCommand(_LttngLiveViewerCommand
):
118 def __init__(self
, version
: int, viewer_session_id
: int, major
: int, minor
: int):
119 super().__init
__(version
)
120 self
._viewer
_session
_id
= viewer_session_id
125 def viewer_session_id(self
):
126 return self
._viewer
_session
_id
137 class _LttngLiveViewerReply
:
141 class _LttngLiveViewerConnectReply(_LttngLiveViewerReply
):
142 def __init__(self
, viewer_session_id
: int, major
: int, minor
: int):
143 self
._viewer
_session
_id
= viewer_session_id
148 def viewer_session_id(self
):
149 return self
._viewer
_session
_id
160 class _LttngLiveViewerGetTracingSessionInfosCommand(_LttngLiveViewerCommand
):
164 class _LttngLiveViewerTracingSessionInfo
:
167 tracing_session_id
: int,
168 live_timer_freq
: int,
174 self
._tracing
_session
_id
= tracing_session_id
175 self
._live
_timer
_freq
= live_timer_freq
176 self
._client
_count
= client_count
177 self
._stream
_count
= stream_count
178 self
._hostname
= hostname
182 def tracing_session_id(self
):
183 return self
._tracing
_session
_id
186 def live_timer_freq(self
):
187 return self
._live
_timer
_freq
190 def client_count(self
):
191 return self
._client
_count
194 def stream_count(self
):
195 return self
._stream
_count
199 return self
._hostname
206 class _LttngLiveViewerGetTracingSessionInfosReply(_LttngLiveViewerReply
):
208 self
, tracing_session_infos
: Sequence
[_LttngLiveViewerTracingSessionInfo
]
210 self
._tracing
_session
_infos
= tracing_session_infos
213 def tracing_session_infos(self
):
214 return self
._tracing
_session
_infos
217 class _LttngLiveViewerAttachToTracingSessionCommand(_LttngLiveViewerCommand
):
223 self
, version
: int, tracing_session_id
: int, offset
: int, seek_type
: int
225 super().__init
__(version
)
226 self
._tracing
_session
_id
= tracing_session_id
227 self
._offset
= offset
228 self
._seek
_type
= seek_type
231 def tracing_session_id(self
):
232 return self
._tracing
_session
_id
240 return self
._seek
_type
243 class _LttngLiveViewerStreamInfo
:
245 self
, id: int, trace_id
: int, is_metadata
: bool, path
: str, channel_name
: str
248 self
._trace
_id
= trace_id
249 self
._is
_metadata
= is_metadata
251 self
._channel
_name
= channel_name
259 return self
._trace
_id
262 def is_metadata(self
):
263 return self
._is
_metadata
270 def channel_name(self
):
271 return self
._channel
_name
274 class _LttngLiveViewerAttachToTracingSessionReply(_LttngLiveViewerReply
):
283 def __init__(self
, status
: int, stream_infos
: Sequence
[_LttngLiveViewerStreamInfo
]):
284 self
._status
= status
285 self
._stream
_infos
= stream_infos
292 def stream_infos(self
):
293 return self
._stream
_infos
296 class _LttngLiveViewerGetNextDataStreamIndexEntryCommand(_LttngLiveViewerCommand
):
297 def __init__(self
, version
: int, stream_id
: int):
298 super().__init
__(version
)
299 self
._stream
_id
= stream_id
303 return self
._stream
_id
306 class _LttngLiveViewerGetNextDataStreamIndexEntryReply(_LttngLiveViewerReply
):
318 index_entry
: _LttngIndexEntryT
,
319 has_new_metadata
: bool,
320 has_new_data_stream
: bool,
322 self
._status
= status
323 self
._index
_entry
= index_entry
324 self
._has
_new
_metadata
= has_new_metadata
325 self
._has
_new
_data
_stream
= has_new_data_stream
332 def index_entry(self
):
333 return self
._index
_entry
336 def has_new_metadata(self
):
337 return self
._has
_new
_metadata
340 def has_new_data_stream(self
):
341 return self
._has
_new
_data
_stream
344 class _LttngLiveViewerGetDataStreamPacketDataCommand(_LttngLiveViewerCommand
):
345 def __init__(self
, version
: int, stream_id
: int, offset
: int, req_length
: int):
346 super().__init
__(version
)
347 self
._stream
_id
= stream_id
348 self
._offset
= offset
349 self
._req
_length
= req_length
353 return self
._stream
_id
360 def req_length(self
):
361 return self
._req
_length
364 class _LttngLiveViewerGetDataStreamPacketDataReply(_LttngLiveViewerReply
):
375 has_new_metadata
: bool,
376 has_new_data_stream
: bool,
378 self
._status
= status
380 self
._has
_new
_metadata
= has_new_metadata
381 self
._has
_new
_data
_stream
= has_new_data_stream
392 def has_new_metadata(self
):
393 return self
._has
_new
_metadata
396 def has_new_data_stream(self
):
397 return self
._has
_new
_data
_stream
400 class _LttngLiveViewerGetMetadataStreamDataCommand(_LttngLiveViewerCommand
):
401 def __init__(self
, version
: int, stream_id
: int):
402 super().__init
__(version
)
403 self
._stream
_id
= stream_id
407 return self
._stream
_id
410 class _LttngLiveViewerGetMetadataStreamDataContentReply(_LttngLiveViewerReply
):
416 def __init__(self
, status
: int, data
: bytes
):
417 self
._status
= status
429 class _LttngLiveViewerGetNewStreamInfosCommand(_LttngLiveViewerCommand
):
430 def __init__(self
, version
: int, tracing_session_id
: int):
431 super().__init
__(version
)
432 self
._tracing
_session
_id
= tracing_session_id
435 def tracing_session_id(self
):
436 return self
._tracing
_session
_id
439 class _LttngLiveViewerGetNewStreamInfosReply(_LttngLiveViewerReply
):
446 def __init__(self
, status
: int, stream_infos
: Sequence
[_LttngLiveViewerStreamInfo
]):
447 self
._status
= status
448 self
._stream
_infos
= stream_infos
455 def stream_infos(self
):
456 return self
._stream
_infos
459 class _LttngLiveViewerCreateViewerSessionCommand(_LttngLiveViewerCommand
):
463 class _LttngLiveViewerCreateViewerSessionReply(_LttngLiveViewerReply
):
468 def __init__(self
, status
: int):
469 self
._status
= status
476 class _LttngLiveViewerDetachFromTracingSessionCommand(_LttngLiveViewerCommand
):
477 def __init__(self
, version
: int, tracing_session_id
: int):
478 super().__init
__(version
)
479 self
._tracing
_session
_id
= tracing_session_id
482 def tracing_session_id(self
):
483 return self
._tracing
_session
_id
486 class _LttngLiveViewerDetachFromTracingSessionReply(_LttngLiveViewerReply
):
492 def __init__(self
, status
: int):
493 self
._status
= status
500 # An LTTng live protocol codec can convert bytes to command objects and
501 # reply objects to bytes.
502 class _LttngLiveViewerProtocolCodec
:
503 _COMMAND_HEADER_STRUCT_FMT
= "QII"
504 _COMMAND_HEADER_SIZE_BYTES
= struct
.calcsize(_COMMAND_HEADER_STRUCT_FMT
)
509 def _unpack(self
, fmt
: str, data
: bytes
, offset
: int = 0):
511 return struct
.unpack_from(fmt
, data
, offset
)
513 def _unpack_payload(self
, fmt
: str, data
: bytes
):
515 fmt
, data
, _LttngLiveViewerProtocolCodec
._COMMAND
_HEADER
_SIZE
_BYTES
518 def decode(self
, data
: bytes
):
519 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
:
520 # Not enough data to read the command header
523 payload_size
, cmd_type
, version
= self
._unpack
(
524 self
._COMMAND
_HEADER
_STRUCT
_FMT
, data
527 "Decoded command header: payload-size={}, cmd-type={}, version={}".format(
528 payload_size
, cmd_type
, version
532 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
+ payload_size
:
533 # Not enough data to read the whole command
537 viewer_session_id
, major
, minor
, _
= self
._unpack
_payload
("QIII", data
)
538 return _LttngLiveViewerConnectCommand(
539 version
, viewer_session_id
, major
, minor
542 return _LttngLiveViewerGetTracingSessionInfosCommand(version
)
544 tracing_session_id
, offset
, seek_type
= self
._unpack
_payload
("QQI", data
)
545 return _LttngLiveViewerAttachToTracingSessionCommand(
546 version
, tracing_session_id
, offset
, seek_type
549 (stream_id
,) = self
._unpack
_payload
("Q", data
)
550 return _LttngLiveViewerGetNextDataStreamIndexEntryCommand(
554 stream_id
, offset
, req_length
= self
._unpack
_payload
("QQI", data
)
555 return _LttngLiveViewerGetDataStreamPacketDataCommand(
556 version
, stream_id
, offset
, req_length
559 (stream_id
,) = self
._unpack
_payload
("Q", data
)
560 return _LttngLiveViewerGetMetadataStreamDataCommand(version
, stream_id
)
562 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
563 return _LttngLiveViewerGetNewStreamInfosCommand(version
, tracing_session_id
)
565 return _LttngLiveViewerCreateViewerSessionCommand(version
)
567 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
568 return _LttngLiveViewerDetachFromTracingSessionCommand(
569 version
, tracing_session_id
572 raise UnexpectedInput("Unknown command type {}".format(cmd_type
))
574 def _pack(self
, fmt
: str, *args
: Any
):
575 # Force network byte order
576 return struct
.pack("!" + fmt
, *args
)
578 def _encode_zero_padded_str(self
, string
: str, length
: int):
579 data
= string
.encode()
580 return data
.ljust(length
, b
"\x00")
582 def _encode_stream_info(self
, info
: _LttngLiveViewerStreamInfo
):
583 data
= self
._pack
("QQI", info
.id, info
.trace_id
, int(info
.is_metadata
))
584 data
+= self
._encode
_zero
_padded
_str
(info
.path
, 4096)
585 data
+= self
._encode
_zero
_padded
_str
(info
.channel_name
, 255)
588 def _get_has_new_stuff_flags(
589 self
, has_new_metadata
: bool, has_new_data_streams
: bool
596 if has_new_data_streams
:
603 reply
: _LttngLiveViewerReply
,
605 if type(reply
) is _LttngLiveViewerConnectReply
:
607 "QIII", reply
.viewer_session_id
, reply
.major
, reply
.minor
, 2
609 elif type(reply
) is _LttngLiveViewerGetTracingSessionInfosReply
:
610 data
= self
._pack
("I", len(reply
.tracing_session_infos
))
612 for info
in reply
.tracing_session_infos
:
615 info
.tracing_session_id
,
616 info
.live_timer_freq
,
620 data
+= self
._encode
_zero
_padded
_str
(info
.hostname
, 64)
621 data
+= self
._encode
_zero
_padded
_str
(info
.name
, 255)
622 elif type(reply
) is _LttngLiveViewerAttachToTracingSessionReply
:
623 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
625 for info
in reply
.stream_infos
:
626 data
+= self
._encode
_stream
_info
(info
)
627 elif type(reply
) is _LttngLiveViewerGetNextDataStreamIndexEntryReply
:
628 index_format
= "QQQQQQQII"
629 entry
= reply
.index_entry
630 flags
= self
._get
_has
_new
_stuff
_flags
(
631 reply
.has_new_metadata
, reply
.has_new_data_stream
634 if isinstance(entry
, _LttngDataStreamIndexEntry
):
638 entry
.total_size_bits
,
639 entry
.content_size_bits
,
640 entry
.timestamp_begin
,
642 entry
.events_discarded
,
643 entry
.stream_class_id
,
656 entry
.stream_class_id
,
660 elif type(reply
) is _LttngLiveViewerGetDataStreamPacketDataReply
:
661 flags
= self
._get
_has
_new
_stuff
_flags
(
662 reply
.has_new_metadata
, reply
.has_new_data_stream
664 data
= self
._pack
("III", reply
.status
, len(reply
.data
), flags
)
666 elif type(reply
) is _LttngLiveViewerGetMetadataStreamDataContentReply
:
667 data
= self
._pack
("QI", len(reply
.data
), reply
.status
)
669 elif type(reply
) is _LttngLiveViewerGetNewStreamInfosReply
:
670 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
672 for info
in reply
.stream_infos
:
673 data
+= self
._encode
_stream
_info
(info
)
674 elif type(reply
) is _LttngLiveViewerCreateViewerSessionReply
:
675 data
= self
._pack
("I", reply
.status
)
676 elif type(reply
) is _LttngLiveViewerDetachFromTracingSessionReply
:
677 data
= self
._pack
("I", reply
.status
)
680 "Unknown reply object with class `{}`".format(reply
.__class
__.__name
__)
686 def _get_entry_timestamp_begin(
687 entry
: _LttngIndexEntryT
,
689 if isinstance(entry
, _LttngDataStreamBeaconIndexEntry
):
690 return entry
.timestamp
692 return entry
.timestamp_begin
695 # The index of an LTTng data stream, a sequence of index entries.
696 class _LttngDataStreamIndex(Sequence
[_LttngIndexEntryT
]):
697 def __init__(self
, path
: str, beacons
: Optional
[tjson
.ArrayVal
]):
702 stream_class_id
= self
._entries
[0].stream_class_id
704 beacons_list
= [] # type: list[_LttngDataStreamBeaconIndexEntry]
705 for ts
in beacons
.iter(tjson
.IntVal
):
707 _LttngDataStreamBeaconIndexEntry(stream_class_id
, ts
.val
)
710 self
._add
_beacons
(beacons_list
)
713 'Built data stream index entries: path="{}", count={}'.format(
714 path
, len(self
._entries
)
719 self
._entries
= [] # type: list[_LttngIndexEntryT]
720 assert os
.path
.isfile(self
._path
)
722 with
open(self
._path
, "rb") as f
:
725 size
= struct
.calcsize(fmt
)
727 assert len(data
) == size
728 magic
, _
, _
, index_entry_length
= struct
.unpack(fmt
, data
)
729 assert magic
== 0xC1F1DCC1
733 size
= struct
.calcsize(fmt
)
737 'Decoding data stream index entry: path="{}", offset={}'.format(
747 assert len(data
) == size
756 ) = struct
.unpack(fmt
, data
)
758 self
._entries
.append(
759 _LttngDataStreamIndexEntry(
770 # Skip anything else before the next entry
771 f
.seek(index_entry_length
- size
, os
.SEEK_CUR
)
773 def _add_beacons(self
, beacons
: Iterable
[_LttngDataStreamBeaconIndexEntry
]):
774 # Assumes entries[n + 1].timestamp_end >= entries[n].timestamp_begin
776 entry
: Union
[_LttngDataStreamIndexEntry
, _LttngDataStreamBeaconIndexEntry
],
778 if isinstance(entry
, _LttngDataStreamBeaconIndexEntry
):
779 return entry
.timestamp
781 return entry
.timestamp_end
783 self
._entries
+= beacons
784 self
._entries
.sort(key
=sort_key
)
787 def __getitem__(self
, index
: int) -> _LttngIndexEntryT
:
791 def __getitem__(self
, index
: slice) -> Sequence
[_LttngIndexEntryT
]: # noqa: F811
794 def __getitem__( # noqa: F811
795 self
, index
: Union
[int, slice]
796 ) -> Union
[_LttngIndexEntryT
, Sequence
[_LttngIndexEntryT
],]:
797 return self
._entries
[index
]
800 return len(self
._entries
)
807 # An LTTng data stream.
808 class _LttngDataStream
:
809 def __init__(self
, path
: str, beacons_json
: Optional
[tjson
.ArrayVal
]):
811 filename
= os
.path
.basename(path
)
812 match
= re
.match(r
"(.*)_\d+", filename
)
815 "Unexpected data stream file name pattern: {}".format(filename
)
818 self
._channel
_name
= match
.group(1)
819 trace_dir
= os
.path
.dirname(path
)
820 index_path
= os
.path
.join(trace_dir
, "index", filename
+ ".idx")
821 self
._index
= _LttngDataStreamIndex(index_path
, beacons_json
)
822 assert os
.path
.isfile(path
)
823 self
._file
= open(path
, "rb")
825 'Built data stream: path="{}", channel-name="{}"'.format(
826 path
, self
._channel
_name
835 def channel_name(self
):
836 return self
._channel
_name
842 def get_data(self
, offset_bytes
: int, len_bytes
: int):
843 self
._file
.seek(offset_bytes
)
844 return self
._file
.read(len_bytes
)
847 class _LttngMetadataStreamSection
:
848 def __init__(self
, timestamp
: int, data
: Optional
[bytes
]):
849 self
._timestamp
= timestamp
855 "Built metadata stream section: ts={}, data-len={}".format(
856 self
._timestamp
, len(self
._data
)
862 return self
._timestamp
869 # An LTTng metadata stream.
870 class _LttngMetadataStream
:
873 metadata_file_path
: str,
874 config_sections
: Sequence
[_LttngMetadataStreamSection
],
876 self
._path
= metadata_file_path
877 self
._sections
= config_sections
879 "Built metadata stream: path={}, section-len={}".format(
880 self
._path
, len(self
._sections
)
890 return self
._sections
893 class LttngMetadataConfigSection
:
894 def __init__(self
, line
: int, timestamp
: int, is_empty
: bool):
896 self
._timestamp
= timestamp
897 self
._is
_empty
= is_empty
905 return self
._timestamp
909 return self
._is
_empty
912 def _parse_metadata_sections_config(metadata_sections_json
: tjson
.ArrayVal
):
913 metadata_sections
= [] # type: list[LttngMetadataConfigSection]
914 append_empty_section
= False
918 for section
in metadata_sections_json
:
919 if isinstance(section
, tjson
.StrVal
):
920 if section
.val
== "empty":
921 # Found a empty section marker. Actually append the section at the
922 # timestamp of the next concrete section.
923 append_empty_section
= True
925 raise ValueError("Invalid string value at {}.".format(section
.path
))
926 elif isinstance(section
, tjson
.ObjVal
):
927 line
= section
.at("line", tjson
.IntVal
).val
928 ts
= section
.at("timestamp", tjson
.IntVal
).val
930 # Sections' timestamps and lines must both be increasing.
931 assert ts
> last_timestamp
934 assert line
> last_line
937 if append_empty_section
:
938 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, True))
939 append_empty_section
= False
941 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, False))
944 "`{}`: expecting a string or object value".format(section
.path
)
947 return metadata_sections
950 def _split_metadata_sections(
951 metadata_file_path
: str, metadata_sections_json
: tjson
.ArrayVal
953 metadata_sections
= _parse_metadata_sections_config(metadata_sections_json
)
955 sections
= [] # type: list[_LttngMetadataStreamSection]
956 with
open(metadata_file_path
, "r") as metadata_file
:
957 metadata_lines
= [line
for line
in metadata_file
]
959 metadata_section_idx
= 0
960 curr_metadata_section
= bytearray()
962 for idx
, line_content
in enumerate(metadata_lines
):
963 # Add one to the index to convert from the zero-indexing of the
964 # enumerate() function to the one-indexing used by humans when
965 # viewing a text file.
966 curr_line_number
= idx
+ 1
968 # If there are no more sections, simply append the line.
969 if metadata_section_idx
+ 1 >= len(metadata_sections
):
970 curr_metadata_section
+= bytearray(line_content
, "utf8")
973 next_section_line_number
= metadata_sections
[metadata_section_idx
+ 1].line
975 # If the next section begins at the current line, create a
976 # section with the metadata we gathered so far.
977 if curr_line_number
>= next_section_line_number
:
978 # Flushing the metadata of the current section.
980 _LttngMetadataStreamSection(
981 metadata_sections
[metadata_section_idx
].timestamp
,
982 bytes(curr_metadata_section
),
986 # Move to the next section.
987 metadata_section_idx
+= 1
989 # Clear old content and append current line for the next section.
990 curr_metadata_section
.clear()
991 curr_metadata_section
+= bytearray(line_content
, "utf8")
993 # Append any empty sections.
994 while metadata_sections
[metadata_section_idx
].is_empty
:
996 _LttngMetadataStreamSection(
997 metadata_sections
[metadata_section_idx
].timestamp
, None
1000 metadata_section_idx
+= 1
1002 # Append line_content to the current metadata section.
1003 curr_metadata_section
+= bytearray(line_content
, "utf8")
1005 # We iterated over all the lines of the metadata file. Close the current section.
1007 _LttngMetadataStreamSection(
1008 metadata_sections
[metadata_section_idx
].timestamp
,
1009 bytes(curr_metadata_section
),
1016 _StreamBeaconsT
= Dict
[str, Iterable
[int]]
1019 # An LTTng trace, a sequence of LTTng data streams.
1020 class LttngTrace(Sequence
[_LttngDataStream
]):
1024 metadata_sections_json
: Optional
[tjson
.ArrayVal
],
1025 beacons_json
: Optional
[tjson
.ObjVal
],
1027 assert os
.path
.isdir(trace_dir
)
1028 self
._path
= trace_dir
1029 self
._create
_metadata
_stream
(trace_dir
, metadata_sections_json
)
1030 self
._create
_data
_streams
(trace_dir
, beacons_json
)
1031 logging
.info('Built trace: path="{}"'.format(trace_dir
))
1033 def _create_data_streams(
1034 self
, trace_dir
: str, beacons_json
: Optional
[tjson
.ObjVal
]
1036 data_stream_paths
= [] # type: list[str]
1038 for filename
in os
.listdir(trace_dir
):
1039 path
= os
.path
.join(trace_dir
, filename
)
1041 if not os
.path
.isfile(path
):
1044 if filename
.startswith("."):
1047 if filename
== "metadata":
1050 data_stream_paths
.append(path
)
1052 data_stream_paths
.sort()
1053 self
._data
_streams
= [] # type: list[_LttngDataStream]
1055 for data_stream_path
in data_stream_paths
:
1056 stream_name
= os
.path
.basename(data_stream_path
)
1057 this_beacons_json
= None
1058 if beacons_json
is not None and stream_name
in beacons_json
:
1059 this_beacons_json
= beacons_json
.at(stream_name
, tjson
.ArrayVal
)
1061 self
._data
_streams
.append(
1062 _LttngDataStream(data_stream_path
, this_beacons_json
)
1065 def _create_metadata_stream(
1066 self
, trace_dir
: str, metadata_sections_json
: Optional
[tjson
.ArrayVal
]
1068 metadata_path
= os
.path
.join(trace_dir
, "metadata")
1069 metadata_sections
= [] # type: list[_LttngMetadataStreamSection]
1071 if metadata_sections_json
is None:
1072 with
open(metadata_path
, "rb") as metadata_file
:
1073 metadata_sections
.append(
1074 _LttngMetadataStreamSection(0, metadata_file
.read())
1077 metadata_sections
= _split_metadata_sections(
1078 metadata_path
, metadata_sections_json
1081 self
._metadata
_stream
= _LttngMetadataStream(metadata_path
, metadata_sections
)
1088 def metadata_stream(self
):
1089 return self
._metadata
_stream
1092 def __getitem__(self
, index
: int) -> _LttngDataStream
:
1096 def __getitem__(self
, index
: slice) -> Sequence
[_LttngDataStream
]: # noqa: F811
1099 def __getitem__( # noqa: F811
1100 self
, index
: Union
[int, slice]
1101 ) -> Union
[_LttngDataStream
, Sequence
[_LttngDataStream
]]:
1102 return self
._data
_streams
[index
]
1105 return len(self
._data
_streams
)
1108 # The state of a single data stream.
1109 class _LttngLiveViewerSessionDataStreamState
:
1112 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1113 info
: _LttngLiveViewerStreamInfo
,
1114 data_stream
: _LttngDataStream
,
1115 metadata_stream_id
: int,
1117 self
._ts
_state
= ts_state
1119 self
._data
_stream
= data_stream
1120 self
._metadata
_stream
_id
= metadata_stream_id
1121 self
._cur
_index
_entry
_index
= 0
1122 fmt
= 'Built data stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1126 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1127 ts_state
.tracing_session_descriptor
.info
.name
,
1133 def tracing_session_state(self
):
1134 return self
._ts
_state
1141 def data_stream(self
):
1142 return self
._data
_stream
1145 def cur_index_entry(self
):
1146 if self
._cur
_index
_entry
_index
== len(self
._data
_stream
.index
):
1149 return self
._data
_stream
.index
[self
._cur
_index
_entry
_index
]
1152 def metadata_stream_id(self
):
1153 return self
._metadata
_stream
_id
1155 def goto_next_index_entry(self
):
1156 self
._cur
_index
_entry
_index
+= 1
1159 # The state of a single metadata stream.
1160 class _LttngLiveViewerSessionMetadataStreamState
:
1163 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1164 info
: _LttngLiveViewerStreamInfo
,
1165 metadata_stream
: _LttngMetadataStream
,
1167 self
._ts
_state
= ts_state
1169 self
._metadata
_stream
= metadata_stream
1170 self
._cur
_metadata
_stream
_section
_index
= 0
1171 if len(metadata_stream
.sections
) > 1:
1172 self
._next
_metadata
_stream
_section
_timestamp
= metadata_stream
.sections
[
1176 self
._next
_metadata
_stream
_section
_timestamp
= None
1178 self
._is
_sent
= False
1179 fmt
= 'Built metadata stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1183 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1184 ts_state
.tracing_session_descriptor
.info
.name
,
1185 metadata_stream
.path
,
1194 def metadata_stream(self
):
1195 return self
._metadata
_stream
1199 return self
._is
_sent
1202 def is_sent(self
, value
: bool):
1203 self
._is
_sent
= value
1206 def cur_section(self
):
1207 fmt
= "Get current metadata section: section-idx={}"
1208 logging
.info(fmt
.format(self
._cur
_metadata
_stream
_section
_index
))
1209 if self
._cur
_metadata
_stream
_section
_index
== len(
1210 self
._metadata
_stream
.sections
1214 return self
._metadata
_stream
.sections
[self
._cur
_metadata
_stream
_section
_index
]
1216 def goto_next_section(self
):
1217 self
._cur
_metadata
_stream
_section
_index
+= 1
1218 if self
.cur_section
:
1219 self
._next
_metadata
_stream
_section
_timestamp
= self
.cur_section
.timestamp
1221 self
._next
_metadata
_stream
_section
_timestamp
= None
1224 def next_section_timestamp(self
):
1225 return self
._next
_metadata
_stream
_section
_timestamp
1228 # A tracing session descriptor.
1230 # In the constructor, `traces` is a list of LTTng traces (`LttngTrace`
1232 class LttngTracingSessionDescriptor
:
1236 tracing_session_id
: int,
1238 live_timer_freq
: int,
1240 traces
: Iterable
[LttngTrace
],
1242 for trace
in traces
:
1243 if name
not in trace
.path
:
1244 fmt
= "Tracing session name must be part of every trace path (`{}` not found in `{}`)"
1245 raise ValueError(fmt
.format(name
, trace
.path
))
1247 self
._traces
= traces
1248 stream_count
= sum([len(t
) + 1 for t
in traces
])
1249 self
._info
= _LttngLiveViewerTracingSessionInfo(
1267 # The state of a tracing session.
1268 class _LttngLiveViewerSessionTracingSessionState
:
1269 def __init__(self
, tc_descr
: LttngTracingSessionDescriptor
, base_stream_id
: int):
1270 self
._tc
_descr
= tc_descr
1271 self
._stream
_infos
= [] # type: list[_LttngLiveViewerStreamInfo]
1272 self
._ds
_states
= {} # type: dict[int, _LttngLiveViewerSessionDataStreamState]
1275 ) # type: dict[int, _LttngLiveViewerSessionMetadataStreamState]
1276 stream_id
= base_stream_id
1278 for trace
in tc_descr
.traces
:
1279 trace_id
= stream_id
* 1000
1281 # Metadata stream -> stream info and metadata stream state
1282 info
= _LttngLiveViewerStreamInfo(
1283 stream_id
, trace_id
, True, trace
.metadata_stream
.path
, "metadata"
1285 self
._stream
_infos
.append(info
)
1286 self
._ms
_states
[stream_id
] = _LttngLiveViewerSessionMetadataStreamState(
1287 self
, info
, trace
.metadata_stream
1289 metadata_stream_id
= stream_id
1292 # Data streams -> stream infos and data stream states
1293 for data_stream
in trace
:
1294 info
= _LttngLiveViewerStreamInfo(
1299 data_stream
.channel_name
,
1301 self
._stream
_infos
.append(info
)
1302 self
._ds
_states
[stream_id
] = _LttngLiveViewerSessionDataStreamState(
1303 self
, info
, data_stream
, metadata_stream_id
1307 self
._is
_attached
= False
1308 fmt
= 'Built tracing session state: id={}, name="{}"'
1309 logging
.info(fmt
.format(tc_descr
.info
.tracing_session_id
, tc_descr
.info
.name
))
1312 def tracing_session_descriptor(self
):
1313 return self
._tc
_descr
1316 def data_stream_states(self
):
1317 return self
._ds
_states
1320 def metadata_stream_states(self
):
1321 return self
._ms
_states
1324 def stream_infos(self
):
1325 return self
._stream
_infos
1328 def has_new_metadata(self
):
1329 return any([not ms
.is_sent
for ms
in self
._ms
_states
.values()])
1332 def is_attached(self
):
1333 return self
._is
_attached
1336 def is_attached(self
, value
: bool):
1337 self
._is
_attached
= value
1340 def needs_new_metadata_section(
1341 metadata_stream_state
: _LttngLiveViewerSessionMetadataStreamState
,
1342 latest_timestamp
: int,
1344 if metadata_stream_state
.next_section_timestamp
is None:
1347 if latest_timestamp
>= metadata_stream_state
.next_section_timestamp
:
1353 # An LTTng live viewer session manages a view on tracing sessions
1354 # and replies to commands accordingly.
1355 class _LttngLiveViewerSession
:
1358 viewer_session_id
: int,
1359 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1360 max_query_data_response_size
: Optional
[int],
1362 self
._viewer
_session
_id
= viewer_session_id
1365 ) # type: dict[int, _LttngLiveViewerSessionTracingSessionState]
1366 self
._stream
_states
= (
1368 ) # type: dict[int, _LttngLiveViewerSessionDataStreamState | _LttngLiveViewerSessionMetadataStreamState]
1369 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1370 total_stream_infos
= 0
1372 for ts_descr
in tracing_session_descriptors
:
1373 ts_state
= _LttngLiveViewerSessionTracingSessionState(
1374 ts_descr
, total_stream_infos
1376 ts_id
= ts_state
.tracing_session_descriptor
.info
.tracing_session_id
1377 self
._ts
_states
[ts_id
] = ts_state
1378 total_stream_infos
+= len(ts_state
.stream_infos
)
1380 # Update session's stream states to have the new states
1381 self
._stream
_states
.update(ts_state
.data_stream_states
)
1382 self
._stream
_states
.update(ts_state
.metadata_stream_states
)
1384 self
._command
_handlers
= {
1385 _LttngLiveViewerAttachToTracingSessionCommand
: self
._handle
_attach
_to
_tracing
_session
_command
,
1386 _LttngLiveViewerCreateViewerSessionCommand
: self
._handle
_create
_viewer
_session
_command
,
1387 _LttngLiveViewerDetachFromTracingSessionCommand
: self
._handle
_detach
_from
_tracing
_session
_command
,
1388 _LttngLiveViewerGetDataStreamPacketDataCommand
: self
._handle
_get
_data
_stream
_packet
_data
_command
,
1389 _LttngLiveViewerGetMetadataStreamDataCommand
: self
._handle
_get
_metadata
_stream
_data
_command
,
1390 _LttngLiveViewerGetNewStreamInfosCommand
: self
._handle
_get
_new
_stream
_infos
_command
,
1391 _LttngLiveViewerGetNextDataStreamIndexEntryCommand
: self
._handle
_get
_next
_data
_stream
_index
_entry
_command
,
1392 _LttngLiveViewerGetTracingSessionInfosCommand
: self
._handle
_get
_tracing
_session
_infos
_command
,
1393 } # type: dict[type[_LttngLiveViewerCommand], Callable[[Any], _LttngLiveViewerReply]]
1396 def viewer_session_id(self
):
1397 return self
._viewer
_session
_id
1399 def _get_tracing_session_state(self
, tracing_session_id
: int):
1400 if tracing_session_id
not in self
._ts
_states
:
1401 raise UnexpectedInput(
1402 "Unknown tracing session ID {}".format(tracing_session_id
)
1405 return self
._ts
_states
[tracing_session_id
]
1407 def _get_data_stream_state(self
, stream_id
: int):
1408 if stream_id
not in self
._stream
_states
:
1409 RuntimeError("Unknown stream ID {}".format(stream_id
))
1411 stream
= self
._stream
_states
[stream_id
]
1412 if type(stream
) is not _LttngLiveViewerSessionDataStreamState
:
1413 raise RuntimeError("Stream is not a data stream")
1417 def _get_metadata_stream_state(self
, stream_id
: int):
1418 if stream_id
not in self
._stream
_states
:
1419 RuntimeError("Unknown stream ID {}".format(stream_id
))
1421 stream
= self
._stream
_states
[stream_id
]
1422 if type(stream
) is not _LttngLiveViewerSessionMetadataStreamState
:
1423 raise RuntimeError("Stream is not a metadata stream")
1427 def handle_command(self
, cmd
: _LttngLiveViewerCommand
):
1429 "Handling command in viewer session: cmd-cls-name={}".format(
1430 cmd
.__class
__.__name
__
1433 cmd_type
= type(cmd
)
1435 if cmd_type
not in self
._command
_handlers
:
1436 raise UnexpectedInput(
1437 "Unexpected command: cmd-cls-name={}".format(cmd
.__class
__.__name
__)
1440 return self
._command
_handlers
[cmd_type
](cmd
)
1442 def _handle_attach_to_tracing_session_command(
1443 self
, cmd
: _LttngLiveViewerAttachToTracingSessionCommand
1445 fmt
= 'Handling "attach to tracing session" command: ts-id={}, offset={}, seek-type={}'
1446 logging
.info(fmt
.format(cmd
.tracing_session_id
, cmd
.offset
, cmd
.seek_type
))
1447 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1448 info
= ts_state
.tracing_session_descriptor
.info
1450 if ts_state
.is_attached
:
1451 raise UnexpectedInput(
1452 "Cannot attach to tracing session `{}`: viewer is already attached".format(
1457 ts_state
.is_attached
= True
1458 status
= _LttngLiveViewerAttachToTracingSessionReply
.Status
.OK
1459 return _LttngLiveViewerAttachToTracingSessionReply(
1460 status
, ts_state
.stream_infos
1463 def _handle_detach_from_tracing_session_command(
1464 self
, cmd
: _LttngLiveViewerDetachFromTracingSessionCommand
1466 fmt
= 'Handling "detach from tracing session" command: ts-id={}'
1467 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1468 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1469 info
= ts_state
.tracing_session_descriptor
.info
1471 if not ts_state
.is_attached
:
1472 raise UnexpectedInput(
1473 "Cannot detach to tracing session `{}`: viewer is not attached".format(
1478 ts_state
.is_attached
= False
1479 status
= _LttngLiveViewerDetachFromTracingSessionReply
.Status
.OK
1480 return _LttngLiveViewerDetachFromTracingSessionReply(status
)
1482 def _handle_get_next_data_stream_index_entry_command(
1483 self
, cmd
: _LttngLiveViewerGetNextDataStreamIndexEntryCommand
1485 fmt
= 'Handling "get next data stream index entry" command: stream-id={}'
1486 logging
.info(fmt
.format(cmd
.stream_id
))
1487 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1488 metadata_stream_state
= self
._get
_metadata
_stream
_state
(
1489 stream_state
.metadata_stream_id
1492 if stream_state
.cur_index_entry
is None:
1493 # The viewer is done reading this stream
1494 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.HUP
1496 # Dummy data stream index entry to use with the `HUP` status
1497 # (the reply needs one, but the viewer ignores it)
1498 index_entry
= _LttngDataStreamIndexEntry(0, 0, 0, 0, 0, 0, 0)
1500 return _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1501 status
, index_entry
, False, False
1504 timestamp_begin
= _get_entry_timestamp_begin(stream_state
.cur_index_entry
)
1506 if needs_new_metadata_section(metadata_stream_state
, timestamp_begin
):
1507 metadata_stream_state
.is_sent
= False
1508 metadata_stream_state
.goto_next_section()
1510 # The viewer only checks the `has_new_metadata` flag if the
1511 # reply's status is `OK`, so we need to provide an index here
1512 has_new_metadata
= stream_state
.tracing_session_state
.has_new_metadata
1513 if isinstance(stream_state
.cur_index_entry
, _LttngDataStreamIndexEntry
):
1514 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.OK
1516 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.INACTIVE
1518 reply
= _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1519 status
, stream_state
.cur_index_entry
, has_new_metadata
, False
1521 stream_state
.goto_next_index_entry()
1524 def _handle_get_data_stream_packet_data_command(
1525 self
, cmd
: _LttngLiveViewerGetDataStreamPacketDataCommand
1527 fmt
= 'Handling "get data stream packet data" command: stream-id={}, offset={}, req-length={}'
1528 logging
.info(fmt
.format(cmd
.stream_id
, cmd
.offset
, cmd
.req_length
))
1529 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1530 data_response_length
= cmd
.req_length
1532 if stream_state
.tracing_session_state
.has_new_metadata
:
1533 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.ERROR
1534 return _LttngLiveViewerGetDataStreamPacketDataReply(
1535 status
, bytes(), True, False
1538 if self
._max
_query
_data
_response
_size
:
1539 # Enforce a server side limit on the query requested length.
1540 # To ensure that the transaction terminate take the minimum of both
1542 data_response_length
= min(
1543 cmd
.req_length
, self
._max
_query
_data
_response
_size
1545 fmt
= 'Limiting "get data stream packet data" command: req-length={} actual response size={}'
1546 logging
.info(fmt
.format(cmd
.req_length
, data_response_length
))
1548 data
= stream_state
.data_stream
.get_data(cmd
.offset
, data_response_length
)
1549 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.OK
1550 return _LttngLiveViewerGetDataStreamPacketDataReply(status
, data
, False, False)
1552 def _handle_get_metadata_stream_data_command(
1553 self
, cmd
: _LttngLiveViewerGetMetadataStreamDataCommand
1555 fmt
= 'Handling "get metadata stream data" command: stream-id={}'
1556 logging
.info(fmt
.format(cmd
.stream_id
))
1557 metadata_stream_state
= self
._get
_metadata
_stream
_state
(cmd
.stream_id
)
1559 if metadata_stream_state
.is_sent
:
1560 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.NO_NEW
1561 return _LttngLiveViewerGetMetadataStreamDataContentReply(status
, bytes())
1563 metadata_stream_state
.is_sent
= True
1564 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.OK
1565 metadata_section
= metadata_stream_state
.cur_section
1566 assert metadata_section
is not None
1568 # If we are sending an empty section, ready the next one right away.
1569 if len(metadata_section
.data
) == 0:
1570 metadata_stream_state
.is_sent
= False
1571 metadata_stream_state
.goto_next_section()
1573 fmt
= 'Replying to "get metadata stream data" command: metadata-size={}'
1574 logging
.info(fmt
.format(len(metadata_section
.data
)))
1575 return _LttngLiveViewerGetMetadataStreamDataContentReply(
1576 status
, metadata_section
.data
1579 def _handle_get_new_stream_infos_command(
1580 self
, cmd
: _LttngLiveViewerGetNewStreamInfosCommand
1582 fmt
= 'Handling "get new stream infos" command: ts-id={}'
1583 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1585 # As of this version, all the tracing session's stream infos are
1586 # always given to the viewer when sending the "attach to tracing
1587 # session" reply, so there's nothing new here. Return the `HUP`
1588 # status as, if we're handling this command, the viewer consumed
1589 # all the existing data streams.
1590 status
= _LttngLiveViewerGetNewStreamInfosReply
.Status
.HUP
1591 return _LttngLiveViewerGetNewStreamInfosReply(status
, [])
1593 def _handle_get_tracing_session_infos_command(
1594 self
, cmd
: _LttngLiveViewerGetTracingSessionInfosCommand
1596 logging
.info('Handling "get tracing session infos" command.')
1598 tss
.tracing_session_descriptor
.info
for tss
in self
._ts
_states
.values()
1600 infos
.sort(key
=lambda info
: info
.name
)
1601 return _LttngLiveViewerGetTracingSessionInfosReply(infos
)
1603 def _handle_create_viewer_session_command(
1604 self
, cmd
: _LttngLiveViewerCreateViewerSessionCommand
1606 logging
.info('Handling "create viewer session" command.')
1607 status
= _LttngLiveViewerCreateViewerSessionReply
.Status
.OK
1609 # This does nothing here. In the LTTng relay daemon, it
1610 # allocates the viewer session's state.
1611 return _LttngLiveViewerCreateViewerSessionReply(status
)
1614 # An LTTng live TCP server.
1616 # On creation, it binds to `localhost` on the TCP port `port` if not `None`, or
1617 # on an OS-assigned TCP port otherwise. It writes the decimal TCP port number
1618 # to a temporary port file. It renames the temporary port file to
1621 # `tracing_session_descriptors` is a list of tracing session descriptors
1622 # (`LttngTracingSessionDescriptor`) to serve.
1624 # This server accepts a single viewer (client).
1626 # When the viewer closes the connection, the server's constructor
1628 class LttngLiveServer
:
1631 port
: Optional
[int],
1633 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1634 max_query_data_response_size
: Optional
[int],
1636 logging
.info("Server configuration:")
1638 logging
.info(" Port file name: `{}`".format(port_filename
))
1640 if max_query_data_response_size
is not None:
1642 " Maximum response data query size: `{}`".format(
1643 max_query_data_response_size
1647 for ts_descr
in tracing_session_descriptors
:
1648 info
= ts_descr
.info
1649 fmt
= ' TS descriptor: name="{}", id={}, hostname="{}", live-timer-freq={}, client-count={}, stream-count={}:'
1653 info
.tracing_session_id
,
1655 info
.live_timer_freq
,
1661 for trace
in ts_descr
.traces
:
1662 logging
.info(' Trace: path="{}"'.format(trace
.path
))
1664 self
._ts
_descriptors
= tracing_session_descriptors
1665 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1666 self
._sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
1667 self
._codec
= _LttngLiveViewerProtocolCodec()
1669 # Port 0: OS assigns an unused port
1670 serv_addr
= ("localhost", port
if port
is not None else 0)
1671 self
._sock
.bind(serv_addr
)
1672 self
._write
_port
_to
_file
(port_filename
)
1678 logging
.info("Closed connection and socket.")
1681 def _server_port(self
):
1682 return self
._sock
.getsockname()[1]
1684 def _recv_command(self
):
1688 logging
.info("Waiting for viewer command.")
1689 buf
= self
._conn
.recv(128)
1692 logging
.info("Client closed connection.")
1695 raise UnexpectedInput(
1696 "Client closed connection after having sent {} command bytes.".format(
1703 logging
.info("Received data from viewer: length={}".format(len(buf
)))
1708 cmd
= self
._codec
.decode(data
)
1709 except struct
.error
as exc
:
1710 raise UnexpectedInput("Malformed command: {}".format(exc
)) from exc
1714 "Received command from viewer: cmd-cls-name={}".format(
1715 cmd
.__class
__.__name
__
1720 def _send_reply(self
, reply
: _LttngLiveViewerReply
):
1721 data
= self
._codec
.encode(reply
)
1723 "Sending reply to viewer: reply-cls-name={}, length={}".format(
1724 reply
.__class
__.__name
__, len(data
)
1727 self
._conn
.sendall(data
)
1729 def _handle_connection(self
):
1730 # First command must be "connect"
1731 cmd
= self
._recv
_command
()
1733 if type(cmd
) is not _LttngLiveViewerConnectCommand
:
1734 raise UnexpectedInput(
1735 'First command is not "connect": cmd-cls-name={}'.format(
1736 cmd
.__class
__.__name
__
1740 # Create viewer session (arbitrary ID 23)
1742 "LTTng live viewer connected: version={}.{}".format(cmd
.major
, cmd
.minor
)
1744 viewer_session
= _LttngLiveViewerSession(
1745 23, self
._ts
_descriptors
, self
._max
_query
_data
_response
_size
1748 # Send "connect" reply
1750 _LttngLiveViewerConnectReply(viewer_session
.viewer_session_id
, 2, 10)
1753 # Make the viewer session handle the remaining commands
1755 cmd
= self
._recv
_command
()
1758 # Connection closed (at an expected location within the
1762 self
._send
_reply
(viewer_session
.handle_command(cmd
))
1765 logging
.info("Listening: port={}".format(self
._server
_port
))
1766 # Backlog must be present for Python version < 3.5.
1767 # 128 is an arbitrary number since we expect only 1 connection anyway.
1768 self
._sock
.listen(128)
1769 self
._conn
, viewer_addr
= self
._sock
.accept()
1771 "Accepted viewer: addr={}:{}".format(viewer_addr
[0], viewer_addr
[1])
1775 self
._handle
_connection
()
1779 def _write_port_to_file(self
, port_filename
: str):
1780 # Write the port number to a temporary file.
1781 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as tmp_port_file
:
1782 print(self
._server
_port
, end
="", file=tmp_port_file
)
1784 # Rename temporary file to real file
1785 os
.replace(tmp_port_file
.name
, port_filename
)
1787 'Renamed port file: src-path="{}", dst-path="{}"'.format(
1788 tmp_port_file
.name
, port_filename
1793 def _session_descriptors_from_path(
1794 sessions_filename
: str, trace_path_prefix
: Optional
[str]
1800 # "name": "my-session",
1802 # "hostname": "myhost",
1803 # "live-timer-freq": 1000000,
1804 # "client-count": 23,
1810 # "path": "meow/mix",
1812 # "my_stream": [ 5235787, 728375283 ]
1814 # "metadata-sections": [
1824 with
open(sessions_filename
, "r") as sessions_file
:
1825 sessions_json
= tjson
.load(sessions_file
, tjson
.ArrayVal
)
1827 sessions
= [] # type: list[LttngTracingSessionDescriptor]
1829 for session_json
in sessions_json
.iter(tjson
.ObjVal
):
1830 name
= session_json
.at("name", tjson
.StrVal
).val
1831 tracing_session_id
= session_json
.at("id", tjson
.IntVal
).val
1832 hostname
= session_json
.at("hostname", tjson
.StrVal
).val
1833 live_timer_freq
= session_json
.at("live-timer-freq", tjson
.IntVal
).val
1834 client_count
= session_json
.at("client-count", tjson
.IntVal
).val
1835 traces_json
= session_json
.at("traces", tjson
.ArrayVal
)
1837 traces
= [] # type: list[LttngTrace]
1839 for trace_json
in traces_json
.iter(tjson
.ObjVal
):
1840 metadata_sections
= (
1841 trace_json
.at("metadata-sections", tjson
.ArrayVal
)
1842 if "metadata-sections" in trace_json
1846 trace_json
.at("beacons", tjson
.ObjVal
)
1847 if "beacons" in trace_json
1850 path
= trace_json
.at("path", tjson
.StrVal
).val
1852 if not os
.path
.isabs(path
) and trace_path_prefix
:
1853 path
= os
.path
.join(trace_path_prefix
, path
)
1864 LttngTracingSessionDescriptor(
1877 def _loglevel_parser(string
: str):
1878 loglevels
= {"info": logging
.INFO
, "warning": logging
.WARNING
}
1879 if string
not in loglevels
:
1880 msg
= "{} is not a valid loglevel".format(string
)
1881 raise argparse
.ArgumentTypeError(msg
)
1882 return loglevels
[string
]
1885 if __name__
== "__main__":
1886 logging
.basicConfig(format
="# %(asctime)-25s%(message)s")
1887 parser
= argparse
.ArgumentParser(
1888 description
="LTTng-live protocol mocker", add_help
=False
1890 parser
.add_argument(
1893 choices
=["info", "warning"],
1894 help="The loglevel to be used.",
1897 loglevel_namespace
, remaining_args
= parser
.parse_known_args()
1898 logging
.getLogger().setLevel(_loglevel_parser(loglevel_namespace
.log_level
))
1900 parser
.add_argument(
1902 help="The port to bind to. If missing, use an OS-assigned port..",
1905 parser
.add_argument(
1907 help="The final port file. This file is present when the server is ready to receive connection.",
1910 parser
.add_argument(
1911 "--max-query-data-response-size",
1913 help="The maximum size of control data response in bytes",
1915 parser
.add_argument(
1916 "--trace-path-prefix",
1918 help="Prefix to prepend to the trace paths of session configurations",
1920 parser
.add_argument(
1921 "--sessions-filename",
1923 help="Path to a session configuration file",
1925 parser
.add_argument(
1929 default
=argparse
.SUPPRESS
,
1930 help="Show this help message and exit.",
1933 args
= parser
.parse_args(args
=remaining_args
)
1935 sessions_filename
= args
.sessions_filename
# type: str
1936 trace_path_prefix
= args
.trace_path_prefix
# type: str | None
1937 sessions
= _session_descriptors_from_path(
1942 port
= args
.port
# type: int | None
1943 port_filename
= args
.port_filename
# type: str
1944 max_query_data_response_size
= (
1945 args
.max_query_data_response_size
1946 ) # type: int | None
1947 LttngLiveServer(port
, port_filename
, sessions
, max_query_data_response_size
)
1948 except UnexpectedInput
as exc
:
1949 logging
.error(str(exc
))
1950 print(exc
, file=sys
.stderr
)