blob: a9a1db11f1de36b3b4d62fdb270ba1a91ae4f3ef [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();
Tyler Chatow67ddb032020-01-12 14:30:04 -080093 tools->event_loop->SkipAosLog();
James Kuszmaul7daef362019-12-31 18:28:17 -080094
95 return 0;
96}
97
98PyObject *LogReader_get_data_for_channel(LogReaderType *self,
99 PyObject *args,
100 PyObject *kwds) {
101 const char *kwlist[] = {"name", "type", nullptr};
102
103 const char *name;
104 const char *type;
105 if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss",
106 const_cast<char **>(kwlist), &name, &type)) {
107 return nullptr;
108 }
109
110 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
111
112 if (!tools->processed) {
113 PyErr_SetString(PyExc_RuntimeError,
114 "Called get_data_for_bus before calling process().");
115 return nullptr;
116 }
117
118 for (const auto &channel : tools->channel_data) {
119 if (channel.name == name && channel.type == type) {
120 PyObject *list = PyList_New(channel.messages.size());
121 for (size_t ii = 0; ii < channel.messages.size(); ++ii)
122 {
123 const auto &message = channel.messages[ii];
124 PyObject *monotonic_time = PyLong_FromLongLong(
125 std::chrono::duration_cast<std::chrono::nanoseconds>(
126 message.monotonic_sent_time.time_since_epoch())
127 .count());
128 PyObject *realtime_time = PyLong_FromLongLong(
129 std::chrono::duration_cast<std::chrono::nanoseconds>(
130 message.realtime_sent_time.time_since_epoch())
131 .count());
132 PyObject *json_data = PyUnicode_FromStringAndSize(
133 message.json_data.data(), message.json_data.size());
134 PyObject *entry =
135 PyTuple_Pack(3, monotonic_time, realtime_time, json_data);
136 if (PyList_SetItem(list, ii, entry) != 0) {
137 return nullptr;
138 }
139 }
140 return list;
141 }
142 }
143 PyErr_SetString(PyExc_ValueError,
144 "The provided channel was never subscribed to.");
145 return nullptr;
146}
147
148PyObject *LogReader_subscribe(LogReaderType *self, PyObject *args,
149 PyObject *kwds) {
150 const char *kwlist[] = {"name", "type", nullptr};
151
152 const char *name;
153 const char *type;
154 if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss",
155 const_cast<char **>(kwlist), &name, &type)) {
156 return nullptr;
157 }
158
159 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
160
161 if (tools->processed) {
162 PyErr_SetString(PyExc_RuntimeError,
163 "Called subscribe after calling process().");
164 return nullptr;
165 }
166
167 const aos::Channel *const channel = aos::configuration::GetChannel(
168 tools->reader->configuration(), name, type, "", nullptr);
169 if (channel == nullptr) {
170 return Py_False;
171 }
172 const int index = tools->channel_data.size();
173 tools->channel_data.push_back(
174 {.name = name, .type = type, .messages = {}});
175 tools->event_loop->MakeRawWatcher(
176 channel, [channel, index, tools](const aos::Context &context,
177 const void *message) {
178 tools->channel_data[index].messages.push_back(
179 {.monotonic_sent_time = context.monotonic_event_time,
180 .realtime_sent_time = context.realtime_event_time,
181 .json_data = aos::FlatbufferToJson(
182 channel->schema(), static_cast<const uint8_t *>(message))});
183 });
184 return Py_True;
185}
186
187static PyObject *LogReader_process(LogReaderType *self,
188 PyObject *Py_UNUSED(ignored)) {
189 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
190
191 if (tools->processed) {
192 PyErr_SetString(PyExc_RuntimeError, "process() may only be called once.");
193 return nullptr;
194 }
195
196 tools->processed = true;
197
James Kuszmaul84ff3e52020-01-03 19:48:53 -0800198 tools->reader->event_loop_factory()->Run();
James Kuszmaul7daef362019-12-31 18:28:17 -0800199
200 Py_RETURN_NONE;
201}
202
203static PyObject *LogReader_configuration(LogReaderType *self,
204 PyObject *Py_UNUSED(ignored)) {
205 LogReaderTools *tools = CHECK_NOTNULL(self->tools);
206
207 // I have no clue if the Configuration that we get from the log reader is in a
208 // contiguous chunk of memory, and I'm too lazy to either figure it out or
209 // figure out how to extract the actual data buffer + offset.
210 // Instead, copy the flatbuffer and return a copy of the new buffer.
211 aos::FlatbufferDetachedBuffer<aos::Configuration> buffer =
212 aos::CopyFlatBuffer(tools->reader->configuration());
213
214 return PyBytes_FromStringAndSize(
215 reinterpret_cast<const char *>(buffer.data()), buffer.size());
216}
217
218static PyMethodDef LogReader_methods[] = {
219 {"configuration", (PyCFunction)LogReader_configuration, METH_NOARGS,
220 "Return a bytes buffer for the Configuration of the logfile."},
221 {"process", (PyCFunction)LogReader_process, METH_NOARGS,
222 "Processes the logfile and all the subscribed to channels."},
223 {"subscribe", (PyCFunction)LogReader_subscribe,
224 METH_VARARGS | METH_KEYWORDS,
225 "Attempts to subscribe to the provided channel name + type. Returns True "
226 "if successful."},
227 {"get_data_for_channel", (PyCFunction)LogReader_get_data_for_channel,
228 METH_VARARGS | METH_KEYWORDS,
229 "Returns the logged data for a given channel. Raises an exception if you "
230 "did not subscribe to the provided channel. Returned data is a list of "
231 "tuples where each tuple is of the form (monotonic_nsec, realtime_nsec, "
232 "json_message_data)."},
233 {nullptr, 0, 0, nullptr} /* Sentinel */
234};
235
236static PyTypeObject LogReaderType = {
237 PyVarObject_HEAD_INIT(NULL, 0).tp_name = "py_log_reader.LogReader",
238 .tp_doc = "LogReader objects",
239 .tp_basicsize = sizeof(LogReaderType),
240 .tp_itemsize = 0,
241 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
242 .tp_new = LogReader_new,
243 .tp_init = (initproc)LogReader_init,
244 .tp_dealloc = (destructor)LogReader_dealloc,
245 .tp_methods = LogReader_methods,
246};
247
248static PyModuleDef log_reader_module = {
249 PyModuleDef_HEAD_INIT,
250 .m_name = "py_log_reader",
251 .m_doc = "Example module that creates an extension type.",
252 .m_size = -1,
253};
254
255PyObject *InitModule() {
256 PyObject *m;
257 if (PyType_Ready(&LogReaderType) < 0) return nullptr;
258
259 m = PyModule_Create(&log_reader_module);
260 if (m == nullptr) return nullptr;
261
262 Py_INCREF(&LogReaderType);
263 if (PyModule_AddObject(m, "LogReader", (PyObject *)&LogReaderType) < 0) {
264 Py_DECREF(&LogReaderType);
265 Py_DECREF(m);
266 return nullptr;
267 }
268
269 return m;
270}
271
272} // namespace
273} // namespace analysis
274} // namespace frc971
275
276PyMODINIT_FUNC PyInit_py_log_reader(void) {
277 return frc971::analysis::InitModule();
278}