1 # SPDX-License-Identifier: MIT
3 # Copyright (C) 2019 Philippe Proulx <pproulx@efficios.com>
16 import collections
.abc
17 from collections
import namedtuple
20 class UnexpectedInput(RuntimeError):
24 # An entry within the index of an LTTng data stream.
25 class _LttngDataStreamIndexEntry
:
36 self
._offset
_bytes
= offset_bytes
37 self
._total
_size
_bits
= total_size_bits
38 self
._content
_size
_bits
= content_size_bits
39 self
._timestamp
_begin
= timestamp_begin
40 self
._timestamp
_end
= timestamp_end
41 self
._events
_discarded
= events_discarded
42 self
._stream
_class
_id
= stream_class_id
45 def offset_bytes(self
):
46 return self
._offset
_bytes
49 def total_size_bits(self
):
50 return self
._total
_size
_bits
53 def total_size_bytes(self
):
54 return self
._total
_size
_bits
// 8
57 def content_size_bits(self
):
58 return self
._content
_size
_bits
61 def content_size_bytes(self
):
62 return self
._content
_size
_bits
// 8
65 def timestamp_begin(self
):
66 return self
._timestamp
_begin
69 def timestamp_end(self
):
70 return self
._timestamp
_end
73 def events_discarded(self
):
74 return self
._events
_discarded
77 def stream_class_id(self
):
78 return self
._stream
_class
_id
81 # An entry within the index of an LTTng data stream. While a stream beacon entry
82 # is conceptually unrelated to an index, it is sent as a reply to a
83 # LttngLiveViewerGetNextDataStreamIndexEntryCommand
84 class _LttngDataStreamBeaconEntry
:
85 def __init__(self
, stream_class_id
, timestamp
):
86 self
._stream
_class
_id
= stream_class_id
87 self
._timestamp
= timestamp
91 return self
._timestamp
94 def stream_class_id(self
):
95 return self
._stream
_class
_id
98 class _LttngLiveViewerCommand
:
99 def __init__(self
, version
):
100 self
._version
= version
107 class _LttngLiveViewerConnectCommand(_LttngLiveViewerCommand
):
108 def __init__(self
, version
, viewer_session_id
, major
, minor
):
109 super().__init
__(version
)
110 self
._viewer
_session
_id
= viewer_session_id
115 def viewer_session_id(self
):
116 return self
._viewer
_session
_id
127 class _LttngLiveViewerConnectReply
:
128 def __init__(self
, viewer_session_id
, major
, minor
):
129 self
._viewer
_session
_id
= viewer_session_id
134 def viewer_session_id(self
):
135 return self
._viewer
_session
_id
146 class _LttngLiveViewerGetTracingSessionInfosCommand(_LttngLiveViewerCommand
):
150 class _LttngLiveViewerTracingSessionInfo
:
160 self
._tracing
_session
_id
= tracing_session_id
161 self
._live
_timer
_freq
= live_timer_freq
162 self
._client
_count
= client_count
163 self
._stream
_count
= stream_count
164 self
._hostname
= hostname
168 def tracing_session_id(self
):
169 return self
._tracing
_session
_id
172 def live_timer_freq(self
):
173 return self
._live
_timer
_freq
176 def client_count(self
):
177 return self
._client
_count
180 def stream_count(self
):
181 return self
._stream
_count
185 return self
._hostname
192 class _LttngLiveViewerGetTracingSessionInfosReply
:
193 def __init__(self
, tracing_session_infos
):
194 self
._tracing
_session
_infos
= tracing_session_infos
197 def tracing_session_infos(self
):
198 return self
._tracing
_session
_infos
201 class _LttngLiveViewerAttachToTracingSessionCommand(_LttngLiveViewerCommand
):
206 def __init__(self
, version
, tracing_session_id
, offset
, seek_type
):
207 super().__init
__(version
)
208 self
._tracing
_session
_id
= tracing_session_id
209 self
._offset
= offset
210 self
._seek
_type
= seek_type
213 def tracing_session_id(self
):
214 return self
._tracing
_session
_id
222 return self
._seek
_type
225 class _LttngLiveViewerStreamInfo
:
226 def __init__(self
, id, trace_id
, is_metadata
, path
, channel_name
):
228 self
._trace
_id
= trace_id
229 self
._is
_metadata
= is_metadata
231 self
._channel
_name
= channel_name
239 return self
._trace
_id
242 def is_metadata(self
):
243 return self
._is
_metadata
250 def channel_name(self
):
251 return self
._channel
_name
254 class _LttngLiveViewerAttachToTracingSessionReply
:
263 def __init__(self
, status
, stream_infos
):
264 self
._status
= status
265 self
._stream
_infos
= stream_infos
272 def stream_infos(self
):
273 return self
._stream
_infos
276 class _LttngLiveViewerGetNextDataStreamIndexEntryCommand(_LttngLiveViewerCommand
):
277 def __init__(self
, version
, stream_id
):
278 super().__init
__(version
)
279 self
._stream
_id
= stream_id
283 return self
._stream
_id
286 class _LttngLiveViewerGetNextDataStreamIndexEntryReply
:
295 def __init__(self
, status
, index_entry
, has_new_metadata
, has_new_data_stream
):
296 self
._status
= status
297 self
._index
_entry
= index_entry
298 self
._has
_new
_metadata
= has_new_metadata
299 self
._has
_new
_data
_stream
= has_new_data_stream
306 def index_entry(self
):
307 return self
._index
_entry
310 def has_new_metadata(self
):
311 return self
._has
_new
_metadata
314 def has_new_data_stream(self
):
315 return self
._has
_new
_data
_stream
318 class _LttngLiveViewerGetDataStreamPacketDataCommand(_LttngLiveViewerCommand
):
319 def __init__(self
, version
, stream_id
, offset
, req_length
):
320 super().__init
__(version
)
321 self
._stream
_id
= stream_id
322 self
._offset
= offset
323 self
._req
_length
= req_length
327 return self
._stream
_id
334 def req_length(self
):
335 return self
._req
_length
338 class _LttngLiveViewerGetDataStreamPacketDataReply
:
345 def __init__(self
, status
, data
, has_new_metadata
, has_new_data_stream
):
346 self
._status
= status
348 self
._has
_new
_metadata
= has_new_metadata
349 self
._has
_new
_data
_stream
= has_new_data_stream
360 def has_new_metadata(self
):
361 return self
._has
_new
_metadata
364 def has_new_data_stream(self
):
365 return self
._has
_new
_data
_stream
368 class _LttngLiveViewerGetMetadataStreamDataCommand(_LttngLiveViewerCommand
):
369 def __init__(self
, version
, stream_id
):
370 super().__init
__(version
)
371 self
._stream
_id
= stream_id
375 return self
._stream
_id
378 class _LttngLiveViewerGetMetadataStreamDataContentReply
:
384 def __init__(self
, status
, data
):
385 self
._status
= status
397 class _LttngLiveViewerGetNewStreamInfosCommand(_LttngLiveViewerCommand
):
398 def __init__(self
, version
, tracing_session_id
):
399 super().__init
__(version
)
400 self
._tracing
_session
_id
= tracing_session_id
403 def tracing_session_id(self
):
404 return self
._tracing
_session
_id
407 class _LttngLiveViewerGetNewStreamInfosReply
:
414 def __init__(self
, status
, stream_infos
):
415 self
._status
= status
416 self
._stream
_infos
= stream_infos
423 def stream_infos(self
):
424 return self
._stream
_infos
427 class _LttngLiveViewerCreateViewerSessionCommand(_LttngLiveViewerCommand
):
431 class _LttngLiveViewerCreateViewerSessionReply
:
436 def __init__(self
, status
):
437 self
._status
= status
444 class _LttngLiveViewerDetachFromTracingSessionCommand(_LttngLiveViewerCommand
):
445 def __init__(self
, version
, tracing_session_id
):
446 super().__init
__(version
)
447 self
._tracing
_session
_id
= tracing_session_id
450 def tracing_session_id(self
):
451 return self
._tracing
_session
_id
454 class _LttngLiveViewerDetachFromTracingSessionReply
:
460 def __init__(self
, status
):
461 self
._status
= status
468 # An LTTng live protocol codec can convert bytes to command objects and
469 # reply objects to bytes.
470 class _LttngLiveViewerProtocolCodec
:
471 _COMMAND_HEADER_STRUCT_FMT
= "QII"
472 _COMMAND_HEADER_SIZE_BYTES
= struct
.calcsize(_COMMAND_HEADER_STRUCT_FMT
)
477 def _unpack(self
, fmt
, data
, offset
=0):
479 return struct
.unpack_from(fmt
, data
, offset
)
481 def _unpack_payload(self
, fmt
, data
):
483 fmt
, data
, _LttngLiveViewerProtocolCodec
._COMMAND
_HEADER
_SIZE
_BYTES
486 def decode(self
, data
):
487 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
:
488 # Not enough data to read the command header
491 payload_size
, cmd_type
, version
= self
._unpack
(
492 self
._COMMAND
_HEADER
_STRUCT
_FMT
, data
495 "Decoded command header: payload-size={}, cmd-type={}, version={}".format(
496 payload_size
, cmd_type
, version
500 if len(data
) < self
._COMMAND
_HEADER
_SIZE
_BYTES
+ payload_size
:
501 # Not enough data to read the whole command
505 viewer_session_id
, major
, minor
, conn_type
= self
._unpack
_payload
(
508 return _LttngLiveViewerConnectCommand(
509 version
, viewer_session_id
, major
, minor
512 return _LttngLiveViewerGetTracingSessionInfosCommand(version
)
514 tracing_session_id
, offset
, seek_type
= self
._unpack
_payload
("QQI", data
)
515 return _LttngLiveViewerAttachToTracingSessionCommand(
516 version
, tracing_session_id
, offset
, seek_type
519 (stream_id
,) = self
._unpack
_payload
("Q", data
)
520 return _LttngLiveViewerGetNextDataStreamIndexEntryCommand(
524 stream_id
, offset
, req_length
= self
._unpack
_payload
("QQI", data
)
525 return _LttngLiveViewerGetDataStreamPacketDataCommand(
526 version
, stream_id
, offset
, req_length
529 (stream_id
,) = self
._unpack
_payload
("Q", data
)
530 return _LttngLiveViewerGetMetadataStreamDataCommand(version
, stream_id
)
532 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
533 return _LttngLiveViewerGetNewStreamInfosCommand(version
, tracing_session_id
)
535 return _LttngLiveViewerCreateViewerSessionCommand(version
)
537 (tracing_session_id
,) = self
._unpack
_payload
("Q", data
)
538 return _LttngLiveViewerDetachFromTracingSessionCommand(
539 version
, tracing_session_id
542 raise UnexpectedInput("Unknown command type {}".format(cmd_type
))
544 def _pack(self
, fmt
, *args
):
545 # Force network byte order
546 return struct
.pack("!" + fmt
, *args
)
548 def _encode_zero_padded_str(self
, string
, length
):
549 data
= string
.encode()
550 return data
.ljust(length
, b
"\x00")
552 def _encode_stream_info(self
, info
):
553 data
= self
._pack
("QQI", info
.id, info
.trace_id
, int(info
.is_metadata
))
554 data
+= self
._encode
_zero
_padded
_str
(info
.path
, 4096)
555 data
+= self
._encode
_zero
_padded
_str
(info
.channel_name
, 255)
558 def _get_has_new_stuff_flags(self
, has_new_metadata
, has_new_data_streams
):
564 if has_new_data_streams
:
569 def encode(self
, reply
):
570 if type(reply
) is _LttngLiveViewerConnectReply
:
572 "QIII", reply
.viewer_session_id
, reply
.major
, reply
.minor
, 2
574 elif type(reply
) is _LttngLiveViewerGetTracingSessionInfosReply
:
575 data
= self
._pack
("I", len(reply
.tracing_session_infos
))
577 for info
in reply
.tracing_session_infos
:
580 info
.tracing_session_id
,
581 info
.live_timer_freq
,
585 data
+= self
._encode
_zero
_padded
_str
(info
.hostname
, 64)
586 data
+= self
._encode
_zero
_padded
_str
(info
.name
, 255)
587 elif type(reply
) is _LttngLiveViewerAttachToTracingSessionReply
:
588 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
590 for info
in reply
.stream_infos
:
591 data
+= self
._encode
_stream
_info
(info
)
592 elif type(reply
) is _LttngLiveViewerGetNextDataStreamIndexEntryReply
:
593 index_format
= "QQQQQQQII"
594 entry
= reply
.index_entry
595 flags
= self
._get
_has
_new
_stuff
_flags
(
596 reply
.has_new_metadata
, reply
.has_new_data_stream
599 if type(entry
) is _LttngDataStreamIndexEntry
:
603 entry
.total_size_bits
,
604 entry
.content_size_bits
,
605 entry
.timestamp_begin
,
607 entry
.events_discarded
,
608 entry
.stream_class_id
,
613 assert type(entry
) is _LttngDataStreamBeaconEntry
622 entry
.stream_class_id
,
626 elif type(reply
) is _LttngLiveViewerGetDataStreamPacketDataReply
:
627 flags
= self
._get
_has
_new
_stuff
_flags
(
628 reply
.has_new_metadata
, reply
.has_new_data_stream
630 data
= self
._pack
("III", reply
.status
, len(reply
.data
), flags
)
632 elif type(reply
) is _LttngLiveViewerGetMetadataStreamDataContentReply
:
633 data
= self
._pack
("QI", len(reply
.data
), reply
.status
)
635 elif type(reply
) is _LttngLiveViewerGetNewStreamInfosReply
:
636 data
= self
._pack
("II", reply
.status
, len(reply
.stream_infos
))
638 for info
in reply
.stream_infos
:
639 data
+= self
._encode
_stream
_info
(info
)
640 elif type(reply
) is _LttngLiveViewerCreateViewerSessionReply
:
641 data
= self
._pack
("I", reply
.status
)
642 elif type(reply
) is _LttngLiveViewerDetachFromTracingSessionReply
:
643 data
= self
._pack
("I", reply
.status
)
646 "Unknown reply object with class `{}`".format(reply
.__class
__.__name
__)
652 def _get_entry_timestamp_begin(entry
):
653 if type(entry
) is _LttngDataStreamBeaconEntry
:
654 return entry
.timestamp
656 assert type(entry
) is _LttngDataStreamIndexEntry
657 return entry
.timestamp_begin
660 # The index of an LTTng data stream, a sequence of index entries.
661 class _LttngDataStreamIndex(collections
.abc
.Sequence
):
662 def __init__(self
, path
, beacons
):
667 stream_class_id
= self
._entries
[0].stream_class_id
669 _LttngDataStreamBeaconEntry(stream_class_id
, ts
) for ts
in beacons
671 self
._add
_beacons
(beacons
)
674 'Built data stream index entries: path="{}", count={}'.format(
675 path
, len(self
._entries
)
681 assert os
.path
.isfile(self
._path
)
683 with
open(self
._path
, "rb") as f
:
686 size
= struct
.calcsize(fmt
)
688 assert len(data
) == size
689 magic
, index_major
, index_minor
, index_entry_length
= struct
.unpack(
692 assert magic
== 0xC1F1DCC1
696 size
= struct
.calcsize(fmt
)
700 'Decoding data stream index entry: path="{}", offset={}'.format(
710 assert len(data
) == size
719 ) = struct
.unpack(fmt
, data
)
721 self
._entries
.append(
722 _LttngDataStreamIndexEntry(
733 # Skip anything else before the next entry
734 f
.seek(index_entry_length
- size
, os
.SEEK_CUR
)
736 def _add_beacons(self
, beacons
):
737 # Assumes entries[n + 1].timestamp_end >= entries[n].timestamp_begin
739 if type(entry
) is _LttngDataStreamBeaconEntry
:
740 return entry
.timestamp
742 return entry
.timestamp_end
744 self
._entries
+= beacons
745 self
._entries
.sort(key
=sort_key
)
747 def __getitem__(self
, index
):
748 return self
._entries
[index
]
751 return len(self
._entries
)
758 # An LTTng data stream.
759 class _LttngDataStream
:
760 def __init__(self
, path
, beacons
):
762 filename
= os
.path
.basename(path
)
763 match
= re
.match(r
"(.*)_\d+", filename
)
764 self
._channel
_name
= match
.group(1)
765 trace_dir
= os
.path
.dirname(path
)
766 index_path
= os
.path
.join(trace_dir
, "index", filename
+ ".idx")
767 self
._index
= _LttngDataStreamIndex(index_path
, beacons
)
768 assert os
.path
.isfile(path
)
769 self
._file
= open(path
, "rb")
771 'Built data stream: path="{}", channel-name="{}"'.format(
772 path
, self
._channel
_name
781 def channel_name(self
):
782 return self
._channel
_name
788 def get_data(self
, offset_bytes
, len_bytes
):
789 self
._file
.seek(offset_bytes
)
790 return self
._file
.read(len_bytes
)
793 class _LttngMetadataStreamSection
:
794 def __init__(self
, timestamp
, data
):
795 self
._timestamp
= timestamp
801 "Built metadata stream section: ts={}, data-len={}".format(
802 self
._timestamp
, len(self
._data
)
808 return self
._timestamp
815 # An LTTng metadata stream.
816 class _LttngMetadataStream
:
817 def __init__(self
, metadata_file_path
, config_sections
):
818 self
._path
= metadata_file_path
819 self
._sections
= config_sections
821 "Built metadata stream: path={}, section-len={}".format(
822 self
._path
, len(self
._sections
)
832 return self
._sections
835 LttngMetadataConfigSection
= namedtuple(
836 "LttngMetadataConfigSection", ["line", "timestamp", "is_empty"]
840 def _parse_metadata_sections_config(config_sections
):
841 assert config_sections
is not None
842 config_metadata_sections
= []
843 append_empty_section
= False
847 for config_section
in config_sections
:
848 if config_section
== "empty":
849 # Found a empty section marker. Actually append the section at the
850 # timestamp of the next concrete section.
851 append_empty_section
= True
853 assert type(config_section
) is dict
854 line
= config_section
.get("line")
855 ts
= config_section
.get("timestamp")
857 # Sections' timestamps and lines must both be increasing.
858 assert ts
> last_timestamp
860 assert line
> last_line
863 if append_empty_section
:
864 config_metadata_sections
.append(
865 LttngMetadataConfigSection(line
, ts
, True)
867 append_empty_section
= False
869 config_metadata_sections
.append(LttngMetadataConfigSection(line
, ts
, False))
871 return config_metadata_sections
874 def _split_metadata_sections(metadata_file_path
, raw_config_sections
):
875 assert isinstance(raw_config_sections
, collections
.abc
.Sequence
)
877 parsed_sections
= _parse_metadata_sections_config(raw_config_sections
)
880 with
open(metadata_file_path
, "r") as metadata_file
:
881 metadata_lines
= [line
for line
in metadata_file
]
883 config_metadata_sections_idx
= 0
884 curr_metadata_section
= bytearray()
886 for idx
, line_content
in enumerate(metadata_lines
):
887 # Add one to the index to convert from the zero-indexing of the
888 # enumerate() function to the one-indexing used by humans when
889 # viewing a text file.
890 curr_line_number
= idx
+ 1
892 # If there are no more sections, simply append the line.
893 if config_metadata_sections_idx
+ 1 >= len(parsed_sections
):
894 curr_metadata_section
+= bytearray(line_content
, "utf8")
897 next_section_line_number
= parsed_sections
[
898 config_metadata_sections_idx
+ 1
901 # If the next section begins at the current line, create a
902 # section with the metadata we gathered so far.
903 if curr_line_number
>= next_section_line_number
:
904 # Flushing the metadata of the current section.
906 _LttngMetadataStreamSection(
907 parsed_sections
[config_metadata_sections_idx
].timestamp
,
908 bytes(curr_metadata_section
),
912 # Move to the next section.
913 config_metadata_sections_idx
+= 1
915 # Clear old content and append current line for the next section.
916 curr_metadata_section
.clear()
917 curr_metadata_section
+= bytearray(line_content
, "utf8")
919 # Append any empty sections.
920 while parsed_sections
[config_metadata_sections_idx
].is_empty
:
922 _LttngMetadataStreamSection(
923 parsed_sections
[config_metadata_sections_idx
].timestamp
, None
926 config_metadata_sections_idx
+= 1
928 # Append line_content to the current metadata section.
929 curr_metadata_section
+= bytearray(line_content
, "utf8")
931 # We iterated over all the lines of the metadata file. Close the current section.
933 _LttngMetadataStreamSection(
934 parsed_sections
[config_metadata_sections_idx
].timestamp
,
935 bytes(curr_metadata_section
),
942 # An LTTng trace, a sequence of LTTng data streams.
943 class LttngTrace(collections
.abc
.Sequence
):
944 def __init__(self
, trace_dir
, metadata_sections
, beacons
):
945 assert os
.path
.isdir(trace_dir
)
946 self
._path
= trace_dir
947 self
._create
_metadata
_stream
(trace_dir
, metadata_sections
)
948 self
._create
_data
_streams
(trace_dir
, beacons
)
949 logging
.info('Built trace: path="{}"'.format(trace_dir
))
951 def _create_data_streams(self
, trace_dir
, beacons
):
952 data_stream_paths
= []
954 for filename
in os
.listdir(trace_dir
):
955 path
= os
.path
.join(trace_dir
, filename
)
957 if not os
.path
.isfile(path
):
960 if filename
.startswith("."):
963 if filename
== "metadata":
966 data_stream_paths
.append(path
)
968 data_stream_paths
.sort()
969 self
._data
_streams
= []
971 for data_stream_path
in data_stream_paths
:
972 stream_name
= os
.path
.basename(data_stream_path
)
973 this_stream_beacons
= None
975 if beacons
is not None and stream_name
in beacons
:
976 this_stream_beacons
= beacons
[stream_name
]
978 self
._data
_streams
.append(
979 _LttngDataStream(data_stream_path
, this_stream_beacons
)
982 def _create_metadata_stream(self
, trace_dir
, config_metadata_sections
):
983 metadata_path
= os
.path
.join(trace_dir
, "metadata")
984 metadata_sections
= []
986 if config_metadata_sections
is None:
987 with
open(metadata_path
, "rb") as metadata_file
:
988 metadata_sections
.append(
989 _LttngMetadataStreamSection(0, metadata_file
.read())
992 metadata_sections
= _split_metadata_sections(
993 metadata_path
, config_metadata_sections
996 self
._metadata
_stream
= _LttngMetadataStream(metadata_path
, metadata_sections
)
1003 def metadata_stream(self
):
1004 return self
._metadata
_stream
1006 def __getitem__(self
, index
):
1007 return self
._data
_streams
[index
]
1010 return len(self
._data
_streams
)
1013 # The state of a single data stream.
1014 class _LttngLiveViewerSessionDataStreamState
:
1015 def __init__(self
, ts_state
, info
, data_stream
, metadata_stream_id
):
1016 self
._ts
_state
= ts_state
1018 self
._data
_stream
= data_stream
1019 self
._metadata
_stream
_id
= metadata_stream_id
1020 self
._cur
_index
_entry
_index
= 0
1021 fmt
= 'Built data stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1025 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1026 ts_state
.tracing_session_descriptor
.info
.name
,
1032 def tracing_session_state(self
):
1033 return self
._ts
_state
1040 def data_stream(self
):
1041 return self
._data
_stream
1044 def cur_index_entry(self
):
1045 if self
._cur
_index
_entry
_index
== len(self
._data
_stream
.index
):
1048 return self
._data
_stream
.index
[self
._cur
_index
_entry
_index
]
1050 def goto_next_index_entry(self
):
1051 self
._cur
_index
_entry
_index
+= 1
1054 # The state of a single metadata stream.
1055 class _LttngLiveViewerSessionMetadataStreamState
:
1056 def __init__(self
, ts_state
, info
, metadata_stream
):
1057 self
._ts
_state
= ts_state
1059 self
._metadata
_stream
= metadata_stream
1060 self
._cur
_metadata
_stream
_section
_index
= 0
1061 if len(metadata_stream
.sections
) > 1:
1062 self
._next
_metadata
_stream
_section
_timestamp
= metadata_stream
.sections
[
1066 self
._next
_metadata
_stream
_section
_timestamp
= None
1068 self
._is
_sent
= False
1069 fmt
= 'Built metadata stream state: id={}, ts-id={}, ts-name="{}", path="{}"'
1073 ts_state
.tracing_session_descriptor
.info
.tracing_session_id
,
1074 ts_state
.tracing_session_descriptor
.info
.name
,
1075 metadata_stream
.path
,
1080 def trace_session_state(self
):
1081 return self
._trace
_session
_state
1088 def metadata_stream(self
):
1089 return self
._metadata
_stream
1093 return self
._is
_sent
1096 def is_sent(self
, value
):
1097 self
._is
_sent
= value
1100 def cur_section(self
):
1101 fmt
= "Get current metadata section: section-idx={}"
1102 logging
.info(fmt
.format(self
._cur
_metadata
_stream
_section
_index
))
1103 if self
._cur
_metadata
_stream
_section
_index
== len(
1104 self
._metadata
_stream
.sections
1108 return self
._metadata
_stream
.sections
[self
._cur
_metadata
_stream
_section
_index
]
1110 def goto_next_section(self
):
1111 self
._cur
_metadata
_stream
_section
_index
+= 1
1112 if self
.cur_section
:
1113 self
._next
_metadata
_stream
_section
_timestamp
= self
.cur_section
.timestamp
1115 self
._next
_metadata
_stream
_section
_timestamp
= None
1118 def next_section_timestamp(self
):
1119 return self
._next
_metadata
_stream
_section
_timestamp
1122 # A tracing session descriptor.
1124 # In the constructor, `traces` is a list of LTTng traces (`LttngTrace`
1126 class LttngTracingSessionDescriptor
:
1128 self
, name
, tracing_session_id
, hostname
, live_timer_freq
, client_count
, traces
1130 for trace
in traces
:
1131 if name
not in trace
.path
:
1132 fmt
= "Tracing session name must be part of every trace path (`{}` not found in `{}`)"
1133 raise ValueError(fmt
.format(name
, trace
.path
))
1135 self
._traces
= traces
1136 stream_count
= sum([len(t
) + 1 for t
in traces
])
1137 self
._info
= _LttngLiveViewerTracingSessionInfo(
1155 # The state of a tracing session.
1156 class _LttngLiveViewerSessionTracingSessionState
:
1157 def __init__(self
, tc_descr
, base_stream_id
):
1158 self
._tc
_descr
= tc_descr
1159 self
._stream
_infos
= []
1160 self
._ds
_states
= {}
1161 self
._ms
_states
= {}
1162 stream_id
= base_stream_id
1164 for trace
in tc_descr
.traces
:
1165 trace_id
= stream_id
* 1000
1167 # Metadata stream -> stream info and metadata stream state
1168 info
= _LttngLiveViewerStreamInfo(
1169 stream_id
, trace_id
, True, trace
.metadata_stream
.path
, "metadata"
1171 self
._stream
_infos
.append(info
)
1172 self
._ms
_states
[stream_id
] = _LttngLiveViewerSessionMetadataStreamState(
1173 self
, info
, trace
.metadata_stream
1175 metadata_stream_id
= stream_id
1178 # Data streams -> stream infos and data stream states
1179 for data_stream
in trace
:
1180 info
= _LttngLiveViewerStreamInfo(
1185 data_stream
.channel_name
,
1187 self
._stream
_infos
.append(info
)
1188 self
._ds
_states
[stream_id
] = _LttngLiveViewerSessionDataStreamState(
1189 self
, info
, data_stream
, metadata_stream_id
1193 self
._is
_attached
= False
1194 fmt
= 'Built tracing session state: id={}, name="{}"'
1195 logging
.info(fmt
.format(tc_descr
.info
.tracing_session_id
, tc_descr
.info
.name
))
1198 def tracing_session_descriptor(self
):
1199 return self
._tc
_descr
1202 def data_stream_states(self
):
1203 return self
._ds
_states
1206 def metadata_stream_states(self
):
1207 return self
._ms
_states
1210 def stream_infos(self
):
1211 return self
._stream
_infos
1214 def has_new_metadata(self
):
1215 return any([not ms
.is_sent
for ms
in self
._ms
_states
.values()])
1218 def is_attached(self
):
1219 return self
._is
_attached
1222 def is_attached(self
, value
):
1223 self
._is
_attached
= value
1226 def needs_new_metadata_section(metadata_stream_state
, latest_timestamp
):
1227 if metadata_stream_state
.next_section_timestamp
is None:
1230 if latest_timestamp
>= metadata_stream_state
.next_section_timestamp
:
1236 # An LTTng live viewer session manages a view on tracing sessions
1237 # and replies to commands accordingly.
1238 class _LttngLiveViewerSession
:
1242 tracing_session_descriptors
,
1243 max_query_data_response_size
,
1245 self
._viewer
_session
_id
= viewer_session_id
1246 self
._ts
_states
= {}
1247 self
._stream
_states
= {}
1248 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1249 total_stream_infos
= 0
1251 for ts_descr
in tracing_session_descriptors
:
1252 ts_state
= _LttngLiveViewerSessionTracingSessionState(
1253 ts_descr
, total_stream_infos
1255 ts_id
= ts_state
.tracing_session_descriptor
.info
.tracing_session_id
1256 self
._ts
_states
[ts_id
] = ts_state
1257 total_stream_infos
+= len(ts_state
.stream_infos
)
1259 # Update session's stream states to have the new states
1260 self
._stream
_states
.update(ts_state
.data_stream_states
)
1261 self
._stream
_states
.update(ts_state
.metadata_stream_states
)
1263 self
._command
_handlers
= {
1264 _LttngLiveViewerAttachToTracingSessionCommand
: self
._handle
_attach
_to
_tracing
_session
_command
,
1265 _LttngLiveViewerCreateViewerSessionCommand
: self
._handle
_create
_viewer
_session
_command
,
1266 _LttngLiveViewerDetachFromTracingSessionCommand
: self
._handle
_detach
_from
_tracing
_session
_command
,
1267 _LttngLiveViewerGetDataStreamPacketDataCommand
: self
._handle
_get
_data
_stream
_packet
_data
_command
,
1268 _LttngLiveViewerGetMetadataStreamDataCommand
: self
._handle
_get
_metadata
_stream
_data
_command
,
1269 _LttngLiveViewerGetNewStreamInfosCommand
: self
._handle
_get
_new
_stream
_infos
_command
,
1270 _LttngLiveViewerGetNextDataStreamIndexEntryCommand
: self
._handle
_get
_next
_data
_stream
_index
_entry
_command
,
1271 _LttngLiveViewerGetTracingSessionInfosCommand
: self
._handle
_get
_tracing
_session
_infos
_command
,
1275 def viewer_session_id(self
):
1276 return self
._viewer
_session
_id
1278 def _get_tracing_session_state(self
, tracing_session_id
):
1279 if tracing_session_id
not in self
._ts
_states
:
1280 raise UnexpectedInput(
1281 "Unknown tracing session ID {}".format(tracing_session_id
)
1284 return self
._ts
_states
[tracing_session_id
]
1286 def _get_stream_state(self
, stream_id
):
1287 if stream_id
not in self
._stream
_states
:
1288 UnexpectedInput("Unknown stream ID {}".format(stream_id
))
1290 return self
._stream
_states
[stream_id
]
1292 def handle_command(self
, cmd
):
1294 "Handling command in viewer session: cmd-cls-name={}".format(
1295 cmd
.__class
__.__name
__
1298 cmd_type
= type(cmd
)
1300 if cmd_type
not in self
._command
_handlers
:
1301 raise UnexpectedInput(
1302 "Unexpected command: cmd-cls-name={}".format(cmd
.__class
__.__name
__)
1305 return self
._command
_handlers
[cmd_type
](cmd
)
1307 def _handle_attach_to_tracing_session_command(self
, cmd
):
1308 fmt
= 'Handling "attach to tracing session" command: ts-id={}, offset={}, seek-type={}'
1309 logging
.info(fmt
.format(cmd
.tracing_session_id
, cmd
.offset
, cmd
.seek_type
))
1310 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1311 info
= ts_state
.tracing_session_descriptor
.info
1313 if ts_state
.is_attached
:
1314 raise UnexpectedInput(
1315 "Cannot attach to tracing session `{}`: viewer is already attached".format(
1320 ts_state
.is_attached
= True
1321 status
= _LttngLiveViewerAttachToTracingSessionReply
.Status
.OK
1322 return _LttngLiveViewerAttachToTracingSessionReply(
1323 status
, ts_state
.stream_infos
1326 def _handle_detach_from_tracing_session_command(self
, cmd
):
1327 fmt
= 'Handling "detach from tracing session" command: ts-id={}'
1328 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1329 ts_state
= self
._get
_tracing
_session
_state
(cmd
.tracing_session_id
)
1330 info
= ts_state
.tracing_session_descriptor
.info
1332 if not ts_state
.is_attached
:
1333 raise UnexpectedInput(
1334 "Cannot detach to tracing session `{}`: viewer is not attached".format(
1339 ts_state
.is_attached
= False
1340 status
= _LttngLiveViewerDetachFromTracingSessionReply
.Status
.OK
1341 return _LttngLiveViewerDetachFromTracingSessionReply(status
)
1343 def _handle_get_next_data_stream_index_entry_command(self
, cmd
):
1344 fmt
= 'Handling "get next data stream index entry" command: stream-id={}'
1345 logging
.info(fmt
.format(cmd
.stream_id
))
1346 stream_state
= self
._get
_stream
_state
(cmd
.stream_id
)
1347 metadata_stream_state
= self
._get
_stream
_state
(stream_state
._metadata
_stream
_id
)
1349 if type(stream_state
) is not _LttngLiveViewerSessionDataStreamState
:
1350 raise UnexpectedInput(
1351 "Stream with ID {} is not a data stream".format(cmd
.stream_id
)
1354 if stream_state
.cur_index_entry
is None:
1355 # The viewer is done reading this stream
1356 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.HUP
1358 # Dummy data stream index entry to use with the `HUP` status
1359 # (the reply needs one, but the viewer ignores it)
1360 index_entry
= _LttngDataStreamIndexEntry(0, 0, 0, 0, 0, 0, 0)
1362 return _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1363 status
, index_entry
, False, False
1366 timestamp_begin
= _get_entry_timestamp_begin(stream_state
.cur_index_entry
)
1368 if needs_new_metadata_section(metadata_stream_state
, timestamp_begin
):
1369 metadata_stream_state
.is_sent
= False
1370 metadata_stream_state
.goto_next_section()
1372 # The viewer only checks the `has_new_metadata` flag if the
1373 # reply's status is `OK`, so we need to provide an index here
1374 has_new_metadata
= stream_state
.tracing_session_state
.has_new_metadata
1375 if type(stream_state
.cur_index_entry
) is _LttngDataStreamIndexEntry
:
1376 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.OK
1378 assert type(stream_state
.cur_index_entry
) is _LttngDataStreamBeaconEntry
1379 status
= _LttngLiveViewerGetNextDataStreamIndexEntryReply
.Status
.INACTIVE
1381 reply
= _LttngLiveViewerGetNextDataStreamIndexEntryReply(
1382 status
, stream_state
.cur_index_entry
, has_new_metadata
, False
1384 stream_state
.goto_next_index_entry()
1387 def _handle_get_data_stream_packet_data_command(self
, cmd
):
1388 fmt
= 'Handling "get data stream packet data" command: stream-id={}, offset={}, req-length={}'
1389 logging
.info(fmt
.format(cmd
.stream_id
, cmd
.offset
, cmd
.req_length
))
1390 stream_state
= self
._get
_stream
_state
(cmd
.stream_id
)
1391 data_response_length
= cmd
.req_length
1393 if type(stream_state
) is not _LttngLiveViewerSessionDataStreamState
:
1394 raise UnexpectedInput(
1395 "Stream with ID {} is not a data stream".format(cmd
.stream_id
)
1398 if stream_state
.tracing_session_state
.has_new_metadata
:
1399 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.ERROR
1400 return _LttngLiveViewerGetDataStreamPacketDataReply(
1401 status
, bytes(), True, False
1404 if self
._max
_query
_data
_response
_size
:
1405 # Enforce a server side limit on the query requested length.
1406 # To ensure that the transaction terminate take the minimum of both
1408 data_response_length
= min(
1409 cmd
.req_length
, self
._max
_query
_data
_response
_size
1411 fmt
= 'Limiting "get data stream packet data" command: req-length={} actual response size={}'
1412 logging
.info(fmt
.format(cmd
.req_length
, data_response_length
))
1414 data
= stream_state
.data_stream
.get_data(cmd
.offset
, data_response_length
)
1415 status
= _LttngLiveViewerGetDataStreamPacketDataReply
.Status
.OK
1416 return _LttngLiveViewerGetDataStreamPacketDataReply(status
, data
, False, False)
1418 def _handle_get_metadata_stream_data_command(self
, cmd
):
1419 fmt
= 'Handling "get metadata stream data" command: stream-id={}'
1420 logging
.info(fmt
.format(cmd
.stream_id
))
1421 metadata_stream_state
= self
._get
_stream
_state
(cmd
.stream_id
)
1424 type(metadata_stream_state
)
1425 is not _LttngLiveViewerSessionMetadataStreamState
1427 raise UnexpectedInput(
1428 "Stream with ID {} is not a metadata stream".format(cmd
.stream_id
)
1431 if metadata_stream_state
.is_sent
:
1432 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.NO_NEW
1433 return _LttngLiveViewerGetMetadataStreamDataContentReply(status
, bytes())
1435 metadata_stream_state
.is_sent
= True
1436 status
= _LttngLiveViewerGetMetadataStreamDataContentReply
.Status
.OK
1437 metadata_section
= metadata_stream_state
.cur_section
1439 # If we are sending an empty section, ready the next one right away.
1440 if len(metadata_section
.data
) == 0:
1441 metadata_stream_state
.is_sent
= False
1442 metadata_stream_state
.goto_next_section()
1444 fmt
= 'Replying to "get metadata stream data" command: metadata-size={}'
1445 logging
.info(fmt
.format(len(metadata_section
.data
)))
1446 return _LttngLiveViewerGetMetadataStreamDataContentReply(
1447 status
, metadata_section
.data
1450 def _handle_get_new_stream_infos_command(self
, cmd
):
1451 fmt
= 'Handling "get new stream infos" command: ts-id={}'
1452 logging
.info(fmt
.format(cmd
.tracing_session_id
))
1454 # As of this version, all the tracing session's stream infos are
1455 # always given to the viewer when sending the "attach to tracing
1456 # session" reply, so there's nothing new here. Return the `HUP`
1457 # status as, if we're handling this command, the viewer consumed
1458 # all the existing data streams.
1459 status
= _LttngLiveViewerGetNewStreamInfosReply
.Status
.HUP
1460 return _LttngLiveViewerGetNewStreamInfosReply(status
, [])
1462 def _handle_get_tracing_session_infos_command(self
, cmd
):
1463 logging
.info('Handling "get tracing session infos" command.')
1465 tss
.tracing_session_descriptor
.info
for tss
in self
._ts
_states
.values()
1467 infos
.sort(key
=lambda info
: info
.name
)
1468 return _LttngLiveViewerGetTracingSessionInfosReply(infos
)
1470 def _handle_create_viewer_session_command(self
, cmd
):
1471 logging
.info('Handling "create viewer session" command.')
1472 status
= _LttngLiveViewerCreateViewerSessionReply
.Status
.OK
1474 # This does nothing here. In the LTTng relay daemon, it
1475 # allocates the viewer session's state.
1476 return _LttngLiveViewerCreateViewerSessionReply(status
)
1479 # An LTTng live TCP server.
1481 # On creation, it binds to `localhost` on the TCP port `port` if not `None`, or
1482 # on an OS-assigned TCP port otherwise. It writes the decimal TCP port number
1483 # to a temporary port file. It renames the temporary port file to
1486 # `tracing_session_descriptors` is a list of tracing session descriptors
1487 # (`LttngTracingSessionDescriptor`) to serve.
1489 # This server accepts a single viewer (client).
1491 # When the viewer closes the connection, the server's constructor
1493 class LttngLiveServer
:
1498 tracing_session_descriptors
,
1499 max_query_data_response_size
,
1501 logging
.info("Server configuration:")
1503 logging
.info(" Port file name: `{}`".format(port_filename
))
1505 if max_query_data_response_size
is not None:
1507 " Maximum response data query size: `{}`".format(
1508 max_query_data_response_size
1512 for ts_descr
in tracing_session_descriptors
:
1513 info
= ts_descr
.info
1514 fmt
= ' TS descriptor: name="{}", id={}, hostname="{}", live-timer-freq={}, client-count={}, stream-count={}:'
1518 info
.tracing_session_id
,
1520 info
.live_timer_freq
,
1526 for trace
in ts_descr
.traces
:
1527 logging
.info(' Trace: path="{}"'.format(trace
.path
))
1529 self
._ts
_descriptors
= tracing_session_descriptors
1530 self
._max
_query
_data
_response
_size
= max_query_data_response_size
1531 self
._sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
1532 self
._codec
= _LttngLiveViewerProtocolCodec()
1534 # Port 0: OS assigns an unused port
1535 serv_addr
= ("localhost", port
if port
is not None else 0)
1536 self
._sock
.bind(serv_addr
)
1537 self
._write
_port
_to
_file
(port_filename
)
1543 logging
.info("Closed connection and socket.")
1546 def _server_port(self
):
1547 return self
._sock
.getsockname()[1]
1549 def _recv_command(self
):
1553 logging
.info("Waiting for viewer command.")
1554 buf
= self
._conn
.recv(128)
1557 logging
.info("Client closed connection.")
1560 raise UnexpectedInput(
1561 "Client closed connection after having sent {} command bytes.".format(
1568 logging
.info("Received data from viewer: length={}".format(len(buf
)))
1573 cmd
= self
._codec
.decode(data
)
1574 except struct
.error
as exc
:
1575 raise UnexpectedInput("Malformed command: {}".format(exc
)) from exc
1579 "Received command from viewer: cmd-cls-name={}".format(
1580 cmd
.__class
__.__name
__
1585 def _send_reply(self
, reply
):
1586 data
= self
._codec
.encode(reply
)
1588 "Sending reply to viewer: reply-cls-name={}, length={}".format(
1589 reply
.__class
__.__name
__, len(data
)
1592 self
._conn
.sendall(data
)
1594 def _handle_connection(self
):
1595 # First command must be "connect"
1596 cmd
= self
._recv
_command
()
1598 if type(cmd
) is not _LttngLiveViewerConnectCommand
:
1599 raise UnexpectedInput(
1600 'First command is not "connect": cmd-cls-name={}'.format(
1601 cmd
.__class
__.__name
__
1605 # Create viewer session (arbitrary ID 23)
1607 "LTTng live viewer connected: version={}.{}".format(cmd
.major
, cmd
.minor
)
1609 viewer_session
= _LttngLiveViewerSession(
1610 23, self
._ts
_descriptors
, self
._max
_query
_data
_response
_size
1613 # Send "connect" reply
1615 _LttngLiveViewerConnectReply(viewer_session
.viewer_session_id
, 2, 10)
1618 # Make the viewer session handle the remaining commands
1620 cmd
= self
._recv
_command
()
1623 # Connection closed (at an expected location within the
1627 self
._send
_reply
(viewer_session
.handle_command(cmd
))
1630 logging
.info("Listening: port={}".format(self
._server
_port
))
1631 # Backlog must be present for Python version < 3.5.
1632 # 128 is an arbitrary number since we expect only 1 connection anyway.
1633 self
._sock
.listen(128)
1634 self
._conn
, viewer_addr
= self
._sock
.accept()
1636 "Accepted viewer: addr={}:{}".format(viewer_addr
[0], viewer_addr
[1])
1640 self
._handle
_connection
()
1644 def _write_port_to_file(self
, port_filename
):
1645 # Write the port number to a temporary file.
1646 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as tmp_port_file
:
1647 print(self
._server
_port
, end
="", file=tmp_port_file
)
1649 # Rename temporary file to real file
1650 os
.replace(tmp_port_file
.name
, port_filename
)
1652 'Renamed port file: src-path="{}", dst-path="{}"'.format(
1653 tmp_port_file
.name
, port_filename
1658 def _session_descriptors_from_path(sessions_filename
, trace_path_prefix
):
1663 # "name": "my-session",
1665 # "hostname": "myhost",
1666 # "live-timer-freq": 1000000,
1667 # "client-count": 23,
1673 # "path": "meow/mix",
1675 # "my_stream": [ 5235787, 728375283 ]
1677 # "metadata-sections": [
1687 with
open(sessions_filename
, "r") as sessions_file
:
1688 params
= json
.load(sessions_file
)
1692 for session
in params
:
1693 name
= session
["name"]
1694 tracing_session_id
= session
["id"]
1695 hostname
= session
["hostname"]
1696 live_timer_freq
= session
["live-timer-freq"]
1697 client_count
= session
["client-count"]
1700 for trace
in session
["traces"]:
1701 metadata_sections
= trace
.get("metadata-sections")
1702 beacons
= trace
.get("beacons")
1703 path
= trace
["path"]
1705 if not os
.path
.isabs(path
):
1706 path
= os
.path
.join(trace_path_prefix
, path
)
1708 traces
.append(LttngTrace(path
, metadata_sections
, beacons
))
1711 LttngTracingSessionDescriptor(
1724 def _loglevel_parser(string
):
1725 loglevels
= {"info": logging
.INFO
, "warning": logging
.WARNING
}
1726 if string
not in loglevels
:
1727 msg
= "{} is not a valid loglevel".format(string
)
1728 raise argparse
.ArgumentTypeError(msg
)
1729 return loglevels
[string
]
1732 if __name__
== "__main__":
1733 logging
.basicConfig(format
="# %(asctime)-25s%(message)s")
1734 parser
= argparse
.ArgumentParser(
1735 description
="LTTng-live protocol mocker", add_help
=False
1737 parser
.add_argument(
1740 choices
=["info", "warning"],
1741 help="The loglevel to be used.",
1744 loglevel_namespace
, remaining_args
= parser
.parse_known_args()
1745 logging
.getLogger().setLevel(_loglevel_parser(loglevel_namespace
.log_level
))
1747 parser
.add_argument(
1749 help="The port to bind to. If missing, use an OS-assigned port..",
1752 parser
.add_argument(
1754 help="The final port file. This file is present when the server is ready to receive connection.",
1757 parser
.add_argument(
1758 "--max-query-data-response-size",
1760 help="The maximum size of control data response in bytes",
1762 parser
.add_argument(
1763 "--trace-path-prefix",
1765 help="Prefix to prepend to the trace paths of session configurations",
1767 parser
.add_argument(
1768 "--sessions-filename",
1770 help="Path to a session configuration file",
1772 parser
.add_argument(
1776 default
=argparse
.SUPPRESS
,
1777 help="Show this help message and exit.",
1780 args
= parser
.parse_args(args
=remaining_args
)
1782 sessions
= _session_descriptors_from_path(
1783 args
.sessions_filename
,
1784 args
.trace_path_prefix
,
1787 args
.port
, args
.port_filename
, sessions
, args
.max_query_data_response_size
1789 except UnexpectedInput
as exc
:
1790 logging
.error(str(exc
))
1791 print(exc
, file=sys
.stderr
)