1
+ import os
1
2
import time
2
3
import txaio
3
4
@@ -31,6 +32,39 @@ def timestamp2influxtime(time, protocol):
31
32
return influx_t
32
33
33
34
35
+ def _get_credentials ():
36
+ """Read credentials from environment variable or file.
37
+
38
+ Reads from either `INFLUXDB_USERNAME`, `INFLUXDB_PASSWORD`,
39
+ `INFLUXDB_USERNAME_FILE`, or `INFLUXDB_PASSWORD_FILE`. Precedence is given
40
+ to the non-`_FILE` variables.
41
+
42
+ Returns:
43
+ A tuple of (username, password). Defaults to ('root', 'root') if none
44
+ of the environment variables are present.
45
+
46
+ """
47
+ username_file = os .environ .get ('INFLUXDB_USERNAME_FILE' )
48
+ password_file = os .environ .get ('INFLUXDB_PASSWORD_FILE' )
49
+
50
+ username = None
51
+ password = None
52
+ if username_file is not None :
53
+ with open (username_file , 'r' , encoding = "utf-8" ) as f :
54
+ username = f .read ().rstrip ('\r \n ' )
55
+ if password_file is not None :
56
+ with open (password_file , 'r' , encoding = "utf-8" ) as f :
57
+ password = f .read ().rstrip ('\r \n ' )
58
+
59
+ username_default = 'root' if username is None else username
60
+ password_default = 'root' if password is None else password
61
+
62
+ username = os .environ .get ('INFLUXDB_USERNAME' , username_default )
63
+ password = os .environ .get ('INFLUXDB_PASSWORD' , password_default )
64
+
65
+ return username , password
66
+
67
+
34
68
class Publisher :
35
69
"""
36
70
Data publisher. This manages data to be published to the InfluxDB.
@@ -81,7 +115,14 @@ def __init__(self, host, database, incoming_data, port=8086, protocol='line',
81
115
print (f"gzip encoding enabled: { gzip } " )
82
116
print (f"data protocol: { protocol } " )
83
117
84
- self .client = InfluxDBClient (host = self .host , port = self .port , gzip = gzip )
118
+ username , password = _get_credentials ()
119
+
120
+ self .client = InfluxDBClient (
121
+ host = self .host ,
122
+ port = self .port ,
123
+ username = username ,
124
+ password = password ,
125
+ gzip = gzip )
85
126
86
127
db_list = None
87
128
# ConnectionError here is indicative of InfluxDB being down
@@ -92,6 +133,12 @@ def __init__(self, host, database, incoming_data, port=8086, protocol='line',
92
133
LOG .error ("Connection error, attempting to reconnect to DB." )
93
134
self .client = InfluxDBClient (host = self .host , port = self .port , gzip = gzip )
94
135
time .sleep (1 )
136
+ except InfluxDBClientError as err :
137
+ if err .code == 401 :
138
+ LOG .error ("Failed to authenticate. Check your credentials." )
139
+ else :
140
+ LOG .error (f"Unknown client error: { err } " )
141
+ time .sleep (1 )
95
142
if operate_callback and not operate_callback ():
96
143
break
97
144
0 commit comments