예제 #1
0
class InfluxOutput(Output):
    ip: str
    port: str
    token: str
    org: str
    bucket: str
    measurement: str
    url: str
    tags: Dict
    output_timestamp_name: str
    influx_writer: Any

    def __init__(self, conf: Dict[Any, Any] = None) -> None:
        super().__init__()
        if (conf is not None):
            self.configure(conf=conf)

    def configure(self, conf: Dict[Any, Any] = None) -> None:
        super().configure(conf=conf)

        # Configura writer
        self.ip = conf["ip"]
        self.port = conf["port"]
        self.token = conf["token"]
        self.org = conf["org"]
        self.url = "http://" + self.ip + ":" + self.port

        self.bucket = conf["bucket"]
        self.measurement = conf["measurement"]
        self.tags = eval(conf["tags"])
        self.output_timestamp_name = conf["output_timestamp_name"]

        self.influx_writer = InfluxDBClient(
            url=self.url, token=self.token,
            org=self.org).write_api(write_options=ASYNCHRONOUS)

    def send_out(self, output_dict: Dict[str, Any],
                 datetime_timestamp: Any) -> None:
        # Remove timestamp from output dictionary
        # NOTE: timestamp MUST be in nanoseconds
        timestamp = int(output_dict[self.output_timestamp_name] * 1000000000)
        only_values = output_dict
        del only_values[self.output_timestamp_name]

        # Delete strings that cannot be written to influxdb
        to_delete = []
        for value in only_values:
            if (isinstance(only_values[value], str)
                    or isinstance(only_values[value], bool)
                    or isinstance(only_values[value], dict)):
                to_delete.append(value)

        for v_d in to_delete:
            del only_values[v_d]

        try:
            # Write to database
            #print(only_values, flush=True)
            self.influx_writer.write(self.bucket, self.org,
                                     [{
                                         "measurement": self.measurement,
                                         "tags": self.tags,
                                         "fields": only_values,
                                         "time": timestamp
                                     }])

            self.influx_writer.close()
        except OSError:
            # If too many opened files wait one second and try again.
            time.sleep(100)
            print("{}: Too many opened files. Retrying now.".format(
                datetime.datetime.now()),
                  flush=True)
            self.send_out(output_dict=output_dict)