1 # SPDX-License-Identifier: MIT
3 # Copyright (C) 2019 Philippe Proulx <pproulx@efficios.com>
6 # pyright: strict, reportTypeCommentUsage=false, reportMissingTypeStubs=false
16 from typing
import Dict
, Union
, Iterable
, Optional
, Sequence
, overload
21 from typing
import Any
, Callable
# noqa: F401
26 # An entry within the index of an LTTng data stream.
27 class _LttngDataStreamIndexEntry
:
32 content_size_bits
: int,
35 events_discarded
: int,
38 self
._offset
_bytes
= offset_bytes
39 self
._total
_size
_bits
= total_size_bits
40 self
._content
_size
_bits
= content_size_bits
41 self
._timestamp
_begin
= timestamp_begin
42 self
._timestamp
_end
= timestamp_end
43 self
._events
_discarded
= events_discarded
44 self
._stream
_class
_id
= stream_class_id
47 def offset_bytes(self
):
48 return self
._offset
_bytes
51 def total_size_bits(self
):
52 return self
._total
_size
_bits
55 def total_size_bytes(self
):
56 return self
._total
_size
_bits
// 8
59 def content_size_bits(self
):
60 return self
._content
_size
_bits
63 def content_size_bytes(self
):
64 return self
._content
_size
_bits
// 8
67 def timestamp_begin(self
):
68 return self
._timestamp
_begin
71 def timestamp_end(self
):
72 return self
._timestamp
_end
75 def events_discarded(self
):
76 return self
._events
_discarded
79 def stream_class_id(self
):
80 return self
._stream
_class
_id
83 # An entry within the index of an LTTng data stream. While a stream beacon entry
84 # is conceptually unrelated to an index, it is sent as a reply to a
85 # LttngLiveViewerGetNextDataStreamIndexEntryCommand
86 class _LttngDataStreamBeaconIndexEntry
:
87 def __init__(self
, stream_class_id
: int, timestamp
: int):
88 self
._stream
_class
_id
= stream_class_id
89 self
._timestamp
= timestamp
93 return self
._timestamp
96 def stream_class_id(self
):
97 return self
._stream
_class
_id
100 _LttngIndexEntryT
= Union
[_LttngDataStreamIndexEntry
, _LttngDataStreamBeaconIndexEntry
]
103 class _LttngLiveViewerCommand
:
104 def __init__(self
, version
: int):
105 self
._version
= version
112 class _LttngLiveViewerConnectCommand(_LttngLiveViewerCommand
):
113 def __init__(self
, version
: int, viewer_session_id
: int, major
: int, minor
: int):
114 super().__init
__(version
)
115 self
._viewer
_session
_id
= viewer_session_id
120 def viewer_session_id(self
):
121 return self
._viewer
_session
_id
132 class _LttngLiveViewerReply
:
136 class _LttngLiveViewerConnectReply(_LttngLiveViewerReply
):
137 def __init__(self
, viewer_session_id
: int, major
: int, minor
: int):
138 self
._viewer
_session
_id
= viewer_session_id
143 def viewer_session_id(self
):
144 return self
._viewer
_session
_id
155 class _LttngLiveViewerGetTracingSessionInfosCommand(_LttngLiveViewerCommand
):
159 class _LttngLiveViewerTracingSessionInfo
:
162 tracing_session_id
: int,
163 live_timer_freq
: int,
169 self
._tracing
_session
_id
= tracing_session_id
170 self
._live
_timer
_freq
= live_timer_freq
171 self
._client
_count
= client_count
172 self
._stream
_count
= stream_count
173 self
._hostname
= hostname
177 def tracing_session_id(self
):
178 return self
._tracing
_session
_id
181 def live_timer_freq(self
):
182 return self
._live
_timer
_freq
185 def client_count(self
):
186 return self
._client
_count
189 def stream_count(self
):
190 return self
._stream
_count
194 return self
._hostname
201 class _LttngLiveViewerGetTracingSessionInfosReply(_LttngLiveViewerReply
):
203 self
, tracing_session_infos
: Sequence
[_LttngLiveViewerTracingSessionInfo
]
205 self
._tracing
_session
_infos
= tracing_session_infos
208 def tracing_session_infos(self
):
209 return self
._tracing
_session
_infos
212 class _LttngLiveViewerAttachToTracingSessionCommand(_LttngLiveViewerCommand
):
218 self
, version
: int, tracing_session_id
: int, offset
: int, seek_type
: int
220 super().__init
__(version
)
221 self
._tracing
_session
_id
= tracing_session_id
222 self
._offset
= offset
223 self
._seek
_type
= seek_type
226 def tracing_session_id(self
):
227 return self
._tracing
_session
_id
235 return self
._seek
_type
238 class _LttngLiveViewerStreamInfo
:
240 self
, id: int, trace_id
: int, is_metadata
: bool, path
: str, channel_name
: str
243 self
._trace
_id
= trace_id
244 self
._is
_metadata
= is_metadata
246 self
._channel
_name
= channel_name
254 return self
._trace
_id
257 def is_metadata(self
):
258 return self
._is
_metadata
265 def channel_name(self
):
266 return self
._channel
_name
269 class _LttngLiveViewerAttachToTracingSessionReply(_LttngLiveViewerReply
):
278 def __init__(self
, status
: int, stream_infos
: Sequence
[_LttngLiveViewerStreamInfo
]):
279 self
._status
= status
280 self
._stream
_infos
= stream_infos
287 def stream_infos(self
):
288 return self
._stream
_infos
291 class _LttngLiveViewerGetNextDataStreamIndexEntryCommand(_LttngLiveViewerCommand
):
292 def __init__(self
, version
: int, stream_id
: int):
293 super().__init
__(version
)
294 self
._stream
_id
= stream_id
298 return self
._stream
_id
301 class _LttngLiveViewerGetNextDataStreamIndexEntryReply(_LttngLiveViewerReply
):
313 index_entry
: _LttngIndexEntryT
,
314 has_new_metadata
: bool,
315 has_new_data_stream
: bool,
317 self
._status
= status
318 self
._index
_entry
= index_entry
319 self
._has
_new
_metadata
= has_new_metadata
320 self
._has
_new
_data
_stream
= has_new_data_stream
327 def index_entry(self
):
328 return self
._index
_entry
331 def has_new_metadata(self
):
332 return self
._has
_new
_metadata
335 def has_new_data_stream(self
):
336 return self
._has
_new
_data
_stream
339 class _LttngLiveViewerGetDataStreamPacketDataCommand(_LttngLiveViewerCommand
):
340 def __init__(self
, version
: int, stream_id
: int, offset
: int, req_length
: int):
341 super().__init
__(version
)
342 self
._stream
_id
= stream_id
343 self
._offset
= offset
344 self
._req
_length
= req_length
348 return self
._stream
_id
355 def req_length(self
):
356 return self
._req
_length
359 class _LttngLiveViewerGetDataStreamPacketDataReply(_LttngLiveViewerReply
):
370 has_new_metadata
: bool,
371 has_new_data_stream
: bool,
373 self
._status
= status
375 self
._has
_new
_metadata
= has_new_metadata
376 self
._has
_new
_data
_stream
= has_new_data_stream
387 def has_new_metadata(self
):
388 return self
._has
_new
_metadata
391 def has_new_data_stream(self
):
392 return self
._has
_new
_data
_stream
395 class _LttngLiveViewerGetMetadataStreamDataCommand(_LttngLiveViewerCommand
):
396 def __init__(self
, version
: int, stream_id
: int):
397 super().__init
__(version
)
398 self
._stream
_id
= stream_id
402 return self
._stream
_id
405 class _LttngLiveViewerGetMetadataStreamDataContentReply(_LttngLiveViewerReply
):
411 def __init__(self
, status
: int, data
: bytes
):
412 self
._status
= status
424 class _LttngLiveViewerGetNewStreamInfosCommand(_LttngLiveViewerCommand
):
425 def __init__(self
, version
: int, tracing_session_id
: int):
426 super().__init
__(version
)
427 self
._tracing
_session
_id
= tracing_session_id
430 def tracing_session_id(self
):
431 return self
._tracing
_session
_id
434 class _LttngLiveViewerGetNewStreamInfosReply(_LttngLiveViewerReply
):
441 def __init__(self
, status
: int, stream_infos
: Sequence
[_LttngLiveViewerStreamInfo
]):
442 self
._status
= status
443 self
._stream
_infos
= stream_infos
450 def stream_infos(self
):
451 return self
._stream
_infos
454 class _LttngLiveViewerCreateViewerSessionCommand(_LttngLiveViewerCommand
):
458 class _LttngLiveViewerCreateViewerSessionReply(_LttngLiveViewerReply
):
463 def __init__(self
, status
: int):
464 self
._status
= status
471 class _LttngLiveViewerDetachFromTracingSessionCommand(_LttngLiveViewerCommand
):
472 def __init__(self
, version
: int, tracing_session_id
: int):
473 super().__init
__(version
)
474 self
._tracing
_session
_id
= tracing_session_id
477 def tracing_session_id(self
):
478 return self
._tracing
_session
_id
481 class _LttngLiveViewerDetachFromTracingSessionReply(_LttngLiveViewerReply
):
487 def __init__(self
, status
: int):
488 self
._status
= status
495 # An LTTng live protocol codec can convert bytes to command objects and
496 # reply objects to bytes.
497 class _LttngLiveViewerProtocolCodec
:
498 _COMMAND_HEADER_STRUCT_FMT
= "QII"
499 _COMMAND_HEADER_SIZE_BYTES
= struct
.calcsize(_COMMAND_HEADER_STRUCT_FMT
)
504 def _unpack(self
, fmt
: str, data
: bytes
, offset
: int = 0):
506 return struct
.unpack_from(fmt
, data
, offset
)
508 def _unpack_payload(self
, fmt
: str, data
: bytes
):
510 fmt
, data
, _LttngLiveViewerProtocolCodec
._COMMAND
_HEADER
_SIZE
_BYTES
513 def decode(self
, data
: bytes
):
514 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
:
515 # Not enough data to read the command header
518 payload_size
, cmd_type
, version
= self
._unpack
(
519 self
._COMMAND
_HEADER
_STRUCT
_FMT
, data
522 "Decoded command header: payload-size={}, cmd-type={}, version={}".format(
523 payload_size
, cmd_type
, version
527 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
+ payload_size
:
528 # Not enough data to read the whole command
532 viewer_session_id
, major
, minor
, _
= self
._unpack
_payload
("QIII", data
)
533 return _LttngLiveViewerConnectCommand(
534 version
, viewer_session_id
, major
, minor
537 return _LttngLiveViewerGetTracingSessionInfosCommand(version
)
539 tracing_session_id
, offset
, seek_type
= self
._unpack
_payload
("QQI", data
)
540 return _LttngLiveViewerAttachToTracingSessionCommand(
541 version
, tracing_session_id
, offset
, seek_type
544 (stream_id
,) = self
._unpack
_payload
("Q", data
)
545 return _LttngLiveViewerGetNextDataStreamIndexEntryCommand(
549 stream_id
, offset
, req_length
= self
._unpack
_payload
("QQI", data
)
550 return _LttngLiveViewerGetDataStreamPacketDataCommand(
551 version
, stream_id
, offset
, req_length
554 (stream_id
,) = self
._unpack
_payload
("Q", data
)
555 return _LttngLiveViewerGetMetadataStreamDataCommand(version
, stream_id
)
557 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
558 return _LttngLiveViewerGetNewStreamInfosCommand(version
, tracing_session_id
)
560 return _LttngLiveViewerCreateViewerSessionCommand(version
)
562 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
563 return _LttngLiveViewerDetachFromTracingSessionCommand(
564 version
, tracing_session_id
567 raise RuntimeError("Unknown command type {}".format(cmd_type
))
569 def _pack(self
, fmt
: str, *args
: Any
):
570 # Force network byte order
571 return struct
.pack("!" + fmt
, *args
)
573 def _encode_zero_padded_str(self
, string
: str, length
: int):
574 data
= string
.encode()
575 return data
.ljust(length
, b
"\x00")
577 def _encode_stream_info(self
, info
: _LttngLiveViewerStreamInfo
):
578 data
= self
._pack
("QQI", info
.id, info
.trace_id
, int(info
.is_metadata
))
579 data
+= self
._encode
_zero
_padded
_str
(info
.path
, 4096)
580 data
+= self
._encode
_zero
_padded
_str
(info
.channel_name
, 255)
583 def _get_has_new_stuff_flags(
584 self
, has_new_metadata
: bool, has_new_data_streams
: bool
591 if has_new_data_streams
:
598 reply
: _LttngLiveViewerReply
,
600 if type(reply
) is _LttngLiveViewerConnectReply
:
602 "QIII", reply
.viewer_session_id
, reply
.major
, reply
.minor
, 2
604 elif type(reply
) is _LttngLiveViewerGetTracingSessionInfosReply
:
605 data
= self
._pack
("I", len(reply
.tracing_session_infos
))
607 for info
in reply
.tracing_session_infos
:
610 info
.tracing_session_id
,
611 info
.live_timer_freq
,
615 data
+= self
._encode
_zero
_padded
_str
(info
.hostname
, 64)
616 data
+= self
._encode
_zero
_padded
_str
(info
.name
, 255)
617 elif type(reply
) is _LttngLiveViewerAttachToTracingSessionReply
:
618 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
620 for info
in reply
.stream_infos
:
621 data
+= self
._encode
_stream
_info
(info
)
622 elif type(reply
) is _LttngLiveViewerGetNextDataStreamIndexEntryReply
:
623 index_format
= "QQQQQQQII"
624 entry
= reply
.index_entry
625 flags
= self
._get
_has
_new
_stuff
_flags
(
626 reply
.has_new_metadata
, reply
.has_new_data_stream
629 if isinstance(entry
, _LttngDataStreamIndexEntry
):
633 entry
.total_size_bits
,
634 entry
.content_size_bits
,
635 entry
.timestamp_begin
,
637 entry
.events_discarded
,
638 entry
.stream_class_id
,
651 entry
.stream_class_id
,
655 elif type(reply
) is _LttngLiveViewerGetDataStreamPacketDataReply
:
656 flags
= self
._get
_has
_new
_stuff
_flags
(
657 reply
.has_new_metadata
, reply
.has_new_data_stream
659 data
= self
._pack
("III", reply
.status
, len(reply
.data
), flags
)
661 elif type(reply
) is _LttngLiveViewerGetMetadataStreamDataContentReply
:
662 data
= self
._pack
("QI", len(reply
.data
), reply
.status
)
664 elif type(reply
) is _LttngLiveViewerGetNewStreamInfosReply
:
665 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
667 for info
in reply
.stream_infos
:
668 data
+= self
._encode
_stream
_info
(info
)
669 elif type(reply
) is _LttngLiveViewerCreateViewerSessionReply
:
670 data
= self
._pack
("I", reply
.status
)
671 elif type(reply
) is _LttngLiveViewerDetachFromTracingSessionReply
:
672 data
= self
._pack
("I", reply
.status
)
675 "Unknown reply object with class `{}`".format(reply
.__class
__.__name
__)
681 def _get_entry_timestamp_begin(
682 entry
: _LttngIndexEntryT
,
684 if isinstance(entry
, _LttngDataStreamBeaconIndexEntry
):
685 return entry
.timestamp
687 return entry
.timestamp_begin
690 # The index of an LTTng data stream, a sequence of index entries.
691 class _LttngDataStreamIndex(Sequence
[_LttngIndexEntryT
]):
692 def __init__(self
, path
: str, beacons
: Optional
[tjson
.ArrayVal
]):
697 stream_class_id
= self
._entries
[0].stream_class_id
699 beacons_list
= [] # type: list[_LttngDataStreamBeaconIndexEntry]
700 for ts
in beacons
.iter(tjson
.IntVal
):
702 _LttngDataStreamBeaconIndexEntry(stream_class_id
, ts
.val
)
705 self
._add
_beacons
(beacons_list
)
708 'Built data stream index entries: path="{}", count={}'.format(
709 path
, len(self
._entries
)
714 self
._entries
= [] # type: list[_LttngIndexEntryT]
716 with
open(self
._path
, "rb") as f
:
719 size
= struct
.calcsize(fmt
)
721 assert len(data
) == size
722 magic
, _
, _
, index_entry_length
= struct
.unpack(fmt
, data
)
723 assert magic
== 0xC1F1DCC1
727 size
= struct
.calcsize(fmt
)
731 'Decoding data stream index entry: path="{}", offset={}'.format(
741 assert len(data
) == size
750 ) = struct
.unpack(fmt
, data
)
752 self
._entries
.append(
753 _LttngDataStreamIndexEntry(
764 # Skip anything else before the next entry
765 f
.seek(index_entry_length
- size
, os
.SEEK_CUR
)
767 def _add_beacons(self
, beacons
: Iterable
[_LttngDataStreamBeaconIndexEntry
]):
768 # Assumes entries[n + 1].timestamp_end >= entries[n].timestamp_begin
770 entry
: Union
[_LttngDataStreamIndexEntry
, _LttngDataStreamBeaconIndexEntry
],
772 if isinstance(entry
, _LttngDataStreamBeaconIndexEntry
):
773 return entry
.timestamp
775 return entry
.timestamp_end
777 self
._entries
+= beacons
778 self
._entries
.sort(key
=sort_key
)
781 def __getitem__(self
, index
: int) -> _LttngIndexEntryT
:
785 def __getitem__(self
, index
: slice) -> Sequence
[_LttngIndexEntryT
]: # noqa: F811
788 def __getitem__( # noqa: F811
789 self
, index
: Union
[int, slice]
790 ) -> Union
[_LttngIndexEntryT
, Sequence
[_LttngIndexEntryT
],]:
791 return self
._entries
[index
]
794 return len(self
._entries
)
801 # An LTTng data stream.
802 class _LttngDataStream
:
803 def __init__(self
, path
: str, beacons_json
: Optional
[tjson
.ArrayVal
]):
805 filename
= os
.path
.basename(path
)
806 match
= re
.match(r
"(.*)_\d+", filename
)
809 "Unexpected data stream file name pattern: {}".format(filename
)
812 self
._channel
_name
= match
.group(1)
813 trace_dir
= os
.path
.dirname(path
)
814 index_path
= os
.path
.join(trace_dir
, "index", filename
+ ".idx")
815 self
._index
= _LttngDataStreamIndex(index_path
, beacons_json
)
816 assert os
.path
.isfile(path
)
817 self
._file
= open(path
, "rb")
819 'Built data stream: path="{}", channel-name="{}"'.format(
820 path
, self
._channel
_name
829 def channel_name(self
):
830 return self
._channel
_name
836 def get_data(self
, offset_bytes
: int, len_bytes
: int):
837 self
._file
.seek(offset_bytes
)
838 return self
._file
.read(len_bytes
)
841 class _LttngMetadataStreamSection
:
842 def __init__(self
, timestamp
: int, data
: Optional
[bytes
]):
843 self
._timestamp
= timestamp
849 "Built metadata stream section: ts={}, data-len={}".format(
850 self
._timestamp
, len(self
._data
)
856 return self
._timestamp
863 # An LTTng metadata stream.
864 class _LttngMetadataStream
:
867 metadata_file_path
: str,
868 config_sections
: Sequence
[_LttngMetadataStreamSection
],
870 self
._path
= metadata_file_path
871 self
._sections
= config_sections
873 "Built metadata stream: path={}, section-len={}".format(
874 self
._path
, len(self
._sections
)
884 return self
._sections
887 class LttngMetadataConfigSection
:
888 def __init__(self
, line
: int, timestamp
: int, is_empty
: bool):
890 self
._timestamp
= timestamp
891 self
._is
_empty
= is_empty
899 return self
._timestamp
903 return self
._is
_empty
906 def _parse_metadata_sections_config(metadata_sections_json
: tjson
.ArrayVal
):
907 metadata_sections
= [] # type: list[LttngMetadataConfigSection]
908 append_empty_section
= False
912 for section
in metadata_sections_json
:
913 if isinstance(section
, tjson
.StrVal
):
914 if section
.val
== "empty":
915 # Found a empty section marker. Actually append the section at the
916 # timestamp of the next concrete section.
917 append_empty_section
= True
919 raise ValueError("Invalid string value at {}.".format(section
.path
))
920 elif isinstance(section
, tjson
.ObjVal
):
921 line
= section
.at("line", tjson
.IntVal
).val
922 ts
= section
.at("timestamp", tjson
.IntVal
).val
924 # Sections' timestamps and lines must both be increasing.
925 assert ts
> last_timestamp
928 assert line
> last_line
931 if append_empty_section
:
932 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, True))
933 append_empty_section
= False
935 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, False))
938 "`{}`: expecting a string or object value".format(section
.path
)
941 return metadata_sections
944 def _split_metadata_sections(
945 metadata_file_path
: str, metadata_sections_json
: tjson
.ArrayVal
947 metadata_sections
= _parse_metadata_sections_config(metadata_sections_json
)
949 sections
= [] # type: list[_LttngMetadataStreamSection]
950 with
open(metadata_file_path
, "r") as metadata_file
:
951 metadata_lines
= [line
for line
in metadata_file
]
953 metadata_section_idx
= 0
954 curr_metadata_section
= bytearray()
956 for idx
, line_content
in enumerate(metadata_lines
):
957 # Add one to the index to convert from the zero-indexing of the
958 # enumerate() function to the one-indexing used by humans when
959 # viewing a text file.
960 curr_line_number
= idx
+ 1
962 # If there are no more sections, simply append the line.
963 if metadata_section_idx
+ 1 >= len(metadata_sections
):
964 curr_metadata_section
+= bytearray(line_content
, "utf8")
967 next_section_line_number
= metadata_sections
[metadata_section_idx
+ 1].line
969 # If the next section begins at the current line, create a
970 # section with the metadata we gathered so far.
971 if curr_line_number
>= next_section_line_number
:
972 # Flushing the metadata of the current section.
974 _LttngMetadataStreamSection(
975 metadata_sections
[metadata_section_idx
].timestamp
,
976 bytes(curr_metadata_section
),
980 # Move to the next section.
981 metadata_section_idx
+= 1
983 # Clear old content and append current line for the next section.
984 curr_metadata_section
.clear()
985 curr_metadata_section
+= bytearray(line_content
, "utf8")
987 # Append any empty sections.
988 while metadata_sections
[metadata_section_idx
].is_empty
:
990 _LttngMetadataStreamSection(
991 metadata_sections
[metadata_section_idx
].timestamp
, None
994 metadata_section_idx
+= 1
996 # Append line_content to the current metadata section.
997 curr_metadata_section
+= bytearray(line_content
, "utf8")
999 # We iterated over all the lines of the metadata file. Close the current section.
1001 _LttngMetadataStreamSection(
1002 metadata_sections
[metadata_section_idx
].timestamp
,
1003 bytes(curr_metadata_section
),
1010 _StreamBeaconsT
= Dict
[str, Iterable
[int]]
1013 # An LTTng trace, a sequence of LTTng data streams.
1014 class LttngTrace(Sequence
[_LttngDataStream
]):
1018 metadata_sections_json
: Optional
[tjson
.ArrayVal
],
1019 beacons_json
: Optional
[tjson
.ObjVal
],
1021 self
._path
= trace_dir
1022 self
._create
_metadata
_stream
(trace_dir
, metadata_sections_json
)
1023 self
._create
_data
_streams
(trace_dir
, beacons_json
)
1024 logging
.info('Built trace: path="{}"'.format(trace_dir
))
1026 def _create_data_streams(
1027 self
, trace_dir
: str, beacons_json
: Optional
[tjson
.ObjVal
]
1029 data_stream_paths
= [] # type: list[str]
1031 for filename
in os
.listdir(trace_dir
):
1032 path
= os
.path
.join(trace_dir
, filename
)
1034 if not os
.path
.isfile(path
):
1037 if filename
.startswith("."):
1040 if filename
== "metadata":
1043 data_stream_paths
.append(path
)
1045 data_stream_paths
.sort()
1046 self
._data
_streams
= [] # type: list[_LttngDataStream]
1048 for data_stream_path
in data_stream_paths
:
1049 stream_name
= os
.path
.basename(data_stream_path
)
1050 this_beacons_json
= None
1051 if beacons_json
is not None and stream_name
in beacons_json
:
1052 this_beacons_json
= beacons_json
.at(stream_name
, tjson
.ArrayVal
)
1054 self
._data
_streams
.append(
1055 _LttngDataStream(data_stream_path
, this_beacons_json
)
1058 def _create_metadata_stream(
1059 self
, trace_dir
: str, metadata_sections_json
: Optional
[tjson
.ArrayVal
]
1061 metadata_path
= os
.path
.join(trace_dir
, "metadata")
1062 metadata_sections
= [] # type: list[_LttngMetadataStreamSection]
1064 if metadata_sections_json
is None:
1065 with
open(metadata_path
, "rb") as metadata_file
:
1066 metadata_sections
.append(
1067 _LttngMetadataStreamSection(0, metadata_file
.read())
1070 metadata_sections
= _split_metadata_sections(
1071 metadata_path
, metadata_sections_json
1074 self
._metadata
_stream
= _LttngMetadataStream(metadata_path
, metadata_sections
)
1081 def metadata_stream(self
):
1082 return self
._metadata
_stream
1085 def __getitem__(self
, index
: int) -> _LttngDataStream
:
1089 def __getitem__(self
, index
: slice) -> Sequence
[_LttngDataStream
]: # noqa: F811
1092 def __getitem__( # noqa: F811
1093 self
, index
: Union
[int, slice]
1094 ) -> Union
[_LttngDataStream
, Sequence
[_LttngDataStream
]]:
1095 return self
._data
_streams
[index
]
1098 return len(self
._data
_streams
)
1101 # The state of a single data stream.
1102 class _LttngLiveViewerSessionDataStreamState
:
1105 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1106 info
: _LttngLiveViewerStreamInfo
,
1107 data_stream
: _LttngDataStream
,
1108 metadata_stream_id
: int,
1110 self
._ts
_state
= ts_state
1112 self
._data
_stream
= data_stream
1113 self
._metadata
_stream
_id
= metadata_stream_id
1114 self
._cur
_index
_entry
_index
= 0
1115 fmt
= 'Built data stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1119 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1120 ts_state
.tracing_session_descriptor
.info
.name
,
1126 def tracing_session_state(self
):
1127 return self
._ts
_state
1134 def data_stream(self
):
1135 return self
._data
_stream
1138 def cur_index_entry(self
):
1139 if self
._cur
_index
_entry
_index
== len(self
._data
_stream
.index
):
1142 return self
._data
_stream
.index
[self
._cur
_index
_entry
_index
]
1145 def metadata_stream_id(self
):
1146 return self
._metadata
_stream
_id
1148 def goto_next_index_entry(self
):
1149 self
._cur
_index
_entry
_index
+= 1
1152 # The state of a single metadata stream.
1153 class _LttngLiveViewerSessionMetadataStreamState
:
1156 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1157 info
: _LttngLiveViewerStreamInfo
,
1158 metadata_stream
: _LttngMetadataStream
,
1160 self
._ts
_state
= ts_state
1162 self
._metadata
_stream
= metadata_stream
1163 self
._cur
_metadata
_stream
_section
_index
= 0
1164 if len(metadata_stream
.sections
) > 1:
1165 self
._next
_metadata
_stream
_section
_timestamp
= metadata_stream
.sections
[
1169 self
._next
_metadata
_stream
_section
_timestamp
= None
1171 self
._is
_sent
= False
1172 fmt
= 'Built metadata stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1176 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1177 ts_state
.tracing_session_descriptor
.info
.name
,
1178 metadata_stream
.path
,
1187 def metadata_stream(self
):
1188 return self
._metadata
_stream
1192 return self
._is
_sent
1195 def is_sent(self
, value
: bool):
1196 self
._is
_sent
= value
1199 def cur_section(self
):
1200 fmt
= "Get current metadata section: section-idx={}"
1201 logging
.info(fmt
.format(self
._cur
_metadata
_stream
_section
_index
))
1202 if self
._cur
_metadata
_stream
_section
_index
== len(
1203 self
._metadata
_stream
.sections
1207 return self
._metadata
_stream
.sections
[self
._cur
_metadata
_stream
_section
_index
]
1209 def goto_next_section(self
):
1210 self
._cur
_metadata
_stream
_section
_index
+= 1
1211 if self
.cur_section
:
1212 self
._next
_metadata
_stream
_section
_timestamp
= self
.cur_section
.timestamp
1214 self
._next
_metadata
_stream
_section
_timestamp
= None
1217 def next_section_timestamp(self
):
1218 return self
._next
_metadata
_stream
_section
_timestamp
1221 # A tracing session descriptor.
1223 # In the constructor, `traces` is a list of LTTng traces (`LttngTrace`
1225 class LttngTracingSessionDescriptor
:
1229 tracing_session_id
: int,
1231 live_timer_freq
: int,
1233 traces
: Iterable
[LttngTrace
],
1235 for trace
in traces
:
1236 if name
not in trace
.path
:
1237 fmt
= "Tracing session name must be part of every trace path (`{}` not found in `{}`)"
1238 raise ValueError(fmt
.format(name
, trace
.path
))
1240 self
._traces
= traces
1241 stream_count
= sum([len(t
) + 1 for t
in traces
])
1242 self
._info
= _LttngLiveViewerTracingSessionInfo(
1260 # The state of a tracing session.
1261 class _LttngLiveViewerSessionTracingSessionState
:
1262 def __init__(self
, tc_descr
: LttngTracingSessionDescriptor
, base_stream_id
: int):
1263 self
._tc
_descr
= tc_descr
1264 self
._stream
_infos
= [] # type: list[_LttngLiveViewerStreamInfo]
1265 self
._ds
_states
= {} # type: dict[int, _LttngLiveViewerSessionDataStreamState]
1268 ) # type: dict[int, _LttngLiveViewerSessionMetadataStreamState]
1269 stream_id
= base_stream_id
1271 for trace
in tc_descr
.traces
:
1272 trace_id
= stream_id
* 1000
1274 # Metadata stream -> stream info and metadata stream state
1275 info
= _LttngLiveViewerStreamInfo(
1276 stream_id
, trace_id
, True, trace
.metadata_stream
.path
, "metadata"
1278 self
._stream
_infos
.append(info
)
1279 self
._ms
_states
[stream_id
] = _LttngLiveViewerSessionMetadataStreamState(
1280 self
, info
, trace
.metadata_stream
1282 metadata_stream_id
= stream_id
1285 # Data streams -> stream infos and data stream states
1286 for data_stream
in trace
:
1287 info
= _LttngLiveViewerStreamInfo(
1292 data_stream
.channel_name
,
1294 self
._stream
_infos
.append(info
)
1295 self
._ds
_states
[stream_id
] = _LttngLiveViewerSessionDataStreamState(
1296 self
, info
, data_stream
, metadata_stream_id
1300 self
._is
_attached
= False
1301 fmt
= 'Built tracing session state: id={}, name="{}"'
1302 logging
.info(fmt
.format(tc_descr
.info
.tracing_session_id
, tc_descr
.info
.name
))
1305 def tracing_session_descriptor(self
):
1306 return self
._tc
_descr
1309 def data_stream_states(self
):
1310 return self
._ds
_states
1313 def metadata_stream_states(self
):
1314 return self
._ms
_states
1317 def stream_infos(self
):
1318 return self
._stream
_infos
1321 def has_new_metadata(self
):
1322 return any([not ms
.is_sent
for ms
in self
._ms
_states
.values()])
1325 def is_attached(self
):
1326 return self
._is
_attached
1329 def is_attached(self
, value
: bool):
1330 self
._is
_attached
= value
1333 def needs_new_metadata_section(
1334 metadata_stream_state
: _LttngLiveViewerSessionMetadataStreamState
,
1335 latest_timestamp
: int,
1337 if metadata_stream_state
.next_section_timestamp
is None:
1340 if latest_timestamp
>= metadata_stream_state
.next_section_timestamp
:
1346 # An LTTng live viewer session manages a view on tracing sessions
1347 # and replies to commands accordingly.
1348 class _LttngLiveViewerSession
:
1351 viewer_session_id
: int,
1352 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1353 max_query_data_response_size
: Optional
[int],
1355 self
._viewer
_session
_id
= viewer_session_id
1358 ) # type: dict[int, _LttngLiveViewerSessionTracingSessionState]
1359 self
._stream
_states
= (
1361 ) # type: dict[int, _LttngLiveViewerSessionDataStreamState | _LttngLiveViewerSessionMetadataStreamState]
1362 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1363 total_stream_infos
= 0
1365 for ts_descr
in tracing_session_descriptors
:
1366 ts_state
= _LttngLiveViewerSessionTracingSessionState(
1367 ts_descr
, total_stream_infos
1369 ts_id
= ts_state
.tracing_session_descriptor
.info
.tracing_session_id
1370 self
._ts
_states
[ts_id
] = ts_state
1371 total_stream_infos
+= len(ts_state
.stream_infos
)
1373 # Update session's stream states to have the new states
1374 self
._stream
_states
.update(ts_state
.data_stream_states
)
1375 self
._stream
_states
.update(ts_state
.metadata_stream_states
)
1377 self
._command
_handlers
= {
1378 _LttngLiveViewerAttachToTracingSessionCommand
: self
._handle
_attach
_to
_tracing
_session
_command
,
1379 _LttngLiveViewerCreateViewerSessionCommand
: self
._handle
_create
_viewer
_session
_command
,
1380 _LttngLiveViewerDetachFromTracingSessionCommand
: self
._handle
_detach
_from
_tracing
_session
_command
,
1381 _LttngLiveViewerGetDataStreamPacketDataCommand
: self
._handle
_get
_data
_stream
_packet
_data
_command
,
1382 _LttngLiveViewerGetMetadataStreamDataCommand
: self
._handle
_get
_metadata
_stream
_data
_command
,
1383 _LttngLiveViewerGetNewStreamInfosCommand
: self
._handle
_get
_new
_stream
_infos
_command
,
1384 _LttngLiveViewerGetNextDataStreamIndexEntryCommand
: self
._handle
_get
_next
_data
_stream
_index
_entry
_command
,
1385 _LttngLiveViewerGetTracingSessionInfosCommand
: self
._handle
_get
_tracing
_session
_infos
_command
,
1386 } # type: dict[type[_LttngLiveViewerCommand], Callable[[Any], _LttngLiveViewerReply]]
1389 def viewer_session_id(self
):
1390 return self
._viewer
_session
_id
1392 def _get_tracing_session_state(self
, tracing_session_id
: int):
1393 if tracing_session_id
not in self
._ts
_states
:
1395 "Unknown tracing session ID {}".format(tracing_session_id
)
1398 return self
._ts
_states
[tracing_session_id
]
1400 def _get_data_stream_state(self
, stream_id
: int):
1401 if stream_id
not in self
._stream
_states
:
1402 RuntimeError("Unknown stream ID {}".format(stream_id
))
1404 stream
= self
._stream
_states
[stream_id
]
1405 if type(stream
) is not _LttngLiveViewerSessionDataStreamState
:
1406 raise RuntimeError("Stream is not a data stream")
1410 def _get_metadata_stream_state(self
, stream_id
: int):
1411 if stream_id
not in self
._stream
_states
:
1412 RuntimeError("Unknown stream ID {}".format(stream_id
))
1414 stream
= self
._stream
_states
[stream_id
]
1415 if type(stream
) is not _LttngLiveViewerSessionMetadataStreamState
:
1416 raise RuntimeError("Stream is not a metadata stream")
1420 def handle_command(self
, cmd
: _LttngLiveViewerCommand
):
1422 "Handling command in viewer session: cmd-cls-name={}".format(
1423 cmd
.__class
__.__name
__
1426 cmd_type
= type(cmd
)
1428 if cmd_type
not in self
._command
_handlers
:
1430 "Unexpected command: cmd-cls-name={}".format(cmd
.__class
__.__name
__)
1433 return self
._command
_handlers
[cmd_type
](cmd
)
1435 def _handle_attach_to_tracing_session_command(
1436 self
, cmd
: _LttngLiveViewerAttachToTracingSessionCommand
1438 fmt
= 'Handling "attach to tracing session" command: ts-id={}, offset={}, seek-type={}'
1439 logging
.info(fmt
.format(cmd
.tracing_session_id
, cmd
.offset
, cmd
.seek_type
))
1440 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1441 info
= ts_state
.tracing_session_descriptor
.info
1443 if ts_state
.is_attached
:
1445 "Cannot attach to tracing session `{}`: viewer is already attached".format(
1450 ts_state
.is_attached
= True
1451 status
= _LttngLiveViewerAttachToTracingSessionReply
.Status
.OK
1452 return _LttngLiveViewerAttachToTracingSessionReply(
1453 status
, ts_state
.stream_infos
1456 def _handle_detach_from_tracing_session_command(
1457 self
, cmd
: _LttngLiveViewerDetachFromTracingSessionCommand
1459 fmt
= 'Handling "detach from tracing session" command: ts-id={}'
1460 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1461 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1462 info
= ts_state
.tracing_session_descriptor
.info
1464 if not ts_state
.is_attached
:
1466 "Cannot detach to tracing session `{}`: viewer is not attached".format(
1471 ts_state
.is_attached
= False
1472 status
= _LttngLiveViewerDetachFromTracingSessionReply
.Status
.OK
1473 return _LttngLiveViewerDetachFromTracingSessionReply(status
)
1475 def _handle_get_next_data_stream_index_entry_command(
1476 self
, cmd
: _LttngLiveViewerGetNextDataStreamIndexEntryCommand
1478 fmt
= 'Handling "get next data stream index entry" command: stream-id={}'
1479 logging
.info(fmt
.format(cmd
.stream_id
))
1480 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1481 metadata_stream_state
= self
._get
_metadata
_stream
_state
(
1482 stream_state
.metadata_stream_id
1485 if stream_state
.cur_index_entry
is None:
1486 # The viewer is done reading this stream
1487 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.HUP
1489 # Dummy data stream index entry to use with the `HUP` status
1490 # (the reply needs one, but the viewer ignores it)
1491 index_entry
= _LttngDataStreamIndexEntry(0, 0, 0, 0, 0, 0, 0)
1493 return _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1494 status
, index_entry
, False, False
1497 timestamp_begin
= _get_entry_timestamp_begin(stream_state
.cur_index_entry
)
1499 if needs_new_metadata_section(metadata_stream_state
, timestamp_begin
):
1500 metadata_stream_state
.is_sent
= False
1501 metadata_stream_state
.goto_next_section()
1503 # The viewer only checks the `has_new_metadata` flag if the
1504 # reply's status is `OK`, so we need to provide an index here
1505 has_new_metadata
= stream_state
.tracing_session_state
.has_new_metadata
1506 if isinstance(stream_state
.cur_index_entry
, _LttngDataStreamIndexEntry
):
1507 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.OK
1509 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.INACTIVE
1511 reply
= _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1512 status
, stream_state
.cur_index_entry
, has_new_metadata
, False
1514 stream_state
.goto_next_index_entry()
1517 def _handle_get_data_stream_packet_data_command(
1518 self
, cmd
: _LttngLiveViewerGetDataStreamPacketDataCommand
1520 fmt
= 'Handling "get data stream packet data" command: stream-id={}, offset={}, req-length={}'
1521 logging
.info(fmt
.format(cmd
.stream_id
, cmd
.offset
, cmd
.req_length
))
1522 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1523 data_response_length
= cmd
.req_length
1525 if stream_state
.tracing_session_state
.has_new_metadata
:
1526 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.ERROR
1527 return _LttngLiveViewerGetDataStreamPacketDataReply(
1528 status
, bytes(), True, False
1531 if self
._max
_query
_data
_response
_size
:
1532 # Enforce a server side limit on the query requested length.
1533 # To ensure that the transaction terminate take the minimum of both
1535 data_response_length
= min(
1536 cmd
.req_length
, self
._max
_query
_data
_response
_size
1538 fmt
= 'Limiting "get data stream packet data" command: req-length={} actual response size={}'
1539 logging
.info(fmt
.format(cmd
.req_length
, data_response_length
))
1541 data
= stream_state
.data_stream
.get_data(cmd
.offset
, data_response_length
)
1542 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.OK
1543 return _LttngLiveViewerGetDataStreamPacketDataReply(status
, data
, False, False)
1545 def _handle_get_metadata_stream_data_command(
1546 self
, cmd
: _LttngLiveViewerGetMetadataStreamDataCommand
1548 fmt
= 'Handling "get metadata stream data" command: stream-id={}'
1549 logging
.info(fmt
.format(cmd
.stream_id
))
1550 metadata_stream_state
= self
._get
_metadata
_stream
_state
(cmd
.stream_id
)
1552 if metadata_stream_state
.is_sent
:
1553 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.NO_NEW
1554 return _LttngLiveViewerGetMetadataStreamDataContentReply(status
, bytes())
1556 metadata_stream_state
.is_sent
= True
1557 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.OK
1558 metadata_section
= metadata_stream_state
.cur_section
1559 assert metadata_section
is not None
1561 # If we are sending an empty section, ready the next one right away.
1562 if len(metadata_section
.data
) == 0:
1563 metadata_stream_state
.is_sent
= False
1564 metadata_stream_state
.goto_next_section()
1566 fmt
= 'Replying to "get metadata stream data" command: metadata-size={}'
1567 logging
.info(fmt
.format(len(metadata_section
.data
)))
1568 return _LttngLiveViewerGetMetadataStreamDataContentReply(
1569 status
, metadata_section
.data
1572 def _handle_get_new_stream_infos_command(
1573 self
, cmd
: _LttngLiveViewerGetNewStreamInfosCommand
1575 fmt
= 'Handling "get new stream infos" command: ts-id={}'
1576 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1578 # As of this version, all the tracing session's stream infos are
1579 # always given to the viewer when sending the "attach to tracing
1580 # session" reply, so there's nothing new here. Return the `HUP`
1581 # status as, if we're handling this command, the viewer consumed
1582 # all the existing data streams.
1583 status
= _LttngLiveViewerGetNewStreamInfosReply
.Status
.HUP
1584 return _LttngLiveViewerGetNewStreamInfosReply(status
, [])
1586 def _handle_get_tracing_session_infos_command(
1587 self
, cmd
: _LttngLiveViewerGetTracingSessionInfosCommand
1589 logging
.info('Handling "get tracing session infos" command.')
1591 tss
.tracing_session_descriptor
.info
for tss
in self
._ts
_states
.values()
1593 infos
.sort(key
=lambda info
: info
.name
)
1594 return _LttngLiveViewerGetTracingSessionInfosReply(infos
)
1596 def _handle_create_viewer_session_command(
1597 self
, cmd
: _LttngLiveViewerCreateViewerSessionCommand
1599 logging
.info('Handling "create viewer session" command.')
1600 status
= _LttngLiveViewerCreateViewerSessionReply
.Status
.OK
1602 # This does nothing here. In the LTTng relay daemon, it
1603 # allocates the viewer session's state.
1604 return _LttngLiveViewerCreateViewerSessionReply(status
)
1607 # An LTTng live TCP server.
1609 # On creation, it binds to `localhost` on the TCP port `port` if not `None`, or
1610 # on an OS-assigned TCP port otherwise. It writes the decimal TCP port number
1611 # to a temporary port file. It renames the temporary port file to
1614 # `tracing_session_descriptors` is a list of tracing session descriptors
1615 # (`LttngTracingSessionDescriptor`) to serve.
1617 # This server accepts a single viewer (client).
1619 # When the viewer closes the connection, the server's constructor
1621 class LttngLiveServer
:
1624 port
: Optional
[int],
1625 port_filename
: Optional
[str],
1626 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1627 max_query_data_response_size
: Optional
[int],
1629 logging
.info("Server configuration:")
1631 logging
.info(" Port file name: `{}`".format(port_filename
))
1633 if max_query_data_response_size
is not None:
1635 " Maximum response data query size: `{}`".format(
1636 max_query_data_response_size
1640 for ts_descr
in tracing_session_descriptors
:
1641 info
= ts_descr
.info
1642 fmt
= ' TS descriptor: name="{}", id={}, hostname="{}", live-timer-freq={}, client-count={}, stream-count={}:'
1646 info
.tracing_session_id
,
1648 info
.live_timer_freq
,
1654 for trace
in ts_descr
.traces
:
1655 logging
.info(' Trace: path="{}"'.format(trace
.path
))
1657 self
._ts
_descriptors
= tracing_session_descriptors
1658 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1659 self
._sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
1660 self
._codec
= _LttngLiveViewerProtocolCodec()
1662 # Port 0: OS assigns an unused port
1663 serv_addr
= ("localhost", port
if port
is not None else 0)
1664 self
._sock
.bind(serv_addr
)
1666 if port_filename
is not None:
1667 self
._write
_port
_to
_file
(port_filename
)
1669 print("Listening on port {}".format(self
._server
_port
))
1675 logging
.info("Closed connection and socket.")
1678 def _server_port(self
):
1679 return self
._sock
.getsockname()[1]
1681 def _recv_command(self
):
1685 logging
.info("Waiting for viewer command.")
1686 buf
= self
._conn
.recv(128)
1689 logging
.info("Client closed connection.")
1693 "Client closed connection after having sent {} command bytes.".format(
1700 logging
.info("Received data from viewer: length={}".format(len(buf
)))
1705 cmd
= self
._codec
.decode(data
)
1706 except struct
.error
as exc
:
1707 raise RuntimeError("Malformed command: {}".format(exc
)) from exc
1711 "Received command from viewer: cmd-cls-name={}".format(
1712 cmd
.__class
__.__name
__
1717 def _send_reply(self
, reply
: _LttngLiveViewerReply
):
1718 data
= self
._codec
.encode(reply
)
1720 "Sending reply to viewer: reply-cls-name={}, length={}".format(
1721 reply
.__class
__.__name
__, len(data
)
1724 self
._conn
.sendall(data
)
1726 def _handle_connection(self
):
1727 # First command must be "connect"
1728 cmd
= self
._recv
_command
()
1730 if type(cmd
) is not _LttngLiveViewerConnectCommand
:
1732 'First command is not "connect": cmd-cls-name={}'.format(
1733 cmd
.__class
__.__name
__
1737 # Create viewer session (arbitrary ID 23)
1739 "LTTng live viewer connected: version={}.{}".format(cmd
.major
, cmd
.minor
)
1741 viewer_session
= _LttngLiveViewerSession(
1742 23, self
._ts
_descriptors
, self
._max
_query
_data
_response
_size
1745 # Send "connect" reply
1747 _LttngLiveViewerConnectReply(viewer_session
.viewer_session_id
, 2, 10)
1750 # Make the viewer session handle the remaining commands
1752 cmd
= self
._recv
_command
()
1755 # Connection closed (at an expected location within the
1759 self
._send
_reply
(viewer_session
.handle_command(cmd
))
1762 logging
.info("Listening: port={}".format(self
._server
_port
))
1763 # Backlog must be present for Python version < 3.5.
1764 # 128 is an arbitrary number since we expect only 1 connection anyway.
1765 self
._sock
.listen(128)
1766 self
._conn
, viewer_addr
= self
._sock
.accept()
1768 "Accepted viewer: addr={}:{}".format(viewer_addr
[0], viewer_addr
[1])
1772 self
._handle
_connection
()
1776 def _write_port_to_file(self
, port_filename
: str):
1777 # Write the port number to a temporary file.
1778 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as tmp_port_file
:
1779 print(self
._server
_port
, end
="", file=tmp_port_file
)
1781 # Rename temporary file to real file
1782 os
.replace(tmp_port_file
.name
, port_filename
)
1784 'Renamed port file: src-path="{}", dst-path="{}"'.format(
1785 tmp_port_file
.name
, port_filename
1790 def _session_descriptors_from_path(
1791 sessions_filename
: str, trace_path_prefix
: Optional
[str]
1797 # "name": "my-session",
1799 # "hostname": "myhost",
1800 # "live-timer-freq": 1000000,
1801 # "client-count": 23,
1807 # "path": "meow/mix",
1809 # "my_stream": [ 5235787, 728375283 ]
1811 # "metadata-sections": [
1821 with
open(sessions_filename
, "r") as sessions_file
:
1822 sessions_json
= tjson
.load(sessions_file
, tjson
.ArrayVal
)
1824 sessions
= [] # type: list[LttngTracingSessionDescriptor]
1826 for session_json
in sessions_json
.iter(tjson
.ObjVal
):
1827 name
= session_json
.at("name", tjson
.StrVal
).val
1828 tracing_session_id
= session_json
.at("id", tjson
.IntVal
).val
1829 hostname
= session_json
.at("hostname", tjson
.StrVal
).val
1830 live_timer_freq
= session_json
.at("live-timer-freq", tjson
.IntVal
).val
1831 client_count
= session_json
.at("client-count", tjson
.IntVal
).val
1832 traces_json
= session_json
.at("traces", tjson
.ArrayVal
)
1834 traces
= [] # type: list[LttngTrace]
1836 for trace_json
in traces_json
.iter(tjson
.ObjVal
):
1837 metadata_sections
= (
1838 trace_json
.at("metadata-sections", tjson
.ArrayVal
)
1839 if "metadata-sections" in trace_json
1843 trace_json
.at("beacons", tjson
.ObjVal
)
1844 if "beacons" in trace_json
1847 path
= trace_json
.at("path", tjson
.StrVal
).val
1849 if not os
.path
.isabs(path
) and trace_path_prefix
:
1850 path
= os
.path
.join(trace_path_prefix
, path
)
1861 LttngTracingSessionDescriptor(
1874 def _loglevel_parser(string
: str):
1875 loglevels
= {"info": logging
.INFO
, "warning": logging
.WARNING
}
1876 if string
not in loglevels
:
1877 msg
= "{} is not a valid loglevel".format(string
)
1878 raise argparse
.ArgumentTypeError(msg
)
1879 return loglevels
[string
]
1882 if __name__
== "__main__":
1883 logging
.basicConfig(format
="# %(asctime)-25s%(message)s")
1884 parser
= argparse
.ArgumentParser(
1885 description
="LTTng-live protocol mocker", add_help
=False
1887 parser
.add_argument(
1890 choices
=["info", "warning"],
1891 help="The loglevel to be used.",
1894 loglevel_namespace
, remaining_args
= parser
.parse_known_args()
1895 logging
.getLogger().setLevel(_loglevel_parser(loglevel_namespace
.log_level
))
1897 parser
.add_argument(
1899 help="The port to bind to. If missing, use an OS-assigned port..",
1902 parser
.add_argument(
1904 help="The final port file. This file is present when the server is ready to receive connection.",
1906 parser
.add_argument(
1907 "--max-query-data-response-size",
1909 help="The maximum size of control data response in bytes",
1911 parser
.add_argument(
1912 "--trace-path-prefix",
1914 help="Prefix to prepend to the trace paths of session configurations",
1916 parser
.add_argument(
1917 "sessions_filename",
1919 help="Path to a session configuration file",
1920 metavar
="sessions-filename",
1922 parser
.add_argument(
1926 default
=argparse
.SUPPRESS
,
1927 help="Show this help message and exit.",
1930 args
= parser
.parse_args(args
=remaining_args
)
1931 sessions_filename
= args
.sessions_filename
# type: str
1932 trace_path_prefix
= args
.trace_path_prefix
# type: str | None
1933 sessions
= _session_descriptors_from_path(
1938 port
= args
.port
# type: int | None
1939 port_filename
= args
.port_filename
# type: str | None
1940 max_query_data_response_size
= args
.max_query_data_response_size
# type: int | None
1941 LttngLiveServer(port
, port_filename
, sessions
, max_query_data_response_size
)