Skip to content

Commit 8876507

Browse files
committed
add iterate method to journald worker
1 parent 0dd33ea commit 8876507

File tree

3 files changed

+46
-3
lines changed

3 files changed

+46
-3
lines changed

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,18 @@ Library functions to monitor state of systemd spawned units
3131
time.sleep(60)
3232
```
3333

34-
2. Get unit properties
34+
2. Single-thread realtime monitoring
35+
36+
```python
37+
from systemd_monitor.journald_worker import JournaldWorker
38+
39+
worker = JournaldWorker()
40+
41+
for unit, state in worker.run_iterate():
42+
print("Update received for unit {}".format(unit))
43+
```
44+
45+
3. Get unit properties
3546

3647
```python
3748
from systemd_monitor.systemd_dbus_adapter import SystemdDBusAdapter

src/systemd_monitor/journald_worker.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@ def __load_states(self):
8080
'''
8181
initial services load
8282
'''
83-
self.__states = self.__systemd.get_all()
83+
with self.__lock:
84+
self.__states = self.__systemd.get_all()
8485

8586
def run(self):
8687
'''
@@ -112,6 +113,37 @@ def run(self):
112113
self.__status = False
113114
time.sleep(60)
114115

116+
def run_iterate(self):
117+
'''
118+
run thread and return states right in time
119+
'''
120+
self.__load_states()
121+
while self.__should_run:
122+
try:
123+
for line in self.__get_journal():
124+
self.__status = True
125+
# exit on no actions
126+
if not self.__should_run:
127+
break
128+
# parse line
129+
if isinstance(line, bytes):
130+
line = line.decode('utf8')
131+
data = json.loads(line)
132+
# check if it is unit related infomation
133+
if 'UNIT' not in data:
134+
continue
135+
# update internal storage
136+
with self.__lock:
137+
self.__states[
138+
data['UNIT']] = self.__systemd.get(
139+
data['UNIT'])
140+
self.__lst = datetime.datetime.utcnow()
141+
yield data['UNIT'], self.__states[data['UNIT']]
142+
except Exception:
143+
self.__logger.warning('Exception recieved', exc_info=True)
144+
self.__status = False
145+
time.sleep(60)
146+
115147
def stop(self):
116148
'''
117149
stop worker

src/systemd_monitor/systemd_dbus_adapter.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def get(self, unit):
113113
# type defined properties
114114
interface = self.__define_type(unit)
115115
properties.update(service.GetAll(interface))
116-
return systemd_unit_state.SystemdUnit(path, **properties)
116+
return systemd_unit.SystemdUnit(path, **properties)
117117

118118
def reload_unit(self, unit, mode='replace'):
119119
'''

0 commit comments

Comments
 (0)