James Kuszmaul | 7daef36 | 2019-12-31 18:28:17 -0800 | [diff] [blame] | 1 | // 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 | |
| 23 | namespace frc971 { |
| 24 | namespace analysis { |
| 25 | namespace { |
| 26 | |
| 27 | // All the data corresponding to a single message. |
| 28 | struct 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. |
| 36 | struct 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. |
| 44 | struct LogReaderTools { |
| 45 | std::unique_ptr<aos::logger::LogReader> reader; |
| 46 | std::unique_ptr<aos::SimulatedEventLoopFactory> event_loop_factory; |
| 47 | // Event loop to use for subscribing to buses. |
| 48 | std::unique_ptr<aos::EventLoop> event_loop; |
| 49 | std::vector<ChannelData> channel_data; |
| 50 | // Whether we have called process() on the reader yet. |
| 51 | bool processed = false; |
| 52 | }; |
| 53 | |
| 54 | struct LogReaderType { |
| 55 | PyObject_HEAD; |
| 56 | LogReaderTools *tools = nullptr; |
| 57 | }; |
| 58 | |
| 59 | void LogReader_dealloc(LogReaderType *self) { |
| 60 | LogReaderTools *tools = self->tools; |
| 61 | if (!tools->processed) { |
| 62 | tools->reader->Deregister(); |
| 63 | } |
| 64 | delete tools; |
| 65 | Py_TYPE(self)->tp_free((PyObject *)self); |
| 66 | } |
| 67 | |
| 68 | PyObject *LogReader_new(PyTypeObject *type, PyObject * /*args*/, |
| 69 | PyObject * /*kwds*/) { |
| 70 | LogReaderType *self; |
| 71 | self = (LogReaderType *)type->tp_alloc(type, 0); |
| 72 | if (self != nullptr) { |
| 73 | self->tools = new LogReaderTools(); |
| 74 | if (self->tools == nullptr) { |
| 75 | return nullptr; |
| 76 | } |
| 77 | } |
| 78 | return (PyObject *)self; |
| 79 | } |
| 80 | |
| 81 | int LogReader_init(LogReaderType *self, PyObject *args, PyObject *kwds) { |
| 82 | const char *kwlist[] = {"log_file_name", nullptr}; |
| 83 | |
| 84 | const char *log_file_name; |
| 85 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "s", const_cast<char **>(kwlist), |
| 86 | &log_file_name)) { |
| 87 | return -1; |
| 88 | } |
| 89 | |
| 90 | LogReaderTools *tools = CHECK_NOTNULL(self->tools); |
| 91 | tools->reader = std::make_unique<aos::logger::LogReader>(log_file_name); |
| 92 | tools->event_loop_factory = std::make_unique<aos::SimulatedEventLoopFactory>( |
| 93 | tools->reader->configuration()); |
| 94 | tools->reader->Register(tools->event_loop_factory.get()); |
| 95 | |
| 96 | tools->event_loop = tools->event_loop_factory->MakeEventLoop("data_fetcher"); |
| 97 | tools->event_loop->SkipTimingReport(); |
| 98 | |
| 99 | return 0; |
| 100 | } |
| 101 | |
| 102 | PyObject *LogReader_get_data_for_channel(LogReaderType *self, |
| 103 | PyObject *args, |
| 104 | PyObject *kwds) { |
| 105 | const char *kwlist[] = {"name", "type", nullptr}; |
| 106 | |
| 107 | const char *name; |
| 108 | const char *type; |
| 109 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss", |
| 110 | const_cast<char **>(kwlist), &name, &type)) { |
| 111 | return nullptr; |
| 112 | } |
| 113 | |
| 114 | LogReaderTools *tools = CHECK_NOTNULL(self->tools); |
| 115 | |
| 116 | if (!tools->processed) { |
| 117 | PyErr_SetString(PyExc_RuntimeError, |
| 118 | "Called get_data_for_bus before calling process()."); |
| 119 | return nullptr; |
| 120 | } |
| 121 | |
| 122 | for (const auto &channel : tools->channel_data) { |
| 123 | if (channel.name == name && channel.type == type) { |
| 124 | PyObject *list = PyList_New(channel.messages.size()); |
| 125 | for (size_t ii = 0; ii < channel.messages.size(); ++ii) |
| 126 | { |
| 127 | const auto &message = channel.messages[ii]; |
| 128 | PyObject *monotonic_time = PyLong_FromLongLong( |
| 129 | std::chrono::duration_cast<std::chrono::nanoseconds>( |
| 130 | message.monotonic_sent_time.time_since_epoch()) |
| 131 | .count()); |
| 132 | PyObject *realtime_time = PyLong_FromLongLong( |
| 133 | std::chrono::duration_cast<std::chrono::nanoseconds>( |
| 134 | message.realtime_sent_time.time_since_epoch()) |
| 135 | .count()); |
| 136 | PyObject *json_data = PyUnicode_FromStringAndSize( |
| 137 | message.json_data.data(), message.json_data.size()); |
| 138 | PyObject *entry = |
| 139 | PyTuple_Pack(3, monotonic_time, realtime_time, json_data); |
| 140 | if (PyList_SetItem(list, ii, entry) != 0) { |
| 141 | return nullptr; |
| 142 | } |
| 143 | } |
| 144 | return list; |
| 145 | } |
| 146 | } |
| 147 | PyErr_SetString(PyExc_ValueError, |
| 148 | "The provided channel was never subscribed to."); |
| 149 | return nullptr; |
| 150 | } |
| 151 | |
| 152 | PyObject *LogReader_subscribe(LogReaderType *self, PyObject *args, |
| 153 | PyObject *kwds) { |
| 154 | const char *kwlist[] = {"name", "type", nullptr}; |
| 155 | |
| 156 | const char *name; |
| 157 | const char *type; |
| 158 | if (!PyArg_ParseTupleAndKeywords(args, kwds, "ss", |
| 159 | const_cast<char **>(kwlist), &name, &type)) { |
| 160 | return nullptr; |
| 161 | } |
| 162 | |
| 163 | LogReaderTools *tools = CHECK_NOTNULL(self->tools); |
| 164 | |
| 165 | if (tools->processed) { |
| 166 | PyErr_SetString(PyExc_RuntimeError, |
| 167 | "Called subscribe after calling process()."); |
| 168 | return nullptr; |
| 169 | } |
| 170 | |
| 171 | const aos::Channel *const channel = aos::configuration::GetChannel( |
| 172 | tools->reader->configuration(), name, type, "", nullptr); |
| 173 | if (channel == nullptr) { |
| 174 | return Py_False; |
| 175 | } |
| 176 | const int index = tools->channel_data.size(); |
| 177 | tools->channel_data.push_back( |
| 178 | {.name = name, .type = type, .messages = {}}); |
| 179 | tools->event_loop->MakeRawWatcher( |
| 180 | channel, [channel, index, tools](const aos::Context &context, |
| 181 | const void *message) { |
| 182 | tools->channel_data[index].messages.push_back( |
| 183 | {.monotonic_sent_time = context.monotonic_event_time, |
| 184 | .realtime_sent_time = context.realtime_event_time, |
| 185 | .json_data = aos::FlatbufferToJson( |
| 186 | channel->schema(), static_cast<const uint8_t *>(message))}); |
| 187 | }); |
| 188 | return Py_True; |
| 189 | } |
| 190 | |
| 191 | static PyObject *LogReader_process(LogReaderType *self, |
| 192 | PyObject *Py_UNUSED(ignored)) { |
| 193 | LogReaderTools *tools = CHECK_NOTNULL(self->tools); |
| 194 | |
| 195 | if (tools->processed) { |
| 196 | PyErr_SetString(PyExc_RuntimeError, "process() may only be called once."); |
| 197 | return nullptr; |
| 198 | } |
| 199 | |
| 200 | tools->processed = true; |
| 201 | |
| 202 | tools->event_loop_factory->Run(); |
| 203 | tools->reader->Deregister(); |
| 204 | |
| 205 | Py_RETURN_NONE; |
| 206 | } |
| 207 | |
| 208 | static PyObject *LogReader_configuration(LogReaderType *self, |
| 209 | PyObject *Py_UNUSED(ignored)) { |
| 210 | LogReaderTools *tools = CHECK_NOTNULL(self->tools); |
| 211 | |
| 212 | // I have no clue if the Configuration that we get from the log reader is in a |
| 213 | // contiguous chunk of memory, and I'm too lazy to either figure it out or |
| 214 | // figure out how to extract the actual data buffer + offset. |
| 215 | // Instead, copy the flatbuffer and return a copy of the new buffer. |
| 216 | aos::FlatbufferDetachedBuffer<aos::Configuration> buffer = |
| 217 | aos::CopyFlatBuffer(tools->reader->configuration()); |
| 218 | |
| 219 | return PyBytes_FromStringAndSize( |
| 220 | reinterpret_cast<const char *>(buffer.data()), buffer.size()); |
| 221 | } |
| 222 | |
| 223 | static PyMethodDef LogReader_methods[] = { |
| 224 | {"configuration", (PyCFunction)LogReader_configuration, METH_NOARGS, |
| 225 | "Return a bytes buffer for the Configuration of the logfile."}, |
| 226 | {"process", (PyCFunction)LogReader_process, METH_NOARGS, |
| 227 | "Processes the logfile and all the subscribed to channels."}, |
| 228 | {"subscribe", (PyCFunction)LogReader_subscribe, |
| 229 | METH_VARARGS | METH_KEYWORDS, |
| 230 | "Attempts to subscribe to the provided channel name + type. Returns True " |
| 231 | "if successful."}, |
| 232 | {"get_data_for_channel", (PyCFunction)LogReader_get_data_for_channel, |
| 233 | METH_VARARGS | METH_KEYWORDS, |
| 234 | "Returns the logged data for a given channel. Raises an exception if you " |
| 235 | "did not subscribe to the provided channel. Returned data is a list of " |
| 236 | "tuples where each tuple is of the form (monotonic_nsec, realtime_nsec, " |
| 237 | "json_message_data)."}, |
| 238 | {nullptr, 0, 0, nullptr} /* Sentinel */ |
| 239 | }; |
| 240 | |
| 241 | static PyTypeObject LogReaderType = { |
| 242 | PyVarObject_HEAD_INIT(NULL, 0).tp_name = "py_log_reader.LogReader", |
| 243 | .tp_doc = "LogReader objects", |
| 244 | .tp_basicsize = sizeof(LogReaderType), |
| 245 | .tp_itemsize = 0, |
| 246 | .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, |
| 247 | .tp_new = LogReader_new, |
| 248 | .tp_init = (initproc)LogReader_init, |
| 249 | .tp_dealloc = (destructor)LogReader_dealloc, |
| 250 | .tp_methods = LogReader_methods, |
| 251 | }; |
| 252 | |
| 253 | static PyModuleDef log_reader_module = { |
| 254 | PyModuleDef_HEAD_INIT, |
| 255 | .m_name = "py_log_reader", |
| 256 | .m_doc = "Example module that creates an extension type.", |
| 257 | .m_size = -1, |
| 258 | }; |
| 259 | |
| 260 | PyObject *InitModule() { |
| 261 | PyObject *m; |
| 262 | if (PyType_Ready(&LogReaderType) < 0) return nullptr; |
| 263 | |
| 264 | m = PyModule_Create(&log_reader_module); |
| 265 | if (m == nullptr) return nullptr; |
| 266 | |
| 267 | Py_INCREF(&LogReaderType); |
| 268 | if (PyModule_AddObject(m, "LogReader", (PyObject *)&LogReaderType) < 0) { |
| 269 | Py_DECREF(&LogReaderType); |
| 270 | Py_DECREF(m); |
| 271 | return nullptr; |
| 272 | } |
| 273 | |
| 274 | return m; |
| 275 | } |
| 276 | |
| 277 | } // namespace |
| 278 | } // namespace analysis |
| 279 | } // namespace frc971 |
| 280 | |
| 281 | PyMODINIT_FUNC PyInit_py_log_reader(void) { |
| 282 | return frc971::analysis::InitModule(); |
| 283 | } |