|
| 1 | +""" |
| 2 | +Helpers classes to make easier use the client in multiprocessing environment. |
| 3 | +
|
| 4 | +For more information how the multiprocessing works see Python's |
| 5 | +`reference docs <https://docs.python.org/3/library/multiprocessing.html>`_. |
| 6 | +""" |
| 7 | +import logging |
| 8 | +import multiprocessing |
| 9 | + |
| 10 | +from influxdb_client import InfluxDBClient, WriteOptions |
| 11 | +from influxdb_client.client.exceptions import InfluxDBError |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def _success_callback(conf: (str, str, str), data: str): |
| 17 | + """Successfully writen batch.""" |
| 18 | + logger.debug(f"Written batch: {conf}, data: {data}") |
| 19 | + |
| 20 | + |
| 21 | +def _error_callback(conf: (str, str, str), data: str, exception: InfluxDBError): |
| 22 | + """Unsuccessfully writen batch.""" |
| 23 | + logger.debug(f"Cannot write batch: {conf}, data: {data} due: {exception}") |
| 24 | + |
| 25 | + |
| 26 | +def _retry_callback(conf: (str, str, str), data: str, exception: InfluxDBError): |
| 27 | + """Retryable error.""" |
| 28 | + logger.debug(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}") |
| 29 | + |
| 30 | + |
| 31 | +class _PoisonPill: |
| 32 | + """To notify process to terminate.""" |
| 33 | + |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class MultiprocessingWriter(multiprocessing.Process): |
| 38 | + """ |
| 39 | + The Helper class to write data into InfluxDB in independent OS process. |
| 40 | +
|
| 41 | + Example: |
| 42 | + .. code-block:: python |
| 43 | +
|
| 44 | + from influxdb_client import WriteOptions |
| 45 | + from influxdb_client.client.util.multiprocessing_helper import MultiprocessingWriter |
| 46 | +
|
| 47 | +
|
| 48 | + def main(): |
| 49 | + writer = MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org", |
| 50 | + write_options=WriteOptions(batch_size=100)) |
| 51 | + writer.start() |
| 52 | +
|
| 53 | + for x in range(1, 1000): |
| 54 | + writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}") |
| 55 | +
|
| 56 | + writer.__del__() |
| 57 | +
|
| 58 | +
|
| 59 | + if __name__ == '__main__': |
| 60 | + main() |
| 61 | +
|
| 62 | +
|
| 63 | + How to use with context_manager: |
| 64 | + .. code-block:: python |
| 65 | +
|
| 66 | + from influxdb_client import WriteOptions |
| 67 | + from influxdb_client.client.util.multiprocessing_helper import MultiprocessingWriter |
| 68 | +
|
| 69 | +
|
| 70 | + def main(): |
| 71 | + with MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org", |
| 72 | + write_options=WriteOptions(batch_size=100)) as writer: |
| 73 | + for x in range(1, 1000): |
| 74 | + writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}") |
| 75 | +
|
| 76 | +
|
| 77 | + if __name__ == '__main__': |
| 78 | + main() |
| 79 | +
|
| 80 | +
|
| 81 | + How to handle batch events: |
| 82 | + .. code-block:: python |
| 83 | +
|
| 84 | + from influxdb_client import WriteOptions |
| 85 | + from influxdb_client.client.exceptions import InfluxDBError |
| 86 | + from influxdb_client.client.util.multiprocessing_helper import MultiprocessingWriter |
| 87 | +
|
| 88 | +
|
| 89 | + class BatchingCallback(object): |
| 90 | +
|
| 91 | + def success(self, conf: (str, str, str), data: str): |
| 92 | + print(f"Written batch: {conf}, data: {data}") |
| 93 | +
|
| 94 | + def error(self, conf: (str, str, str), data: str, exception: InfluxDBError): |
| 95 | + print(f"Cannot write batch: {conf}, data: {data} due: {exception}") |
| 96 | +
|
| 97 | + def retry(self, conf: (str, str, str), data: str, exception: InfluxDBError): |
| 98 | + print(f"Retryable error occurs for batch: {conf}, data: {data} retry: {exception}") |
| 99 | +
|
| 100 | +
|
| 101 | + def main(): |
| 102 | + callback = BatchingCallback() |
| 103 | + with MultiprocessingWriter(url="http://localhost:8086", token="my-token", org="my-org", |
| 104 | + success_callback=callback.success, |
| 105 | + error_callback=callback.error, |
| 106 | + retry_callback=callback.retry) as writer: |
| 107 | +
|
| 108 | + for x in range(1, 1000): |
| 109 | + writer.write(bucket="my-bucket", record=f"mem,tag=a value={x}i {x}") |
| 110 | +
|
| 111 | +
|
| 112 | + if __name__ == '__main__': |
| 113 | + main() |
| 114 | +
|
| 115 | +
|
| 116 | + """ |
| 117 | + |
| 118 | + __started__ = False |
| 119 | + __disposed__ = False |
| 120 | + |
| 121 | + def __init__(self, **kwargs) -> None: |
| 122 | + """ |
| 123 | + Initialize defaults. |
| 124 | +
|
| 125 | + For more information how to initialize the writer see the examples above. |
| 126 | +
|
| 127 | + :param kwargs: arguments are passed into ``__init__`` function of ``InfluxDBClient`` and ``write_api``. |
| 128 | + """ |
| 129 | + multiprocessing.Process.__init__(self) |
| 130 | + self.kwargs = kwargs |
| 131 | + self.client = None |
| 132 | + self.write_api = None |
| 133 | + self.queue_ = multiprocessing.Manager().Queue() |
| 134 | + |
| 135 | + def write(self, **kwargs) -> None: |
| 136 | + """ |
| 137 | + Append time-series data into underlying queue. |
| 138 | +
|
| 139 | + For more information how to pass arguments see the examples above. |
| 140 | +
|
| 141 | + :param kwargs: arguments are passed into ``write`` function of ``WriteApi`` |
| 142 | + :return: None |
| 143 | + """ |
| 144 | + assert self.__disposed__ is False, 'Cannot write data: the writer is closed.' |
| 145 | + assert self.__started__ is True, 'Cannot write data: the writer is not started.' |
| 146 | + self.queue_.put(kwargs) |
| 147 | + |
| 148 | + def run(self): |
| 149 | + """Initialize ``InfluxDBClient`` and waits for data to writes into InfluxDB.""" |
| 150 | + # Initialize Client and Write API |
| 151 | + self.client = InfluxDBClient(**self.kwargs) |
| 152 | + self.write_api = self.client.write_api(write_options=self.kwargs.get('write_options', WriteOptions()), |
| 153 | + success_callback=self.kwargs.get('success_callback', _success_callback), |
| 154 | + error_callback=self.kwargs.get('error_callback', _error_callback), |
| 155 | + retry_callback=self.kwargs.get('retry_callback', _retry_callback)) |
| 156 | + # Infinite loop - until poison pill |
| 157 | + while True: |
| 158 | + next_record = self.queue_.get() |
| 159 | + if type(next_record) is _PoisonPill: |
| 160 | + # Poison pill means break the loop |
| 161 | + self.terminate() |
| 162 | + self.queue_.task_done() |
| 163 | + break |
| 164 | + self.write_api.write(**next_record) |
| 165 | + self.queue_.task_done() |
| 166 | + |
| 167 | + def start(self) -> None: |
| 168 | + """Start independent process for writing data into InfluxDB.""" |
| 169 | + super().start() |
| 170 | + self.__started__ = True |
| 171 | + |
| 172 | + def terminate(self) -> None: |
| 173 | + """ |
| 174 | + Cleanup resources in independent process. |
| 175 | +
|
| 176 | + This function **cannot be used** to terminate the ``MultiprocessingWriter``. |
| 177 | + If you want to finish your writes please call: ``__del__``. |
| 178 | + """ |
| 179 | + if self.write_api: |
| 180 | + logger.info("flushing data...") |
| 181 | + self.write_api.__del__() |
| 182 | + self.write_api = None |
| 183 | + if self.client: |
| 184 | + self.client.__del__() |
| 185 | + self.client = None |
| 186 | + logger.info("closed") |
| 187 | + |
| 188 | + def __enter__(self): |
| 189 | + """Enter the runtime context related to this object.""" |
| 190 | + self.start() |
| 191 | + return self |
| 192 | + |
| 193 | + def __exit__(self, exc_type, exc_value, traceback): |
| 194 | + """Exit the runtime context related to this object.""" |
| 195 | + self.__del__() |
| 196 | + |
| 197 | + def __del__(self): |
| 198 | + """Dispose the client and write_api.""" |
| 199 | + if self.__started__: |
| 200 | + self.queue_.put(_PoisonPill()) |
| 201 | + self.queue_.join() |
| 202 | + self.join() |
| 203 | + self.queue_ = None |
| 204 | + self.__started__ = False |
| 205 | + self.__disposed__ = True |
0 commit comments