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]
715 assert os
.path
.isfile(self
._path
)
717 with
open(self
._path
, "rb") as f
:
720 size
= struct
.calcsize(fmt
)
722 assert len(data
) == size
723 magic
, _
, _
, index_entry_length
= struct
.unpack(fmt
, data
)
724 assert magic
== 0xC1F1DCC1
728 size
= struct
.calcsize(fmt
)
732 'Decoding data stream index entry: path="{}", offset={}'.format(
742 assert len(data
) == size
751 ) = struct
.unpack(fmt
, data
)
753 self
._entries
.append(
754 _LttngDataStreamIndexEntry(
765 # Skip anything else before the next entry
766 f
.seek(index_entry_length
- size
, os
.SEEK_CUR
)
768 def _add_beacons(self
, beacons
: Iterable
[_LttngDataStreamBeaconIndexEntry
]):
769 # Assumes entries[n + 1].timestamp_end >= entries[n].timestamp_begin
771 entry
: Union
[_LttngDataStreamIndexEntry
, _LttngDataStreamBeaconIndexEntry
],
773 if isinstance(entry
, _LttngDataStreamBeaconIndexEntry
):
774 return entry
.timestamp
776 return entry
.timestamp_end
778 self
._entries
+= beacons
779 self
._entries
.sort(key
=sort_key
)
782 def __getitem__(self
, index
: int) -> _LttngIndexEntryT
:
786 def __getitem__(self
, index
: slice) -> Sequence
[_LttngIndexEntryT
]: # noqa: F811
789 def __getitem__( # noqa: F811
790 self
, index
: Union
[int, slice]
791 ) -> Union
[_LttngIndexEntryT
, Sequence
[_LttngIndexEntryT
],]:
792 return self
._entries
[index
]
795 return len(self
._entries
)
802 # An LTTng data stream.
803 class _LttngDataStream
:
804 def __init__(self
, path
: str, beacons_json
: Optional
[tjson
.ArrayVal
]):
806 filename
= os
.path
.basename(path
)
807 match
= re
.match(r
"(.*)_\d+", filename
)
810 "Unexpected data stream file name pattern: {}".format(filename
)
813 self
._channel
_name
= match
.group(1)
814 trace_dir
= os
.path
.dirname(path
)
815 index_path
= os
.path
.join(trace_dir
, "index", filename
+ ".idx")
816 self
._index
= _LttngDataStreamIndex(index_path
, beacons_json
)
817 assert os
.path
.isfile(path
)
818 self
._file
= open(path
, "rb")
820 'Built data stream: path="{}", channel-name="{}"'.format(
821 path
, self
._channel
_name
830 def channel_name(self
):
831 return self
._channel
_name
837 def get_data(self
, offset_bytes
: int, len_bytes
: int):
838 self
._file
.seek(offset_bytes
)
839 return self
._file
.read(len_bytes
)
842 class _LttngMetadataStreamSection
:
843 def __init__(self
, timestamp
: int, data
: Optional
[bytes
]):
844 self
._timestamp
= timestamp
850 "Built metadata stream section: ts={}, data-len={}".format(
851 self
._timestamp
, len(self
._data
)
857 return self
._timestamp
864 # An LTTng metadata stream.
865 class _LttngMetadataStream
:
868 metadata_file_path
: str,
869 config_sections
: Sequence
[_LttngMetadataStreamSection
],
871 self
._path
= metadata_file_path
872 self
._sections
= config_sections
874 "Built metadata stream: path={}, section-len={}".format(
875 self
._path
, len(self
._sections
)
885 return self
._sections
888 class LttngMetadataConfigSection
:
889 def __init__(self
, line
: int, timestamp
: int, is_empty
: bool):
891 self
._timestamp
= timestamp
892 self
._is
_empty
= is_empty
900 return self
._timestamp
904 return self
._is
_empty
907 def _parse_metadata_sections_config(metadata_sections_json
: tjson
.ArrayVal
):
908 metadata_sections
= [] # type: list[LttngMetadataConfigSection]
909 append_empty_section
= False
913 for section
in metadata_sections_json
:
914 if isinstance(section
, tjson
.StrVal
):
915 if section
.val
== "empty":
916 # Found a empty section marker. Actually append the section at the
917 # timestamp of the next concrete section.
918 append_empty_section
= True
920 raise ValueError("Invalid string value at {}.".format(section
.path
))
921 elif isinstance(section
, tjson
.ObjVal
):
922 line
= section
.at("line", tjson
.IntVal
).val
923 ts
= section
.at("timestamp", tjson
.IntVal
).val
925 # Sections' timestamps and lines must both be increasing.
926 assert ts
> last_timestamp
929 assert line
> last_line
932 if append_empty_section
:
933 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, True))
934 append_empty_section
= False
936 metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, False))
939 "`{}`: expecting a string or object value".format(section
.path
)
942 return metadata_sections
945 def _split_metadata_sections(
946 metadata_file_path
: str, metadata_sections_json
: tjson
.ArrayVal
948 metadata_sections
= _parse_metadata_sections_config(metadata_sections_json
)
950 sections
= [] # type: list[_LttngMetadataStreamSection]
951 with
open(metadata_file_path
, "r") as metadata_file
:
952 metadata_lines
= [line
for line
in metadata_file
]
954 metadata_section_idx
= 0
955 curr_metadata_section
= bytearray()
957 for idx
, line_content
in enumerate(metadata_lines
):
958 # Add one to the index to convert from the zero-indexing of the
959 # enumerate() function to the one-indexing used by humans when
960 # viewing a text file.
961 curr_line_number
= idx
+ 1
963 # If there are no more sections, simply append the line.
964 if metadata_section_idx
+ 1 >= len(metadata_sections
):
965 curr_metadata_section
+= bytearray(line_content
, "utf8")
968 next_section_line_number
= metadata_sections
[metadata_section_idx
+ 1].line
970 # If the next section begins at the current line, create a
971 # section with the metadata we gathered so far.
972 if curr_line_number
>= next_section_line_number
:
973 # Flushing the metadata of the current section.
975 _LttngMetadataStreamSection(
976 metadata_sections
[metadata_section_idx
].timestamp
,
977 bytes(curr_metadata_section
),
981 # Move to the next section.
982 metadata_section_idx
+= 1
984 # Clear old content and append current line for the next section.
985 curr_metadata_section
.clear()
986 curr_metadata_section
+= bytearray(line_content
, "utf8")
988 # Append any empty sections.
989 while metadata_sections
[metadata_section_idx
].is_empty
:
991 _LttngMetadataStreamSection(
992 metadata_sections
[metadata_section_idx
].timestamp
, None
995 metadata_section_idx
+= 1
997 # Append line_content to the current metadata section.
998 curr_metadata_section
+= bytearray(line_content
, "utf8")
1000 # We iterated over all the lines of the metadata file. Close the current section.
1002 _LttngMetadataStreamSection(
1003 metadata_sections
[metadata_section_idx
].timestamp
,
1004 bytes(curr_metadata_section
),
1011 _StreamBeaconsT
= Dict
[str, Iterable
[int]]
1014 # An LTTng trace, a sequence of LTTng data streams.
1015 class LttngTrace(Sequence
[_LttngDataStream
]):
1019 metadata_sections_json
: Optional
[tjson
.ArrayVal
],
1020 beacons_json
: Optional
[tjson
.ObjVal
],
1022 assert os
.path
.isdir(trace_dir
)
1023 self
._path
= trace_dir
1024 self
._create
_metadata
_stream
(trace_dir
, metadata_sections_json
)
1025 self
._create
_data
_streams
(trace_dir
, beacons_json
)
1026 logging
.info('Built trace: path="{}"'.format(trace_dir
))
1028 def _create_data_streams(
1029 self
, trace_dir
: str, beacons_json
: Optional
[tjson
.ObjVal
]
1031 data_stream_paths
= [] # type: list[str]
1033 for filename
in os
.listdir(trace_dir
):
1034 path
= os
.path
.join(trace_dir
, filename
)
1036 if not os
.path
.isfile(path
):
1039 if filename
.startswith("."):
1042 if filename
== "metadata":
1045 data_stream_paths
.append(path
)
1047 data_stream_paths
.sort()
1048 self
._data
_streams
= [] # type: list[_LttngDataStream]
1050 for data_stream_path
in data_stream_paths
:
1051 stream_name
= os
.path
.basename(data_stream_path
)
1052 this_beacons_json
= None
1053 if beacons_json
is not None and stream_name
in beacons_json
:
1054 this_beacons_json
= beacons_json
.at(stream_name
, tjson
.ArrayVal
)
1056 self
._data
_streams
.append(
1057 _LttngDataStream(data_stream_path
, this_beacons_json
)
1060 def _create_metadata_stream(
1061 self
, trace_dir
: str, metadata_sections_json
: Optional
[tjson
.ArrayVal
]
1063 metadata_path
= os
.path
.join(trace_dir
, "metadata")
1064 metadata_sections
= [] # type: list[_LttngMetadataStreamSection]
1066 if metadata_sections_json
is None:
1067 with
open(metadata_path
, "rb") as metadata_file
:
1068 metadata_sections
.append(
1069 _LttngMetadataStreamSection(0, metadata_file
.read())
1072 metadata_sections
= _split_metadata_sections(
1073 metadata_path
, metadata_sections_json
1076 self
._metadata
_stream
= _LttngMetadataStream(metadata_path
, metadata_sections
)
1083 def metadata_stream(self
):
1084 return self
._metadata
_stream
1087 def __getitem__(self
, index
: int) -> _LttngDataStream
:
1091 def __getitem__(self
, index
: slice) -> Sequence
[_LttngDataStream
]: # noqa: F811
1094 def __getitem__( # noqa: F811
1095 self
, index
: Union
[int, slice]
1096 ) -> Union
[_LttngDataStream
, Sequence
[_LttngDataStream
]]:
1097 return self
._data
_streams
[index
]
1100 return len(self
._data
_streams
)
1103 # The state of a single data stream.
1104 class _LttngLiveViewerSessionDataStreamState
:
1107 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1108 info
: _LttngLiveViewerStreamInfo
,
1109 data_stream
: _LttngDataStream
,
1110 metadata_stream_id
: int,
1112 self
._ts
_state
= ts_state
1114 self
._data
_stream
= data_stream
1115 self
._metadata
_stream
_id
= metadata_stream_id
1116 self
._cur
_index
_entry
_index
= 0
1117 fmt
= 'Built data stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1121 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1122 ts_state
.tracing_session_descriptor
.info
.name
,
1128 def tracing_session_state(self
):
1129 return self
._ts
_state
1136 def data_stream(self
):
1137 return self
._data
_stream
1140 def cur_index_entry(self
):
1141 if self
._cur
_index
_entry
_index
== len(self
._data
_stream
.index
):
1144 return self
._data
_stream
.index
[self
._cur
_index
_entry
_index
]
1147 def metadata_stream_id(self
):
1148 return self
._metadata
_stream
_id
1150 def goto_next_index_entry(self
):
1151 self
._cur
_index
_entry
_index
+= 1
1154 # The state of a single metadata stream.
1155 class _LttngLiveViewerSessionMetadataStreamState
:
1158 ts_state
: "_LttngLiveViewerSessionTracingSessionState",
1159 info
: _LttngLiveViewerStreamInfo
,
1160 metadata_stream
: _LttngMetadataStream
,
1162 self
._ts
_state
= ts_state
1164 self
._metadata
_stream
= metadata_stream
1165 self
._cur
_metadata
_stream
_section
_index
= 0
1166 if len(metadata_stream
.sections
) > 1:
1167 self
._next
_metadata
_stream
_section
_timestamp
= metadata_stream
.sections
[
1171 self
._next
_metadata
_stream
_section
_timestamp
= None
1173 self
._is
_sent
= False
1174 fmt
= 'Built metadata stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1178 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1179 ts_state
.tracing_session_descriptor
.info
.name
,
1180 metadata_stream
.path
,
1189 def metadata_stream(self
):
1190 return self
._metadata
_stream
1194 return self
._is
_sent
1197 def is_sent(self
, value
: bool):
1198 self
._is
_sent
= value
1201 def cur_section(self
):
1202 fmt
= "Get current metadata section: section-idx={}"
1203 logging
.info(fmt
.format(self
._cur
_metadata
_stream
_section
_index
))
1204 if self
._cur
_metadata
_stream
_section
_index
== len(
1205 self
._metadata
_stream
.sections
1209 return self
._metadata
_stream
.sections
[self
._cur
_metadata
_stream
_section
_index
]
1211 def goto_next_section(self
):
1212 self
._cur
_metadata
_stream
_section
_index
+= 1
1213 if self
.cur_section
:
1214 self
._next
_metadata
_stream
_section
_timestamp
= self
.cur_section
.timestamp
1216 self
._next
_metadata
_stream
_section
_timestamp
= None
1219 def next_section_timestamp(self
):
1220 return self
._next
_metadata
_stream
_section
_timestamp
1223 # A tracing session descriptor.
1225 # In the constructor, `traces` is a list of LTTng traces (`LttngTrace`
1227 class LttngTracingSessionDescriptor
:
1231 tracing_session_id
: int,
1233 live_timer_freq
: int,
1235 traces
: Iterable
[LttngTrace
],
1237 for trace
in traces
:
1238 if name
not in trace
.path
:
1239 fmt
= "Tracing session name must be part of every trace path (`{}` not found in `{}`)"
1240 raise ValueError(fmt
.format(name
, trace
.path
))
1242 self
._traces
= traces
1243 stream_count
= sum([len(t
) + 1 for t
in traces
])
1244 self
._info
= _LttngLiveViewerTracingSessionInfo(
1262 # The state of a tracing session.
1263 class _LttngLiveViewerSessionTracingSessionState
:
1264 def __init__(self
, tc_descr
: LttngTracingSessionDescriptor
, base_stream_id
: int):
1265 self
._tc
_descr
= tc_descr
1266 self
._stream
_infos
= [] # type: list[_LttngLiveViewerStreamInfo]
1267 self
._ds
_states
= {} # type: dict[int, _LttngLiveViewerSessionDataStreamState]
1270 ) # type: dict[int, _LttngLiveViewerSessionMetadataStreamState]
1271 stream_id
= base_stream_id
1273 for trace
in tc_descr
.traces
:
1274 trace_id
= stream_id
* 1000
1276 # Metadata stream -> stream info and metadata stream state
1277 info
= _LttngLiveViewerStreamInfo(
1278 stream_id
, trace_id
, True, trace
.metadata_stream
.path
, "metadata"
1280 self
._stream
_infos
.append(info
)
1281 self
._ms
_states
[stream_id
] = _LttngLiveViewerSessionMetadataStreamState(
1282 self
, info
, trace
.metadata_stream
1284 metadata_stream_id
= stream_id
1287 # Data streams -> stream infos and data stream states
1288 for data_stream
in trace
:
1289 info
= _LttngLiveViewerStreamInfo(
1294 data_stream
.channel_name
,
1296 self
._stream
_infos
.append(info
)
1297 self
._ds
_states
[stream_id
] = _LttngLiveViewerSessionDataStreamState(
1298 self
, info
, data_stream
, metadata_stream_id
1302 self
._is
_attached
= False
1303 fmt
= 'Built tracing session state: id={}, name="{}"'
1304 logging
.info(fmt
.format(tc_descr
.info
.tracing_session_id
, tc_descr
.info
.name
))
1307 def tracing_session_descriptor(self
):
1308 return self
._tc
_descr
1311 def data_stream_states(self
):
1312 return self
._ds
_states
1315 def metadata_stream_states(self
):
1316 return self
._ms
_states
1319 def stream_infos(self
):
1320 return self
._stream
_infos
1323 def has_new_metadata(self
):
1324 return any([not ms
.is_sent
for ms
in self
._ms
_states
.values()])
1327 def is_attached(self
):
1328 return self
._is
_attached
1331 def is_attached(self
, value
: bool):
1332 self
._is
_attached
= value
1335 def needs_new_metadata_section(
1336 metadata_stream_state
: _LttngLiveViewerSessionMetadataStreamState
,
1337 latest_timestamp
: int,
1339 if metadata_stream_state
.next_section_timestamp
is None:
1342 if latest_timestamp
>= metadata_stream_state
.next_section_timestamp
:
1348 # An LTTng live viewer session manages a view on tracing sessions
1349 # and replies to commands accordingly.
1350 class _LttngLiveViewerSession
:
1353 viewer_session_id
: int,
1354 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1355 max_query_data_response_size
: Optional
[int],
1357 self
._viewer
_session
_id
= viewer_session_id
1360 ) # type: dict[int, _LttngLiveViewerSessionTracingSessionState]
1361 self
._stream
_states
= (
1363 ) # type: dict[int, _LttngLiveViewerSessionDataStreamState | _LttngLiveViewerSessionMetadataStreamState]
1364 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1365 total_stream_infos
= 0
1367 for ts_descr
in tracing_session_descriptors
:
1368 ts_state
= _LttngLiveViewerSessionTracingSessionState(
1369 ts_descr
, total_stream_infos
1371 ts_id
= ts_state
.tracing_session_descriptor
.info
.tracing_session_id
1372 self
._ts
_states
[ts_id
] = ts_state
1373 total_stream_infos
+= len(ts_state
.stream_infos
)
1375 # Update session's stream states to have the new states
1376 self
._stream
_states
.update(ts_state
.data_stream_states
)
1377 self
._stream
_states
.update(ts_state
.metadata_stream_states
)
1379 self
._command
_handlers
= {
1380 _LttngLiveViewerAttachToTracingSessionCommand
: self
._handle
_attach
_to
_tracing
_session
_command
,
1381 _LttngLiveViewerCreateViewerSessionCommand
: self
._handle
_create
_viewer
_session
_command
,
1382 _LttngLiveViewerDetachFromTracingSessionCommand
: self
._handle
_detach
_from
_tracing
_session
_command
,
1383 _LttngLiveViewerGetDataStreamPacketDataCommand
: self
._handle
_get
_data
_stream
_packet
_data
_command
,
1384 _LttngLiveViewerGetMetadataStreamDataCommand
: self
._handle
_get
_metadata
_stream
_data
_command
,
1385 _LttngLiveViewerGetNewStreamInfosCommand
: self
._handle
_get
_new
_stream
_infos
_command
,
1386 _LttngLiveViewerGetNextDataStreamIndexEntryCommand
: self
._handle
_get
_next
_data
_stream
_index
_entry
_command
,
1387 _LttngLiveViewerGetTracingSessionInfosCommand
: self
._handle
_get
_tracing
_session
_infos
_command
,
1388 } # type: dict[type[_LttngLiveViewerCommand], Callable[[Any], _LttngLiveViewerReply]]
1391 def viewer_session_id(self
):
1392 return self
._viewer
_session
_id
1394 def _get_tracing_session_state(self
, tracing_session_id
: int):
1395 if tracing_session_id
not in self
._ts
_states
:
1397 "Unknown tracing session ID {}".format(tracing_session_id
)
1400 return self
._ts
_states
[tracing_session_id
]
1402 def _get_data_stream_state(self
, stream_id
: int):
1403 if stream_id
not in self
._stream
_states
:
1404 RuntimeError("Unknown stream ID {}".format(stream_id
))
1406 stream
= self
._stream
_states
[stream_id
]
1407 if type(stream
) is not _LttngLiveViewerSessionDataStreamState
:
1408 raise RuntimeError("Stream is not a data stream")
1412 def _get_metadata_stream_state(self
, stream_id
: int):
1413 if stream_id
not in self
._stream
_states
:
1414 RuntimeError("Unknown stream ID {}".format(stream_id
))
1416 stream
= self
._stream
_states
[stream_id
]
1417 if type(stream
) is not _LttngLiveViewerSessionMetadataStreamState
:
1418 raise RuntimeError("Stream is not a metadata stream")
1422 def handle_command(self
, cmd
: _LttngLiveViewerCommand
):
1424 "Handling command in viewer session: cmd-cls-name={}".format(
1425 cmd
.__class
__.__name
__
1428 cmd_type
= type(cmd
)
1430 if cmd_type
not in self
._command
_handlers
:
1432 "Unexpected command: cmd-cls-name={}".format(cmd
.__class
__.__name
__)
1435 return self
._command
_handlers
[cmd_type
](cmd
)
1437 def _handle_attach_to_tracing_session_command(
1438 self
, cmd
: _LttngLiveViewerAttachToTracingSessionCommand
1440 fmt
= 'Handling "attach to tracing session" command: ts-id={}, offset={}, seek-type={}'
1441 logging
.info(fmt
.format(cmd
.tracing_session_id
, cmd
.offset
, cmd
.seek_type
))
1442 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1443 info
= ts_state
.tracing_session_descriptor
.info
1445 if ts_state
.is_attached
:
1447 "Cannot attach to tracing session `{}`: viewer is already attached".format(
1452 ts_state
.is_attached
= True
1453 status
= _LttngLiveViewerAttachToTracingSessionReply
.Status
.OK
1454 return _LttngLiveViewerAttachToTracingSessionReply(
1455 status
, ts_state
.stream_infos
1458 def _handle_detach_from_tracing_session_command(
1459 self
, cmd
: _LttngLiveViewerDetachFromTracingSessionCommand
1461 fmt
= 'Handling "detach from tracing session" command: ts-id={}'
1462 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1463 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1464 info
= ts_state
.tracing_session_descriptor
.info
1466 if not ts_state
.is_attached
:
1468 "Cannot detach to tracing session `{}`: viewer is not attached".format(
1473 ts_state
.is_attached
= False
1474 status
= _LttngLiveViewerDetachFromTracingSessionReply
.Status
.OK
1475 return _LttngLiveViewerDetachFromTracingSessionReply(status
)
1477 def _handle_get_next_data_stream_index_entry_command(
1478 self
, cmd
: _LttngLiveViewerGetNextDataStreamIndexEntryCommand
1480 fmt
= 'Handling "get next data stream index entry" command: stream-id={}'
1481 logging
.info(fmt
.format(cmd
.stream_id
))
1482 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1483 metadata_stream_state
= self
._get
_metadata
_stream
_state
(
1484 stream_state
.metadata_stream_id
1487 if stream_state
.cur_index_entry
is None:
1488 # The viewer is done reading this stream
1489 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.HUP
1491 # Dummy data stream index entry to use with the `HUP` status
1492 # (the reply needs one, but the viewer ignores it)
1493 index_entry
= _LttngDataStreamIndexEntry(0, 0, 0, 0, 0, 0, 0)
1495 return _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1496 status
, index_entry
, False, False
1499 timestamp_begin
= _get_entry_timestamp_begin(stream_state
.cur_index_entry
)
1501 if needs_new_metadata_section(metadata_stream_state
, timestamp_begin
):
1502 metadata_stream_state
.is_sent
= False
1503 metadata_stream_state
.goto_next_section()
1505 # The viewer only checks the `has_new_metadata` flag if the
1506 # reply's status is `OK`, so we need to provide an index here
1507 has_new_metadata
= stream_state
.tracing_session_state
.has_new_metadata
1508 if isinstance(stream_state
.cur_index_entry
, _LttngDataStreamIndexEntry
):
1509 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.OK
1511 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.INACTIVE
1513 reply
= _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1514 status
, stream_state
.cur_index_entry
, has_new_metadata
, False
1516 stream_state
.goto_next_index_entry()
1519 def _handle_get_data_stream_packet_data_command(
1520 self
, cmd
: _LttngLiveViewerGetDataStreamPacketDataCommand
1522 fmt
= 'Handling "get data stream packet data" command: stream-id={}, offset={}, req-length={}'
1523 logging
.info(fmt
.format(cmd
.stream_id
, cmd
.offset
, cmd
.req_length
))
1524 stream_state
= self
._get
_data
_stream
_state
(cmd
.stream_id
)
1525 data_response_length
= cmd
.req_length
1527 if stream_state
.tracing_session_state
.has_new_metadata
:
1528 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.ERROR
1529 return _LttngLiveViewerGetDataStreamPacketDataReply(
1530 status
, bytes(), True, False
1533 if self
._max
_query
_data
_response
_size
:
1534 # Enforce a server side limit on the query requested length.
1535 # To ensure that the transaction terminate take the minimum of both
1537 data_response_length
= min(
1538 cmd
.req_length
, self
._max
_query
_data
_response
_size
1540 fmt
= 'Limiting "get data stream packet data" command: req-length={} actual response size={}'
1541 logging
.info(fmt
.format(cmd
.req_length
, data_response_length
))
1543 data
= stream_state
.data_stream
.get_data(cmd
.offset
, data_response_length
)
1544 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.OK
1545 return _LttngLiveViewerGetDataStreamPacketDataReply(status
, data
, False, False)
1547 def _handle_get_metadata_stream_data_command(
1548 self
, cmd
: _LttngLiveViewerGetMetadataStreamDataCommand
1550 fmt
= 'Handling "get metadata stream data" command: stream-id={}'
1551 logging
.info(fmt
.format(cmd
.stream_id
))
1552 metadata_stream_state
= self
._get
_metadata
_stream
_state
(cmd
.stream_id
)
1554 if metadata_stream_state
.is_sent
:
1555 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.NO_NEW
1556 return _LttngLiveViewerGetMetadataStreamDataContentReply(status
, bytes())
1558 metadata_stream_state
.is_sent
= True
1559 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.OK
1560 metadata_section
= metadata_stream_state
.cur_section
1561 assert metadata_section
is not None
1563 # If we are sending an empty section, ready the next one right away.
1564 if len(metadata_section
.data
) == 0:
1565 metadata_stream_state
.is_sent
= False
1566 metadata_stream_state
.goto_next_section()
1568 fmt
= 'Replying to "get metadata stream data" command: metadata-size={}'
1569 logging
.info(fmt
.format(len(metadata_section
.data
)))
1570 return _LttngLiveViewerGetMetadataStreamDataContentReply(
1571 status
, metadata_section
.data
1574 def _handle_get_new_stream_infos_command(
1575 self
, cmd
: _LttngLiveViewerGetNewStreamInfosCommand
1577 fmt
= 'Handling "get new stream infos" command: ts-id={}'
1578 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1580 # As of this version, all the tracing session's stream infos are
1581 # always given to the viewer when sending the "attach to tracing
1582 # session" reply, so there's nothing new here. Return the `HUP`
1583 # status as, if we're handling this command, the viewer consumed
1584 # all the existing data streams.
1585 status
= _LttngLiveViewerGetNewStreamInfosReply
.Status
.HUP
1586 return _LttngLiveViewerGetNewStreamInfosReply(status
, [])
1588 def _handle_get_tracing_session_infos_command(
1589 self
, cmd
: _LttngLiveViewerGetTracingSessionInfosCommand
1591 logging
.info('Handling "get tracing session infos" command.')
1593 tss
.tracing_session_descriptor
.info
for tss
in self
._ts
_states
.values()
1595 infos
.sort(key
=lambda info
: info
.name
)
1596 return _LttngLiveViewerGetTracingSessionInfosReply(infos
)
1598 def _handle_create_viewer_session_command(
1599 self
, cmd
: _LttngLiveViewerCreateViewerSessionCommand
1601 logging
.info('Handling "create viewer session" command.')
1602 status
= _LttngLiveViewerCreateViewerSessionReply
.Status
.OK
1604 # This does nothing here. In the LTTng relay daemon, it
1605 # allocates the viewer session's state.
1606 return _LttngLiveViewerCreateViewerSessionReply(status
)
1609 # An LTTng live TCP server.
1611 # On creation, it binds to `localhost` on the TCP port `port` if not `None`, or
1612 # on an OS-assigned TCP port otherwise. It writes the decimal TCP port number
1613 # to a temporary port file. It renames the temporary port file to
1616 # `tracing_session_descriptors` is a list of tracing session descriptors
1617 # (`LttngTracingSessionDescriptor`) to serve.
1619 # This server accepts a single viewer (client).
1621 # When the viewer closes the connection, the server's constructor
1623 class LttngLiveServer
:
1626 port
: Optional
[int],
1627 port_filename
: Optional
[str],
1628 tracing_session_descriptors
: Iterable
[LttngTracingSessionDescriptor
],
1629 max_query_data_response_size
: Optional
[int],
1631 logging
.info("Server configuration:")
1633 logging
.info(" Port file name: `{}`".format(port_filename
))
1635 if max_query_data_response_size
is not None:
1637 " Maximum response data query size: `{}`".format(
1638 max_query_data_response_size
1642 for ts_descr
in tracing_session_descriptors
:
1643 info
= ts_descr
.info
1644 fmt
= ' TS descriptor: name="{}", id={}, hostname="{}", live-timer-freq={}, client-count={}, stream-count={}:'
1648 info
.tracing_session_id
,
1650 info
.live_timer_freq
,
1656 for trace
in ts_descr
.traces
:
1657 logging
.info(' Trace: path="{}"'.format(trace
.path
))
1659 self
._ts
_descriptors
= tracing_session_descriptors
1660 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1661 self
._sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
1662 self
._codec
= _LttngLiveViewerProtocolCodec()
1664 # Port 0: OS assigns an unused port
1665 serv_addr
= ("localhost", port
if port
is not None else 0)
1666 self
._sock
.bind(serv_addr
)
1668 if port_filename
is not None:
1669 self
._write
_port
_to
_file
(port_filename
)
1671 print("Listening on port {}".format(self
._server
_port
))
1677 logging
.info("Closed connection and socket.")
1680 def _server_port(self
):
1681 return self
._sock
.getsockname()[1]
1683 def _recv_command(self
):
1687 logging
.info("Waiting for viewer command.")
1688 buf
= self
._conn
.recv(128)
1691 logging
.info("Client closed connection.")
1695 "Client closed connection after having sent {} command bytes.".format(
1702 logging
.info("Received data from viewer: length={}".format(len(buf
)))
1707 cmd
= self
._codec
.decode(data
)
1708 except struct
.error
as exc
:
1709 raise RuntimeError("Malformed command: {}".format(exc
)) from exc
1713 "Received command from viewer: cmd-cls-name={}".format(
1714 cmd
.__class
__.__name
__
1719 def _send_reply(self
, reply
: _LttngLiveViewerReply
):
1720 data
= self
._codec
.encode(reply
)
1722 "Sending reply to viewer: reply-cls-name={}, length={}".format(
1723 reply
.__class
__.__name
__, len(data
)
1726 self
._conn
.sendall(data
)
1728 def _handle_connection(self
):
1729 # First command must be "connect"
1730 cmd
= self
._recv
_command
()
1732 if type(cmd
) is not _LttngLiveViewerConnectCommand
:
1734 'First command is not "connect": cmd-cls-name={}'.format(
1735 cmd
.__class
__.__name
__
1739 # Create viewer session (arbitrary ID 23)
1741 "LTTng live viewer connected: version={}.{}".format(cmd
.major
, cmd
.minor
)
1743 viewer_session
= _LttngLiveViewerSession(
1744 23, self
._ts
_descriptors
, self
._max
_query
_data
_response
_size
1747 # Send "connect" reply
1749 _LttngLiveViewerConnectReply(viewer_session
.viewer_session_id
, 2, 10)
1752 # Make the viewer session handle the remaining commands
1754 cmd
= self
._recv
_command
()
1757 # Connection closed (at an expected location within the
1761 self
._send
_reply
(viewer_session
.handle_command(cmd
))
1764 logging
.info("Listening: port={}".format(self
._server
_port
))
1765 # Backlog must be present for Python version < 3.5.
1766 # 128 is an arbitrary number since we expect only 1 connection anyway.
1767 self
._sock
.listen(128)
1768 self
._conn
, viewer_addr
= self
._sock
.accept()
1770 "Accepted viewer: addr={}:{}".format(viewer_addr
[0], viewer_addr
[1])
1774 self
._handle
_connection
()
1778 def _write_port_to_file(self
, port_filename
: str):
1779 # Write the port number to a temporary file.
1780 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as tmp_port_file
:
1781 print(self
._server
_port
, end
="", file=tmp_port_file
)
1783 # Rename temporary file to real file
1784 os
.replace(tmp_port_file
.name
, port_filename
)
1786 'Renamed port file: src-path="{}", dst-path="{}"'.format(
1787 tmp_port_file
.name
, port_filename
1792 def _session_descriptors_from_path(
1793 sessions_filename
: str, trace_path_prefix
: Optional
[str]
1799 # "name": "my-session",
1801 # "hostname": "myhost",
1802 # "live-timer-freq": 1000000,
1803 # "client-count": 23,
1809 # "path": "meow/mix",
1811 # "my_stream": [ 5235787, 728375283 ]
1813 # "metadata-sections": [
1823 with
open(sessions_filename
, "r") as sessions_file
:
1824 sessions_json
= tjson
.load(sessions_file
, tjson
.ArrayVal
)
1826 sessions
= [] # type: list[LttngTracingSessionDescriptor]
1828 for session_json
in sessions_json
.iter(tjson
.ObjVal
):
1829 name
= session_json
.at("name", tjson
.StrVal
).val
1830 tracing_session_id
= session_json
.at("id", tjson
.IntVal
).val
1831 hostname
= session_json
.at("hostname", tjson
.StrVal
).val
1832 live_timer_freq
= session_json
.at("live-timer-freq", tjson
.IntVal
).val
1833 client_count
= session_json
.at("client-count", tjson
.IntVal
).val
1834 traces_json
= session_json
.at("traces", tjson
.ArrayVal
)
1836 traces
= [] # type: list[LttngTrace]
1838 for trace_json
in traces_json
.iter(tjson
.ObjVal
):
1839 metadata_sections
= (
1840 trace_json
.at("metadata-sections", tjson
.ArrayVal
)
1841 if "metadata-sections" in trace_json
1845 trace_json
.at("beacons", tjson
.ObjVal
)
1846 if "beacons" in trace_json
1849 path
= trace_json
.at("path", tjson
.StrVal
).val
1851 if not os
.path
.isabs(path
) and trace_path_prefix
:
1852 path
= os
.path
.join(trace_path_prefix
, path
)
1863 LttngTracingSessionDescriptor(
1876 def _loglevel_parser(string
: str):
1877 loglevels
= {"info": logging
.INFO
, "warning": logging
.WARNING
}
1878 if string
not in loglevels
:
1879 msg
= "{} is not a valid loglevel".format(string
)
1880 raise argparse
.ArgumentTypeError(msg
)
1881 return loglevels
[string
]
1884 if __name__
== "__main__":
1885 logging
.basicConfig(format
="# %(asctime)-25s%(message)s")
1886 parser
= argparse
.ArgumentParser(
1887 description
="LTTng-live protocol mocker", add_help
=False
1889 parser
.add_argument(
1892 choices
=["info", "warning"],
1893 help="The loglevel to be used.",
1896 loglevel_namespace
, remaining_args
= parser
.parse_known_args()
1897 logging
.getLogger().setLevel(_loglevel_parser(loglevel_namespace
.log_level
))
1899 parser
.add_argument(
1901 help="The port to bind to. If missing, use an OS-assigned port..",
1904 parser
.add_argument(
1906 help="The final port file. This file is present when the server is ready to receive connection.",
1908 parser
.add_argument(
1909 "--max-query-data-response-size",
1911 help="The maximum size of control data response in bytes",
1913 parser
.add_argument(
1914 "--trace-path-prefix",
1916 help="Prefix to prepend to the trace paths of session configurations",
1918 parser
.add_argument(
1919 "--sessions-filename",
1921 help="Path to a session configuration file",
1923 parser
.add_argument(
1927 default
=argparse
.SUPPRESS
,
1928 help="Show this help message and exit.",
1931 args
= parser
.parse_args(args
=remaining_args
)
1932 sessions_filename
= args
.sessions_filename
# type: str
1933 trace_path_prefix
= args
.trace_path_prefix
# type: str | None
1934 sessions
= _session_descriptors_from_path(
1939 port
= args
.port
# type: int | None
1940 port_filename
= args
.port_filename
# type: str | None
1941 max_query_data_response_size
= args
.max_query_data_response_size
# type: int | None
1942 LttngLiveServer(port
, port_filename
, sessions
, max_query_data_response_size
)