/
hibernated
executable file
·317 lines (276 loc) · 11.5 KB
/
hibernated
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/python3
# jbin - Joe's miscellaneous scripts, tools and configs
# hibernated: hibernation daemon with customizable rules
# Copyright (C) 2021-2022 Johannes Bauer
#
# This file is part of jbin.
#
# jbin is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; this program is ONLY licensed under
# version 3 of the License, later versions are explicitly excluded.
#
# jbin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with jbin. If not, see <http://www.gnu.org/licenses/>.
#
# Johannes Bauer <JohannesBauer@gmx.de>
import os
import sys
import json
import time
import datetime
import contextlib
import collections
import subprocess
import enum
import argparse
import signal
from FriendlyArgumentParser import FriendlyArgumentParser
from DBusQuery import DBusQuery
debug_visible = False
parser = FriendlyArgumentParser(description = "Hibernation daemon.")
parser.add_argument("--debug-assume-screensaver", action = "store_true", help = "Assume screensaver is always active (used for debugging only)." if debug_visible else argparse.SUPPRESS)
parser.add_argument("--debug-no-hibernation", action = "store_true", help = "Do not actually hibernate, just print a message (used for debugging only)." if debug_visible else argparse.SUPPRESS)
parser.add_argument("--debug-no-tasks", action = "store_true", help = "Do not actually execute tasks, just print a message (used for debugging only)." if debug_visible else argparse.SUPPRESS)
parser.add_argument("-s", "--inhibit", action = "store_true", help = "Create the inhibit file to prevent hibernated from hibernating the system, then quit.")
parser.add_argument("-i", "--install", action = "store_true", help = "Install systemd units and activate hibernated, then quit.")
parser.add_argument("-c", "--config", metavar = "filename", default = "~/.config/jbin/hibernated/configuration.json", help = "Configuration file. Defaults to %(default)s.")
parser.add_argument("--create-config", action = "store_true", help = "If it does not exist yet, create a configuration file.")
parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increases verbosity. Can be specified multiple times to increase.")
args = parser.parse_args(sys.argv[1:])
class ScreensaverState(enum.IntEnum):
ScreensaverOff = 0
ScreensaverOn = 1
class TimeLogger():
class Action(enum.IntEnum):
Initial = 0
Same = 1
Change = 2
_Event = collections.namedtuple("Event", [ "action", "old_state", "new_state", "duration" ])
def __init__(self):
self._state = None
self._time = None
def state(self, new_state):
now = time.time()
if (self._state is None) or (self._state != new_state):
if self._state is not None:
result = self._Event(action = self.Action.Change, old_state = self._state, new_state = new_state, duration = now - self._time)
else:
result = self._Event(action = self.Action.Initial, old_state = self._state, new_state = new_state, duration = None)
self._state = new_state
self._time = now
else:
result = self._Event(action = self.Action.Same, old_state = self._state, new_state = None, duration = now - self._time)
return result
class HibernateDaemon():
_DEFAULT_CONFIG = collections.OrderedDict((
("iteration_delay_secs", 10),
("time_until_hibernation_secs", 60),
("inhibit_filename", "/var/run/user/%d/hibernated.inhibit" % (os.getuid())),
("inhibit_processes", [ "restic", "apt-get", "apt-cache", "apt-check", "dpkg" ]),
("logfile_name", "~/.config/jbin/hibernated/hibernated.log"),
("taskfile_name", "~/.config/jbin/hibernated/tasks.json"),
("task_logfile_name", "~/.config/jbin/hibernated/tasks.log"),
("tasks", [ ]),
))
def __init__(self, args):
self._args = args
if self._args.create_config:
self._create_config()
if self._args.install:
self._perform_installation()
self._config = dict(self._DEFAULT_CONFIG)
try:
with open(self.config_filename) as f:
self._config.update(json.load(f))
except FileNotFoundError:
if self._args.verbose >= 2:
print("No configuration file found, using default.", file = sys.stderr)
if self._args.verbose >= 2:
print("Config: %s" % (str(self._config)), file = sys.stderr)
self._itercount = 0
self._state = TimeLogger()
if self._args.inhibit:
self._create_inhibit_file()
self._running = False
signal.signal(signal.SIGINT, self._do_exit)
signal.signal(signal.SIGHUP, self._do_exit)
signal.signal(signal.SIGTERM, self._do_exit)
def _read_taskfile(self):
try:
with open(self.taskfile_name) as f:
return json.load(f)
except FileNotFoundError:
return { }
def _write_taskfile(self, taskfile):
with open(self.taskfile_name, "w") as f:
json.dump(taskfile, f)
def _create_config(self):
if not os.path.exists(self.config_filename):
print("Creating configuration file: %s" % (self.config_filename), file = sys.stderr)
with open(self.config_filename, "w") as f:
json.dump(self._DEFAULT_CONFIG, f, indent = 4)
f.write("\n")
else:
print("Not creating configuration file because it already exists: %s" % (self.config_filename), file = sys.stderr)
def _perform_installation(self):
print("Installing systemd service.", file = sys.stderr)
dirname = os.path.expanduser("~/.local/share/systemd/user")
with contextlib.suppress(FileExistsError):
os.makedirs(dirname)
with open(dirname + "/hibernated.service", "w") as f:
print("[Unit]", file = f)
print("Description=Automatic hibernation service", file = f)
print("After=network-online.target", file = f)
print(file = f)
print("[Service]", file = f)
print("Environment=\"SSH_AUTH_SOCK=/run/user/%d/keyring/ssh\"" % (os.getuid()), file = f)
print("Type=simple", file = f)
print("ExecStart=%s" % (os.path.realpath(__file__)), file = f)
print("WorkingDirectory=%s" % (os.getenv("HOME")), file = f)
print(file = f)
print("[Install]", file = f)
print("WantedBy=default.target", file = f)
subprocess.check_call([ "systemctl", "--user", "enable", "hibernated" ])
subprocess.check_call([ "systemctl", "--user", "start", "hibernated" ])
sys.exit(0)
def _create_inhibit_file(self):
print("Creating inhibit file: %s" % (self.inhibit_filename), file = sys.stderr)
with open(self.inhibit_filename, "wb") as f:
pass
sys.exit(0)
@staticmethod
def _get_running_processes():
output = subprocess.check_output([ "ps", "-A", "--no-headers", "-o", "%c" ]).decode()
return output.rstrip("\r\n").split("\n")
@property
def config_filename(self):
return os.path.realpath(os.path.expanduser(self._args.config))
@property
def tasks(self):
return self._config.get("tasks", [ ])
@property
def iteration_delay_secs(self):
return self._config["iteration_delay_secs"]
@property
def time_until_hibernation_secs(self):
return self._config["time_until_hibernation_secs"]
@property
def inhibit_filename(self):
return self._config["inhibit_filename"]
@property
def inhibit_processes(self):
return self._config["inhibit_processes"]
@property
def logfile_name(self):
filename = self._config["logfile_name"]
return os.path.expanduser(filename)
@property
def taskfile_name(self):
filename = self._config["taskfile_name"]
return os.path.expanduser(filename)
@property
def task_logfile_name(self):
filename = self._config["task_logfile_name"]
return os.path.expanduser(filename)
def _log(self, msg):
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self.logfile_name, "a") as f:
print("%s: %s" % (now, msg), file = sys.stderr)
print("%s: %s" % (now, msg), file = f)
def _perform_idle_task(self, task):
cmd = " ".join(task["cmd"])
taskfile = self._read_taskfile()
screentime_since_last_run = taskfile.get(cmd, 0)
if screentime_since_last_run > task["every_secs"]:
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self.task_logfile_name, "a") as f:
print("%s: %s" % (now, cmd), file = f)
f.flush()
self._log("Running command: %s (after %d secs, threshold %d secs)" % (cmd, screentime_since_last_run, task["every_secs"]))
t0 = time.time()
if not self._args.debug_no_tasks:
result = subprocess.run(task["cmd"], stdout = f, stderr = subprocess.STDOUT)
returncode = result.returncode
else:
returncode = -1
t1 = time.time()
self._log("Command %s finished after %d secs with returncode %d." % (cmd, t1 - t0, returncode))
print("Finished: %s after %d secs with returncode %d." % (cmd, t1 - t0, returncode), file = f)
print(file = f)
taskfile[cmd] = 0
self._write_taskfile(taskfile)
def _perform_idle_tasks(self):
for task in self.tasks:
self._perform_idle_task(task)
def _trigger_hibernation(self):
# Send machine into suspend.
self._screensaver_active_since = None
t0 = time.time()
if not self._args.debug_no_hibernation:
DBusQuery.suspend_to_ram()
else:
print("Would now suspend to RAM.")
# Give the system some time to adjust after waking up so that we can
# measure correctly. Trying to get rid of "Woke up from suspend after 0
# seconds" messages.
time.sleep(10)
t1 = time.time() - 10
self._log("Woke up from suspend after %d seconds." % (t1 - t0))
time.sleep(self.time_until_hibernation_secs)
def _perform_idle_tasks_then_hibernate(self):
self._perform_idle_tasks()
if DBusQuery.is_screensaver_active() or self._args.debug_assume_screensaver:
# If the tasks ran very long, the user might be working again, so
# double check the screensaver. Only hibernate if it's active.
self._trigger_hibernation()
def _time_threshold_reached(self):
if os.path.exists(self.inhibit_filename):
return
running_processes = set(self._get_running_processes())
inhibit_processes = set(self.inhibit_processes)
forbidden_processes = running_processes & inhibit_processes
if len(forbidden_processes) > 0:
return
self._perform_idle_tasks_then_hibernate()
def _add_screentime(self, time_secs):
taskfile = self._read_taskfile()
for task in self._config.get("tasks", [ ]):
cmd = " ".join(task["cmd"])
if cmd not in taskfile:
taskfile[cmd] = time_secs
else:
taskfile[cmd] += time_secs
self._write_taskfile(taskfile)
def _get_screensaver_event(self):
screensaver_active = DBusQuery.is_screensaver_active() or self._args.debug_assume_screensaver
screensaver_state = ScreensaverState(screensaver_active)
event = self._state.state(screensaver_state)
return event
def _check_run(self):
event = self._get_screensaver_event()
if (event.action == self._state.Action.Change) and (event.old_state == ScreensaverState.ScreensaverOff):
# We log the time that the screensaver was off
self._add_screentime(event.duration)
elif (event.action == self._state.Action.Same) and (event.old_state == ScreensaverState.ScreensaverOn) and (event.duration > self.time_until_hibernation_secs):
# Screensaver has been on for longer than the threshold
self._time_threshold_reached()
def _do_exit(self, signal_no, frame):
self._running = False
def run(self):
self._running = True
while self._running:
self._itercount += 1
self._check_run()
time.sleep(self.iteration_delay_secs)
event = self._get_screensaver_event()
if (event.action == self._state.Action.Same) and (event.old_state == ScreensaverState.ScreensaverOff):
# We're shutting down while the screensaver is off
self._add_screentime(event.duration)
hd = HibernateDaemon(args)
hd.run()