blob: 6a002dff80be994295c36bb0d171b2b2750496db [file] [log] [blame]
James Kuszmaul7daef362019-12-31 18:28:17 -08001// This file provides a Python module for reading logfiles. See
2// log_reader_test.py for usage.
3//
4// This reader works by having the user specify exactly what channels they want
5// data for. We then process the logfile and store all the data on that channel
6// into a list of timestamps + JSON message data. The user can then use an
7// accessor method (get_data_for_channel) to retrieve the cached data.
8
9// Defining PY_SSIZE_T_CLEAN seems to be suggested by most of the Python
10// documentation.
11#define PY_SSIZE_T_CLEAN
12// Note that Python.h needs to be included before anything else.
13#include <Python.h>
14
15#include <memory>
16
17#include "aos/configuration.h"
18#include "aos/events/logging/logger.h"
19#include "aos/events/simulated_event_loop.h"
20#include "aos/flatbuffer_merge.h"
21#include "aos/json_to_flatbuffer.h"
22
23namespace frc971 {
24namespace analysis {
25namespace {
26
27// All the data corresponding to a single message.
28struct MessageData {
29 aos::monotonic_clock::time_point monotonic_sent_time;
30 aos::realtime_clock::time_point realtime_sent_time;
31 // JSON representation of the message.
32 std::string json_data;
33};
34
35// Data corresponding to an entire channel.
36struct ChannelData {
37 std::string name;
38 std::string type;
39 // Each message published on the channel, in order by monotonic time.
40 std::vector<MessageData> messages;
41};
42
43// All the objects that we need for managing reading a logfile.
44struct LogReaderTools {
45 std::unique_ptr<aos::logger::LogReader> reader;
James Kuszmaul7daef362019-12-31 18:28:17 -080046 // Event loop to use for subscribing to buses.
47 std::unique_ptr<aos::EventLoop> event_loop;
48 std::vector<ChannelData> channel_data;
49 // Whether we have called process() on the reader yet.
50 bool processed = false;
51};
52
53struct LogReaderType {
54 PyObject_HEAD;
55 LogReaderTools *tools = nullptr;
56};
57
58void LogReader_dealloc(LogReaderType *self) {
59 LogReaderTools *tools = self->tools;
James Kuszmaul7daef362019-12-31 18:28:17 -080060 delete tools;
61 Py_TYPE(self)->tp_free((PyObject *)self);
62}
63
64PyObject *LogReader_new(PyTypeObject *type, PyObject * /*args*/,
65 PyObject * /*kwds*/) {
66 LogReaderType *self;
67 self = (LogReaderType *)type->tp_alloc(type, 0);
68 if (self != nullptr) {
69 self->tools = new LogReaderTools();
70 if (self->tools == nullptr) {
71 return nullptr;
72 }
73 }
74 return (PyObject *)self;
75}
76
77int LogReader_init(LogReaderType *self, PyObject *args, PyObject *kwds) {
78 const char *kwlist[] = {"log_file_name", nullptr};
79
80 const char *log_file_name;
81 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", const_cast<char **>(kwlist),
82 &log_file_name)) {
83 return -1;
84 }
85
86 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
87 tools->reader = std::make_unique<aos::logger::LogReader>(log_file_name);
James Kuszmaul84ff3e52020-01-03 19:48:53 -080088 tools->reader->Register();
James Kuszmaul7daef362019-12-31 18:28:17 -080089
James Kuszmaul84ff3e52020-01-03 19:48:53 -080090 tools->event_loop =
91 tools->reader->event_loop_factory()->MakeEventLoop("data_fetcher");
James Kuszmaul7daef362019-12-31 18:28:17 -080092 tools->event_loop->SkipTimingReport();
93
94 return 0;
95}
96
97PyObject *LogReader_get_data_for_channel(LogReaderType *self,
98 PyObject *args,
99 PyObject *kwds) {
100 const char *kwlist[] = {"name", "type", nullptr};
101
102 const char *name;
103 const char *type;
104 if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss",
105 const_cast<char **>(kwlist), &name, &type)) {
106 return nullptr;
107 }
108
109 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
110
111 if (!tools->processed) {
112 PyErr_SetString(PyExc_RuntimeError,
113 "Called get_data_for_bus before calling process().");
114 return nullptr;
115 }
116
117 for (const auto &channel : tools->channel_data) {
118 if (channel.name == name && channel.type == type) {
119 PyObject *list = PyList_New(channel.messages.size());
120 for (size_t ii = 0; ii < channel.messages.size(); ++ii)
121 {
122 const auto &message = channel.messages[ii];
123 PyObject *monotonic_time = PyLong_FromLongLong(
124 std::chrono::duration_cast<std::chrono::nanoseconds>(
125 message.monotonic_sent_time.time_since_epoch())
126 .count());
127 PyObject *realtime_time = PyLong_FromLongLong(
128 std::chrono::duration_cast<std::chrono::nanoseconds>(
129 message.realtime_sent_time.time_since_epoch())
130 .count());
131 PyObject *json_data = PyUnicode_FromStringAndSize(
132 message.json_data.data(), message.json_data.size());
133 PyObject *entry =
134 PyTuple_Pack(3, monotonic_time, realtime_time, json_data);
135 if (PyList_SetItem(list, ii, entry) != 0) {
136 return nullptr;
137 }
138 }
139 return list;
140 }
141 }
142 PyErr_SetString(PyExc_ValueError,
143 "The provided channel was never subscribed to.");
144 return nullptr;
145}
146
147PyObject *LogReader_subscribe(LogReaderType *self, PyObject *args,
148 PyObject *kwds) {
149 const char *kwlist[] = {"name", "type", nullptr};
150
151 const char *name;
152 const char *type;
153 if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss",
154 const_cast<char **>(kwlist), &name, &type)) {
155 return nullptr;
156 }
157
158 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
159
160 if (tools->processed) {
161 PyErr_SetString(PyExc_RuntimeError,
162 "Called subscribe after calling process().");
163 return nullptr;
164 }
165
166 const aos::Channel *const channel = aos::configuration::GetChannel(
167 tools->reader->configuration(), name, type, "", nullptr);
168 if (channel == nullptr) {
169 return Py_False;
170 }
171 const int index = tools->channel_data.size();
172 tools->channel_data.push_back(
173 {.name = name, .type = type, .messages = {}});
174 tools->event_loop->MakeRawWatcher(
175 channel, [channel, index, tools](const aos::Context &context,
176 const void *message) {
177 tools->channel_data[index].messages.push_back(
178 {.monotonic_sent_time = context.monotonic_event_time,
179 .realtime_sent_time = context.realtime_event_time,
180 .json_data = aos::FlatbufferToJson(
181 channel->schema(), static_cast<const uint8_t *>(message))});
182 });
183 return Py_True;
184}
185
186static PyObject *LogReader_process(LogReaderType *self,
187 PyObject *Py_UNUSED(ignored)) {
188 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
189
190 if (tools->processed) {
191 PyErr_SetString(PyExc_RuntimeError, "process() may only be called once.");
192 return nullptr;
193 }
194
195 tools->processed = true;
196
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800197 tools->reader->event_loop_factory()->Run();
James Kuszmaul7daef362019-12-31 18:28:17 -0800198
199 Py_RETURN_NONE;
200}
201
202static PyObject *LogReader_configuration(LogReaderType *self,
203 PyObject *Py_UNUSED(ignored)) {
204 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
205
206 // I have no clue if the Configuration that we get from the log reader is in a
207 // contiguous chunk of memory, and I'm too lazy to either figure it out or
208 // figure out how to extract the actual data buffer + offset.
209 // Instead, copy the flatbuffer and return a copy of the new buffer.
210 aos::FlatbufferDetachedBuffer<aos::Configuration> buffer =
211 aos::CopyFlatBuffer(tools->reader->configuration());
212
213 return PyBytes_FromStringAndSize(
214 reinterpret_cast<const char *>(buffer.data()), buffer.size());
215}
216
217static PyMethodDef LogReader_methods[] = {
218 {"configuration", (PyCFunction)LogReader_configuration, METH_NOARGS,
219 "Return a bytes buffer for the Configuration of the logfile."},
220 {"process", (PyCFunction)LogReader_process, METH_NOARGS,
221 "Processes the logfile and all the subscribed to channels."},
222 {"subscribe", (PyCFunction)LogReader_subscribe,
223 METH_VARARGS | METH_KEYWORDS,
224 "Attempts to subscribe to the provided channel name + type. Returns True "
225 "if successful."},
226 {"get_data_for_channel", (PyCFunction)LogReader_get_data_for_channel,
227 METH_VARARGS | METH_KEYWORDS,
228 "Returns the logged data for a given channel. Raises an exception if you "
229 "did not subscribe to the provided channel. Returned data is a list of "
230 "tuples where each tuple is of the form (monotonic_nsec, realtime_nsec, "
231 "json_message_data)."},
232 {nullptr, 0, 0, nullptr} /* Sentinel */
233};
234
235static PyTypeObject LogReaderType = {
236 PyVarObject_HEAD_INIT(NULL, 0).tp_name = "py_log_reader.LogReader",
237 .tp_doc = "LogReader objects",
238 .tp_basicsize = sizeof(LogReaderType),
239 .tp_itemsize = 0,
240 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
241 .tp_new = LogReader_new,
242 .tp_init = (initproc)LogReader_init,
243 .tp_dealloc = (destructor)LogReader_dealloc,
244 .tp_methods = LogReader_methods,
245};
246
247static PyModuleDef log_reader_module = {
248 PyModuleDef_HEAD_INIT,
249 .m_name = "py_log_reader",
250 .m_doc = "Example module that creates an extension type.",
251 .m_size = -1,
252};
253
254PyObject *InitModule() {
255 PyObject *m;
256 if (PyType_Ready(&LogReaderType) < 0) return nullptr;
257
258 m = PyModule_Create(&log_reader_module);
259 if (m == nullptr) return nullptr;
260
261 Py_INCREF(&LogReaderType);
262 if (PyModule_AddObject(m, "LogReader", (PyObject *)&LogReaderType) < 0) {
263 Py_DECREF(&LogReaderType);
264 Py_DECREF(m);
265 return nullptr;
266 }
267
268 return m;
269}
270
271} // namespace
272} // namespace analysis
273} // namespace frc971
274
275PyMODINIT_FUNC PyInit_py_log_reader(void) {
276 return frc971::analysis::InitModule();
277}