Chronoscope 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,56 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+
6
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
7
+
8
+ This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
9
+
10
+ 0. Additional Definitions.
11
+ As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
12
+
13
+ “The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
14
+
15
+ An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
16
+
17
+ A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
18
+
19
+ The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
20
+
21
+ The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
22
+
23
+ 1. Exception to Section 3 of the GNU GPL.
24
+ You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
25
+
26
+ 2. Conveying Modified Versions.
27
+ If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
28
+
29
+ a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
30
+ b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
31
+ 3. Object Code Incorporating Material from Library Header Files.
32
+ The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
33
+
34
+ a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
35
+ b) Accompany the object code with a copy of the GNU GPL and this license document.
36
+ 4. Combined Works.
37
+ You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
38
+
39
+ a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
40
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
41
+ c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
42
+ d) Do one of the following:
43
+ 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
44
+ 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
45
+ e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
46
+ 5. Combined Libraries.
47
+ You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
48
+
49
+ a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
50
+ b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
51
+ 6. Revised Versions of the GNU Lesser General Public License.
52
+ The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
53
+
54
+ Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
55
+
56
+ If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.1
2
+ Name: Chronoscope
3
+ Version: 0.0.1
4
+ Summary: A cross-platform matplotlib-based observability tool
5
+ Home-page: https://github.com/just-now/chronoscope
6
+ Author: Anatoliy Bilenko
7
+ Author-email: anatoliy.bilenko@gmail.com
8
+ License: LGPLv3
9
+ Keywords: cli observability
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: System :: Monitoring
20
+ Requires-Python: >=3.10
21
+ License-File: COPYING
22
+ Requires-Dist: peewee
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: PyYAML
25
+ Requires-Dist: graphviz
26
+ Requires-Dist: packaging
27
+
28
+ A cross-platform matplotlib-based observability tool
@@ -0,0 +1,17 @@
1
+ COPYING
2
+ README.md
3
+ setup.cfg
4
+ setup.py
5
+ Chronoscope.egg-info/PKG-INFO
6
+ Chronoscope.egg-info/SOURCES.txt
7
+ Chronoscope.egg-info/dependency_links.txt
8
+ Chronoscope.egg-info/entry_points.txt
9
+ Chronoscope.egg-info/requires.txt
10
+ Chronoscope.egg-info/top_level.txt
11
+ chronoscope/__init__.py
12
+ chronoscope/__main__.py
13
+ chronoscope/chart.py
14
+ chronoscope/db.py
15
+ chronoscope/parser.py
16
+ chronoscope/tree.py
17
+ chronoscope/utils.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ chronoscope = chronoscope:main
@@ -0,0 +1,5 @@
1
+ peewee
2
+ matplotlib
3
+ PyYAML
4
+ graphviz
5
+ packaging
@@ -0,0 +1 @@
1
+ chronoscope
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.1
2
+ Name: Chronoscope
3
+ Version: 0.0.1
4
+ Summary: A cross-platform matplotlib-based observability tool
5
+ Home-page: https://github.com/just-now/chronoscope
6
+ Author: Anatoliy Bilenko
7
+ Author-email: anatoliy.bilenko@gmail.com
8
+ License: LGPLv3
9
+ Keywords: cli observability
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: System :: Monitoring
20
+ Requires-Python: >=3.10
21
+ License-File: COPYING
22
+ Requires-Dist: peewee
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: PyYAML
25
+ Requires-Dist: graphviz
26
+ Requires-Dist: packaging
27
+
28
+ A cross-platform matplotlib-based observability tool
@@ -0,0 +1,106 @@
1
+ ![pytest/systest workflow](https://github.com/just-now/chronoscope/actions/workflows/python-package.yml/badge.svg)
2
+ ![systest workflow](https://github.com/just-now/chronoscope/actions/workflows/makefile.yml/badge.svg)
3
+
4
+ # chronoscope
5
+ Chronoscope, a cross-platform matplotlib-based observability tool
6
+
7
+ ## Chart
8
+ ![alt text](https://github.com/just-now/chronoscope/blob/master/img/chart1.png)
9
+
10
+ ## Definitions
11
+
12
+ ```math
13
+ \mathcal{S} \subset \mathbb{N}.
14
+ ```
15
+
16
+ ```math
17
+ \mathcal{T} = \left\langle \mathbb{T},\prec \right\rangle.
18
+ ```
19
+
20
+ ```math
21
+ \mathcal{A}:\mathcal{S}\times\Sigma^{c}\times\Sigma^{c}.
22
+ ```
23
+
24
+ ```math
25
+ \mathcal{K}:\mathcal{S}\times\mathcal{S}\times\Sigma^{c}.
26
+ ```
27
+
28
+ ```math
29
+ \mathcal{R}:\mathcal{S}\times\mathcal{S}.
30
+ ```
31
+
32
+ ```math
33
+ relation \triangleq \left\langle origin: \mathcal{S}, dest: \mathcal{S} \right\rangle.
34
+ ```
35
+
36
+ ```math
37
+ tick \triangleq \left\langle sm: \mathcal{S}, time: \mathcal{T}, event: \Sigma^{c} \right\rangle.
38
+ ```
39
+
40
+ ```math
41
+ attr \triangleq \left\langle sm: \mathcal{S}, key: \Sigma^{c}, val: \Sigma^{c} \right\rangle.
42
+ ```
43
+
44
+ ## Notes
45
+
46
+ ### Note 0.0
47
+ ```math
48
+ iter_1: \mathcal{S} \to \left\{ \mathcal{S^{1}}, ... \mathcal{S^{p}} \right\},
49
+ ```
50
+
51
+ ```math
52
+ iter_1(sm) = \left\{ dest(related\_sm) | related\_sm \in \left\{ rel \in \mathcal{R} | origin(rel) = sm \right\} \right\},
53
+ ```
54
+
55
+ ```math
56
+ p = \left| iter_1(sm) \right|.
57
+ ```
58
+
59
+ ### Note 0.1
60
+ ```math
61
+ height: \mathcal{S} \to \mathbb{N},
62
+ ```
63
+
64
+ ```math
65
+ height(sm_i) = 1 + max(\left\{ height(sm_i) | sm_i \in iter_1(sm_i) \right\}),
66
+ ```
67
+
68
+ ```math
69
+ max(\varnothing) = 0.
70
+ ```
71
+
72
+ ### Note 0.2
73
+
74
+ ```math
75
+ iter: \mathcal{S} \to \left\{ \mathcal{S^{1}}, ... \mathcal{S^{r}} \right\},
76
+ ```
77
+
78
+ ```math
79
+ iter(sm_i) = \left\{ sm_i \right\} \cup \bigcup_{i=1}^{height(sm_i)-1}\left( \left\{ iter_1(sm_{i+1}) | iter_1(sm_{i+1}) \in iter_1(sm_i)\right\} \right),
80
+ ```
81
+
82
+ ```math
83
+ r = \sum_{i=0}^{height(sm_i)}\left| iter_1(sm_i) \right|.
84
+ ```
85
+
86
+ ### Note 1
87
+ ```math
88
+ timeline: \mathcal{S} \to \left\{ \mathcal{K^{1}}, ... \mathcal{K^{q}} \right\},
89
+ ```
90
+
91
+ ```math
92
+ timeline(sm_i) = \left\{ tick \in \mathcal{K} | sm(tick)=sm_i \right\},
93
+ ```
94
+
95
+ ```math
96
+ q=\left| timeline(sm_i) \right|.
97
+ ```
98
+
99
+ ### Note 2
100
+ ```math
101
+ chart: \mathcal{S} \to \left\{ \left\{ \mathcal{K^{1}}, ... \mathcal{K^{q}} \right\}^{1}, ... \left\{ \mathcal{K^{1}}, ... \mathcal{K^{q}} \right\}^{r} \right\}
102
+ ```
103
+
104
+ ```math
105
+ chart(sm_i) = \left\{ timeline(sm) | sm \in iter(sm_i) \right\},
106
+ ```
@@ -0,0 +1,61 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ from chronoscope import db
11
+ from chronoscope import parser
12
+ import chronoscope.tree as tree
13
+ import chronoscope.chart as chart
14
+ import argparse
15
+ import sys
16
+
17
+ __version__ = '0.0.1'
18
+ __author__ = 'Anatoliy Bilenko <anatoliy.bilenko@gmail.com>'
19
+ __license__ = 'LGPLv3'
20
+
21
+ db_options: dict[str, int | str] = {
22
+ "cache_size": -128 << 20,
23
+ "synchronous": "off",
24
+ "journal_mode": "off",
25
+ }
26
+
27
+ def parse_args():
28
+ parser = argparse.ArgumentParser(prog=sys.argv[0], description="""
29
+ chronoscope: Plots drill-down chart based on user's traces""")
30
+ parser.add_argument("-d", "--db", type=str, default="chronoscope.db",
31
+ help="chronoscope database")
32
+ parser.add_argument("-c", "--conf", type=str, default="chronoscope.yaml",
33
+ help="configuration, defines how to parse out users'\n"
34
+ "ticks, attrs and relations from the traces")
35
+ parser.add_argument("-t", "--trace", type=str, help="User's traces")
36
+ parser.add_argument("-D", "--depth", type=int, default=50,
37
+ help="limits output to given level of ticks")
38
+ parser.add_argument("command", type=str, choices=["create", "plot"],
39
+ help="create: build chronoscope database\n"
40
+ "plot: plots drill-down chart for the given tick")
41
+ parser.add_argument("-f", "--fig_size", nargs=2, type=int, default=[16, 4])
42
+ parser.add_argument("-k", "--tick_id", type=int,
43
+ help="tick identifier to plot")
44
+ return parser.parse_args()
45
+
46
+
47
+ def main() -> int:
48
+ args = parse_args()
49
+
50
+ if args.command == "create":
51
+ db.open(args.db, db_options, create=True)
52
+ db.load(parser.parser(args.conf), args.trace)
53
+ db.mkidx()
54
+ db.close()
55
+
56
+ if args.command == "plot":
57
+ db.open(args.db, db_options)
58
+ chart.plot(args.tick_id, args.fig_size, args.depth)
59
+ tree.plot(args.tick_id, args.depth)
60
+
61
+ return 0
@@ -0,0 +1,14 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ import chronoscope
11
+ import sys
12
+
13
+ if __name__ == "__main__":
14
+ sys.exit(chronoscope.main())
@@ -0,0 +1,127 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ import chronoscope.db as db
11
+ import chronoscope.utils as utils
12
+ import matplotlib.cm as cm # type: ignore
13
+ import matplotlib.pyplot as pt # type: ignore
14
+ import matplotlib.ticker as ticker # type: ignore
15
+ from dataclasses import dataclass
16
+ import sys
17
+
18
+
19
+ Y_LINE_SPACING = 2
20
+ X_TICKS_MAX = 5
21
+
22
+ def plot_timeline(timeline, y_pos: int):
23
+ y_pos_scaled = -Y_LINE_SPACING * y_pos
24
+ colors = cm.get_cmap("tab10").colors # type: ignore[attr-defined]
25
+
26
+ for current, current_tick in enumerate(timeline[:-1]):
27
+ next_tick = timeline[current + 1]
28
+ start_time, end_time = current_tick["time"], next_tick["time"]
29
+ event_label = current_tick["event"]
30
+
31
+ pt.hlines(y_pos_scaled, start_time, end_time, lw=4,
32
+ colors=colors[current % len(colors)])
33
+ pt.text(start_time, y_pos_scaled, event_label, rotation=90)
34
+
35
+ pt.text(timeline[-1]["time"], y_pos_scaled,
36
+ timeline[-1]["event"], rotation=90)
37
+
38
+ @dataclass
39
+ class timeline_visitor:
40
+ y_labels: list
41
+ y_pos: int
42
+ x_min: int
43
+ x_max: int
44
+
45
+ def __call__(self, timeline: list[dict], origin: int, parent: None | int):
46
+ plot_timeline(timeline, self.y_pos)
47
+ self.y_pos += 1
48
+ duration = round((timeline[-1]["time"] - timeline[0]["time"]) / 1e6, 3)
49
+ type, id = timeline[0]["type"], timeline[0]["id"]
50
+ self.y_labels.append(f"{type}{utils.unpack(id)} [{duration}ms]")
51
+
52
+ times = [tick["time"] for tick in timeline]
53
+ self.x_min = min(self.x_min, min(times))
54
+ self.x_max = max(self.x_max, max(times))
55
+
56
+ class chart_annotation:
57
+ def __init__(self, fig):
58
+ self.cur_mark = ord('A')
59
+ self.cur = []
60
+ self.ann = []
61
+ self.ann_mode = False
62
+ fig.canvas.mpl_connect("key_press_event", self.on_key)
63
+ fig.canvas.mpl_connect("button_press_event", self.on_click)
64
+
65
+ def on_key(self, event):
66
+ if event.key == "escape":
67
+ sys.exit(1)
68
+ elif event.key == "e":
69
+ self.ann_mode = not self.ann_mode
70
+ elif event.key == "d":
71
+ if self.ann:
72
+ self.cur_mark -= 1
73
+ self.cur.pop()
74
+ self.ann.pop().remove()
75
+ self.ann.pop().remove()
76
+ event.canvas.draw()
77
+
78
+ def on_click(self, event):
79
+ if not self.ann_mode:
80
+ return
81
+
82
+ x, ax = event.xdata, event.inaxes
83
+ # TODO: Don't ask me what's going on with cursors... I don't know!
84
+ self.cur.append(x)
85
+ cursor = chr(self.cur_mark)
86
+ if self.cur_mark % 2 == 0:
87
+ cursor = chr(self.cur_mark - 1) + cursor + ": "
88
+ cursor += utils.str_ns_diff(int(abs(self.cur[-1] - self.cur[-2])))
89
+ self.cur_mark += 1
90
+
91
+ self.ann.append(ax.axvline(x=x, color="lightgray"))
92
+ self.ann.append(ax.annotate(cursor, xycoords=("data", "axes fraction"),
93
+ xy=(x, 0)))
94
+ self.ann_mode = not self.ann_mode
95
+ event.canvas.draw()
96
+
97
+ def plot(origin: int, figsize=(16, 4), depth_max=50):
98
+ fig = pt.figure(figsize=figsize)
99
+ pt.style.use("bmh")
100
+ pt.rcParams["font.size"] = 8
101
+ pt.subplots_adjust(top=0.75)
102
+
103
+ v = timeline_visitor([], 0, utils.MAX_INT, utils.MIN_INT)
104
+ db.iterate(origin, None, db.tick, v, 0, depth_max)
105
+
106
+ end = -Y_LINE_SPACING * v.y_pos
107
+ y_range = [float(x) for x in range(0, end, -Y_LINE_SPACING)]
108
+ x_range = range(v.x_min, v.x_max, round((v.x_max - v.x_min) / X_TICKS_MAX))
109
+
110
+ # (1)
111
+ # x_labels = [utils.str_ns(x, compact=True) for x in x_range]
112
+ # pt.xticks(x_range, x_labels)
113
+ # (2) This might be slow, consider to uncomment (1) in such cases.
114
+ pt.gca().xaxis.set_major_formatter(ticker.FuncFormatter(
115
+ lambda value, pos: utils.str_ns(value, compact=True)))
116
+
117
+ pt.yticks(y_range, v.y_labels)
118
+ pt.xlabel("Time")
119
+ pt.autoscale(enable=True, axis="x", tight=True)
120
+ pt.margins(0.1)
121
+ _ = chart_annotation(fig)
122
+
123
+ pt.grid(True)
124
+ title = f"Request {utils.unpack(origin)}\n"
125
+ title += f"[{utils.str_ns(x_range[0])}...{utils.str_ns(x_range[-1])}]"
126
+ pt.suptitle(title)
127
+ pt.show()
@@ -0,0 +1,93 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ import chronoscope.parser as pr
11
+ from typing import Callable
12
+ import subprocess as sp
13
+ import builtins as b
14
+ import peewee as p
15
+ import os
16
+
17
+ db = p.SqliteDatabase(None)
18
+
19
+ class T(p.Model):
20
+ class Meta:
21
+ database = db
22
+ primary_key = False
23
+
24
+ class tick(T):
25
+ id = p.IntegerField()
26
+ time = p.IntegerField()
27
+ event = p.TextField()
28
+ type = p.TextField()
29
+
30
+ class attr(T):
31
+ id = p.IntegerField()
32
+ name = p.TextField()
33
+ val = p.TextField()
34
+
35
+ class relation(T):
36
+ orig = p.IntegerField()
37
+ dest = p.IntegerField()
38
+ type = p.TextField()
39
+
40
+
41
+ TABLES = [tick, attr, relation]
42
+
43
+ def open(path: str, opts: None | dict[str, int | str] = None, create=False):
44
+ if create and os.path.exists(path):
45
+ raise FileExistsError("`{path}' exists!")
46
+ if not create and not os.path.exists(path):
47
+ raise FileNotFoundError("`{path}' not found!")
48
+
49
+ db.init(path, opts)
50
+ db.connect()
51
+ if create:
52
+ with db:
53
+ db.create_tables(TABLES)
54
+
55
+ def close():
56
+ db.close()
57
+
58
+ def mkidx():
59
+ db.execute_sql("CREATE INDEX tick_idx on tick(id);")
60
+ db.execute_sql("CREATE INDEX relation_idx on relation(orig);")
61
+ db.execute_sql("CREATE INDEX attr_idx on attr(id);")
62
+
63
+ def line_nr(file: str) -> int:
64
+ result = sp.run(['wc', file], stdout=sp.PIPE, text=True)
65
+ return int(result.stdout.split()[0])
66
+
67
+ def load(pr: pr.parser, trace_path: str, fd_chunk_size=100, db_chunk_size=10):
68
+ if not os.path.exists(trace_path):
69
+ raise FileNotFoundError("`{trace_path}' not found!")
70
+
71
+ with b.open(trace_path) as fd:
72
+ for fd_chunk in p.chunked(fd, fd_chunk_size):
73
+ records = pr.parse(fd_chunk)
74
+ with db.atomic():
75
+ for table in TABLES:
76
+ t_name: str = table._meta.name # type: ignore
77
+ for db_chunk in p.chunked(records[t_name], db_chunk_size):
78
+ table.insert_many(db_chunk).execute()
79
+
80
+ def iterate(origin: int, parent: None | int, samples: type[tick] | type[attr],
81
+ visit: Callable, depth: int, depth_max: int):
82
+ if depth_max < depth:
83
+ return
84
+
85
+ # pull origin
86
+ if timeline := samples.select().where((samples.id == origin)):
87
+ visit(timeline.dicts(), origin, parent)
88
+
89
+ # pull children
90
+ orig_to_children = relation.select().where((relation.orig == origin))
91
+ for child in orig_to_children.dicts():
92
+ print(f"@[{depth}] {hex(child['orig'])} ... {hex(child['dest'])} ...")
93
+ iterate(child["dest"], origin, samples, visit, depth + 1, depth_max)
@@ -0,0 +1,84 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ import chronoscope.utils as u
11
+ from typing import Callable
12
+ import yaml
13
+
14
+ class parser:
15
+ def __init__(self, conf_path: str):
16
+ # type -> (dest_table, parser_func)
17
+ self.parsers: dict[str, tuple[str, Callable]] = {}
18
+ # the parser knows about table names
19
+ self.tables = ["tick", "attr", "relation"]
20
+ self.load_config(conf_path)
21
+
22
+ def load_config(self, conf_path: str):
23
+ with open(conf_path) as fd:
24
+ conf = yaml.safe_load(fd)
25
+ conf_tables = [t for t in conf.keys() if t[0] != '.']
26
+ if not all(t in self.tables for t in conf_tables):
27
+ raise SyntaxError(f"a few of {conf_tables} aren't known!")
28
+
29
+ for table in conf_tables:
30
+ for trace in conf[table]:
31
+ self.register_parser(table, trace["type"],
32
+ self.make_parser(table, trace["pos"]))
33
+
34
+ def make_parser(self, table: str, kwargs: dict[str, int]) -> Callable:
35
+ match table:
36
+ case "tick":
37
+ return self.make_req_parser(**kwargs)
38
+ case "relation":
39
+ return self.make_rel_parser(**kwargs)
40
+ case "attr":
41
+ return self.make_attr_parser(**kwargs)
42
+ raise NotImplementedError()
43
+
44
+ def make_req_parser(self, type: int, time: int, event: int,
45
+ pid: int, id: int) -> Callable:
46
+ def parse(line: list[str], parse_type: str):
47
+ return {
48
+ "time": u.ns(line[time]),
49
+ "type": line[type], "event": line[event],
50
+ "id": u.pack(int(line[id]), int(line[pid]))
51
+ } if parse_type == line[type] else None
52
+ return parse
53
+
54
+ def make_rel_parser(self, orig_id: int, dest_id: int,
55
+ orig_pid: int, dest_pid: int, type: int) -> Callable:
56
+ def parse(line: list[str], parse_type: str):
57
+ return {
58
+ "orig": u.pack(int(line[orig_id]), int(line[orig_pid])),
59
+ "dest": u.pack(int(line[dest_id]), int(line[orig_pid])),
60
+ "type": line[type]
61
+ } if parse_type == line[type] else None
62
+ return parse
63
+
64
+ def make_attr_parser(self, id: int, pid: int,
65
+ name: int, value: int, type: int) -> Callable:
66
+ def parse(line: list[str], parse_type: str):
67
+ return {
68
+ "id": u.pack(int(line[id]), int(line[pid])),
69
+ "val": line[value],
70
+ "name": line[name],
71
+ } if parse_type == line[type] else None
72
+ return parse
73
+
74
+ def register_parser(self, dest_table: str, type: str, parse: Callable):
75
+ self.parsers[type] = (dest_table, parse)
76
+
77
+ def parse(self,
78
+ fd_chunk: list[str]) -> dict[str, list[dict[str, str | int]]]:
79
+ records: dict[str, list] = {t: [] for t in self.tables}
80
+ for line in fd_chunk:
81
+ for p_name, (dest_table, parser) in self.parsers.items():
82
+ if record := parser(line.split(), p_name):
83
+ records[dest_table].append(record)
84
+ return records
@@ -0,0 +1,35 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ import chronoscope.db as db
11
+ import chronoscope.utils as utils
12
+ from graphviz import Graph # type: ignore
13
+
14
+ # https://graphviz.readthedocs.io/en/stable/examples.html#structs-py
15
+ FMT_NODE = """<
16
+ <table border="0" cellborder="1" cellspacing="0">
17
+ <tr><td>{}</td></tr><tr><td>{}</td></tr></table>>
18
+ """
19
+
20
+ class attr_visitor:
21
+ def __init__(self, graph: Graph):
22
+ self.graph = graph
23
+
24
+ def __call__(self, node_attrs: list[dict], current: int, parent: None | int):
25
+ contents = "<br/>".join([f"{na['name']}={na['val']}" for na in node_attrs])
26
+ self.graph.node(str(current), FMT_NODE.format(utils.unpack(current), contents))
27
+
28
+ if parent:
29
+ self.graph.edge(str(parent), str(current))
30
+
31
+ def plot(origin: int, depth_max=50):
32
+ g = Graph(strict=True, format="png", node_attr={"shape": "plaintext"})
33
+ db.iterate(origin, None, db.attr, attr_visitor(g), 0, depth_max)
34
+ pid, id = utils.unpack(origin)
35
+ g.render(f"tree_{pid}_{id}", cleanup=True)
@@ -0,0 +1,51 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # This file is part of Chronoscope.
4
+ #
5
+ # SPDX-FileCopyrightText: 2024 Anatoliy Bilenko <anatoliy.bilenko@gmail.com>
6
+ #
7
+ # SPDX-License-Identifier: LGPL-3.0-only
8
+ #
9
+
10
+ from datetime import datetime as t
11
+ import sys
12
+
13
+ NS_TIME_LEN = len("2055-11-29T20:57:56.489282133")
14
+ FMT_MS = "%Y-%m-%dT%H:%M:%S.%f"
15
+ FMT_MS_COMPACT = ":%S.%f"
16
+ MAX_INT = sys.maxsize
17
+ MIN_INT = -sys.maxsize - 1
18
+ BITS_PER_PID = 8
19
+ DB_INT_SIZE = 64
20
+
21
+
22
+ def pack_unpack_init(p_bits_per_pid: int, p_db_int_size: int):
23
+ global BITS_PER_PID, DB_INT_SIZE
24
+ BITS_PER_PID = p_bits_per_pid
25
+ DB_INT_SIZE = p_db_int_size
26
+
27
+ def pack(id: int, pid: int) -> int:
28
+ masked_pid = ((1 << BITS_PER_PID) - 1) & pid
29
+ packed_pid = masked_pid << (DB_INT_SIZE - BITS_PER_PID)
30
+ packed_id = ((1 << (DB_INT_SIZE - BITS_PER_PID)) - 1) & id
31
+ return (packed_pid | packed_id)
32
+
33
+ def unpack(id_pid: int) -> tuple[int, int]:
34
+ pid = id_pid >> (DB_INT_SIZE - BITS_PER_PID)
35
+ id = ((1 << (DB_INT_SIZE - BITS_PER_PID)) - 1) & id_pid
36
+ return pid, id
37
+
38
+ def ns(time: str) -> int:
39
+ if len(time) != NS_TIME_LEN:
40
+ raise ValueError("Not a nanosecond time format")
41
+ ms = int(t.strptime(time[:-3], FMT_MS).timestamp() * 1e6)
42
+ return ms * 1_000 + int(time[-3:])
43
+
44
+ def str_ns(unix_time_ns: int, compact=False) -> str:
45
+ dt = t.utcfromtimestamp(unix_time_ns / 1e9)
46
+ if compact:
47
+ return dt.strftime(FMT_MS_COMPACT)
48
+ return dt.strftime(FMT_MS)
49
+
50
+ def str_ns_diff(unix_time_ns: int) -> str:
51
+ return str(unix_time_ns) + "ns"
@@ -0,0 +1,10 @@
1
+ [pydocstyle]
2
+ ignore = D100,D101,D102,D103,D104,D106,D107
3
+
4
+ [flake8]
5
+ ignore = E302
6
+
7
+ [egg_info]
8
+ tag_build =
9
+ tag_date = 0
10
+
@@ -0,0 +1,58 @@
1
+ import os
2
+ import re
3
+ import sys
4
+ from io import open
5
+ from setuptools import setup
6
+
7
+
8
+ if sys.version_info < (3, 10):
9
+ print('Chronoscope requires at least Python 3.10 to run.')
10
+ sys.exit(1)
11
+
12
+ with open(os.path.join('chronoscope', '__init__.py'), encoding='utf-8') as f:
13
+ rexp = r"^__version__ = ['\"]([^'\"]*)['\"]"
14
+ version = re.search(rexp, f.read(), re.M).group(1) # type: ignore
15
+
16
+
17
+ if not version:
18
+ raise RuntimeError('Cannot find Chronoscope version information.')
19
+
20
+ def install_requires():
21
+ requires = [
22
+ 'peewee',
23
+ 'matplotlib',
24
+ 'PyYAML',
25
+ 'graphviz',
26
+ 'packaging',
27
+ ]
28
+
29
+ return requires
30
+
31
+
32
+ setup(
33
+ name='Chronoscope',
34
+ version=version,
35
+ description="A cross-platform matplotlib-based observability tool",
36
+ long_description="A cross-platform matplotlib-based observability tool",
37
+ author='Anatoliy Bilenko',
38
+ author_email='anatoliy.bilenko@gmail.com',
39
+ url='https://github.com/just-now/chronoscope',
40
+ license='LGPLv3',
41
+ keywords="cli observability",
42
+ python_requires=">=3.10",
43
+ install_requires=install_requires(),
44
+ packages=['chronoscope'],
45
+ entry_points={"console_scripts": ["chronoscope=chronoscope:main"]},
46
+ classifiers=[
47
+ 'Development Status :: 3 - Alpha',
48
+ 'Environment :: Console',
49
+ 'Intended Audience :: Developers',
50
+ 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
51
+ 'Operating System :: OS Independent',
52
+ 'Programming Language :: Python :: 3',
53
+ 'Programming Language :: Python :: 3.10',
54
+ 'Programming Language :: Python :: 3.11',
55
+ 'Programming Language :: Python :: 3.12',
56
+ 'Topic :: System :: Monitoring'
57
+ ]
58
+ )