-
Notifications
You must be signed in to change notification settings - Fork 863
Expand file tree
/
Copy pathcinnamon-launcher
More file actions
executable file
·271 lines (239 loc) · 9.56 KB
/
cinnamon-launcher
File metadata and controls
executable file
·271 lines (239 loc) · 9.56 KB
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
#!/usr/bin/python3
#
""" Launches or restarts cinnamon
"""
import os
import sys
import time
import gettext
from setproctitle import setproctitle
from pathlib import Path
import psutil
import subprocess
import threading
import gi
import shutil
gi.require_version('Gtk', '3.0') # noqa
from gi.repository import Gtk, GLib, Gio, GLib
FALLBACK_COMMAND = "metacity"
FALLBACK_ARGS = ("--replace",)
LAUNCHER_BUS_NAME = "org.cinnamon.Launcher"
LAUNCHER_BUS_PATH = "/org/cinnamon/Launcher"
INTERFACE_XML = (
"<node>"
" <interface name='org.cinnamon.Launcher'>"
" <method name='CanRestart'>"
" <arg type='b' name='result' direction='out'/>"
" </method>"
" <method name='TryRestart'>"
" <arg type='b' name='result' direction='out'/>"
" </method>"
" </interface>"
"</node>"
)
gettext.install("cinnamon", "/usr/share/locale")
panel_process_name = None
panel_cmd = None
if shutil.which("mate-panel"):
panel_process_name = "mate-panel"
panel_cmd = "mate-panel --replace &"
elif shutil.which("gnome-panel"):
panel_process_name = "gnome-panel"
panel_cmd = "gnome-panel --replace &"
elif shutil.which("tint2"):
panel_process_name = "tint2"
panel_cmd = "killall tint2; tint2 &"
# Used as a decorator to run things in the background
def async_function(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
return wrapper
# Used as a decorator to run things in the main loop, from another thread
def idle_function(func):
def wrapper(*args):
GLib.idle_add(func, *args)
return wrapper
class Launcher:
def __init__(self):
self.fb_pid = 0
self.kill_lock = threading.Lock()
self.polkit_agent_proc = None
self.nm_applet_proc = None
self.automount_proc = None
self.can_restart = False
self.dialog = None
self.cinnamon_pid = os.fork()
if self.cinnamon_pid == 0:
os.execvp("cinnamon", ("cinnamon", "--replace", ) + tuple(sys.argv[1:]))
else:
self.settings = Gio.Settings(schema="org.cinnamon.launcher")
self.settings.connect("changed::memory-limit-enabled", self.on_settings_changed)
self.killed = False
if self.settings.get_boolean("memory-limit-enabled"):
print("Cinnamon memory limit enabled: %d MB" % self.settings.get_int("memory-limit"))
self.monitor_memory()
self.setup_dbus()
self.wait_for_process()
Gtk.main()
def on_settings_changed(self, settings, key):
print("Memory profiler status changed, restarting Cinnamon.")
self.restart_cinnamon()
def setup_dbus(self):
self.node_info = Gio.DBusNodeInfo.new_for_xml(INTERFACE_XML)
Gio.bus_own_name(
Gio.BusType.SESSION,
LAUNCHER_BUS_NAME,
Gio.BusNameOwnerFlags.NONE,
self.on_bus_acquired,
None,
None
)
def on_bus_acquired(self, connection, name):
connection.register_object(
LAUNCHER_BUS_PATH,
self.node_info.interfaces[0],
self.on_method_call
)
def on_method_call(self, connection, sender, object_path,
interface_name, method_name, parameters, invocation):
if method_name == "CanRestart":
invocation.return_value(GLib.Variant("(b)", (self.can_restart,)))
elif method_name == "TryRestart":
result = False
if self.can_restart and self.dialog is not None:
GLib.idle_add(self.dialog.response, Gtk.ResponseType.YES)
result = True
invocation.return_value(GLib.Variant("(b)", (result,)))
@async_function
def wait_for_process(self):
exit_status = os.waitpid(self.cinnamon_pid, 0)[1]
if not os.WIFEXITED(exit_status):
with self.kill_lock:
if self.killed:
# Restart Cinnamon
self.restart_cinnamon()
else:
self.fb_pid = os.fork()
if self.fb_pid == 0:
# Start the fallback panel
if panel_cmd is not None:
os.system(panel_cmd)
# Start the fallback window manager
os.execvp(FALLBACK_COMMAND, (FALLBACK_COMMAND,) + FALLBACK_ARGS)
else:
self.launch_fallback_helpers()
self.confirm_restart()
else:
Gtk.main_quit()
def launch_fallback_helpers(self):
agents = ("/usr/lib/policykit-1-gnome/polkit-gnome-authentication-agent-1",
"/usr/libexec/polkit-gnome-authentication-agent-1",
"/usr/libexec/polkit-mate-authentication-agent-1")
for path in agents:
if Path(path).exists():
print(f"Launching for fallback session: {path}")
self.polkit_agent_proc = subprocess.Popen([path])
break
# Start NM applet
if shutil.which("nm-applet"):
print(f"Launching for fallback session: nm-applet")
self.nm_applet_proc = subprocess.Popen(["nm-applet"])
if shutil.which("csd-automount"):
print(f"Launching for fallback session: csd-automount")
self.automount_proc = subprocess.Popen(["csd-automount"])
def kill_fallback_helpers(self):
if self.polkit_agent_proc is not None:
print("Killing fallback polkit agent")
self.polkit_agent_proc.terminate()
try:
self.polkit_agent_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.polkit_agent_proc.kill()
self.polkit_agent_proc = None
if self.nm_applet_proc is not None:
print("Killing fallback nm-applet")
self.nm_applet_proc.terminate()
try:
self.nm_applet_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.nm_applet_proc.kill()
self.nm_applet_proc = None
if self.automount_proc is not None:
print("Killing fallback csd-automount")
self.automount_proc.terminate()
try:
self.automount_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
self.automount_proc.kill()
self.automount_proc = None
@async_function
def monitor_memory(self):
if psutil.pid_exists(self.cinnamon_pid):
process = psutil.Process(self.cinnamon_pid)
while True:
delay = self.settings.get_int("check-frequency")
limit = self.settings.get_int("memory-limit")
time.sleep(delay)
if not process.is_running():
break
memory = ((process.memory_full_info().rss - process.memory_full_info().shared) / 1024 ** 2)
if memory > limit:
print ("Memory threshold reached: %d" % memory)
self.log_kill(memory, limit, delay)
with self.kill_lock:
self.killed = True
process.kill()
break
def restart_cinnamon(self):
os.execvp(sys.argv[0], sys.argv)
def log_kill(self, memory, limit, delay):
try:
directory = os.path.join(GLib.get_user_state_dir(), 'cinnamon')
except AttributeError:
directory = os.path.expanduser("~/.cinnamon")
string = "%s - Usage: %d MB - Limit: %d MB - Freq: %s sec" % (time.strftime("%Y.%m.%d %H:%M:%S"), memory, limit, delay)
if not os.path.exists(directory):
os.mkdir(directory)
with open(os.path.join(directory, "restarts.log"), "a") as log_file:
print(string, file=log_file)
@idle_function
def confirm_restart(self):
self.can_restart = True
d = Gtk.MessageDialog(title=None, parent=None, flags=0, message_type=Gtk.MessageType.WARNING)
d.add_buttons(_("No"), Gtk.ResponseType.NO,
_("Yes"), Gtk.ResponseType.YES)
d.set_keep_above(True)
d.set_position(Gtk.WindowPosition.CENTER)
d.set_title(_("Cinnamon just crashed"))
box = d.get_content_area()
checkbutton = Gtk.CheckButton(label=_("Disable downloaded applets, desklets and extensions"))
d.set_markup("<span size='large'><b>%s</b></span>\n\n%s\n\n%s\n\n" %
(
_("You are currently running in fallback mode."),
_("If you suspect the source of the crash is a local extension, applet or desklet, you can disable downloaded add-ons using the checkbox below."),
_("Do you want to restart Cinnamon?"),
))
box.set_border_width(20)
box.add(checkbutton)
checkbutton.show_all()
self.dialog = d
resp = d.run()
self.dialog = None
self.can_restart = False
d.destroy()
if resp == Gtk.ResponseType.YES:
if checkbutton.get_active():
os.environ["CINNAMON_TROUBLESHOOT"] = "1"
os.system("killall %s" % panel_process_name)
self.kill_fallback_helpers()
os.system("kill %d" % self.fb_pid)
os.waitpid(self.fb_pid, 0)
self.restart_cinnamon()
else:
Gtk.main_quit()
if __name__ == "__main__":
setproctitle("cinnamon-launcher")
Launcher()