]> glassweightruler.freedombox.rocks Git - waydroid.git/blob - tools/actions/initializer.py
gpu: Also mount card node
[waydroid.git] / tools / actions / initializer.py
1 # Copyright 2021 Erfan Abdi
2 # SPDX-License-Identifier: GPL-3.0-or-later
3 import logging
4 import os
5 from tools import helpers
6 import tools.config
7
8 import sys
9 import threading
10 import multiprocessing
11 import select
12 import queue
13 import time
14 import dbus
15 import dbus.service
16 from gi.repository import GLib
17
18 def is_initialized(args):
19 return os.path.isfile(args.config) and os.path.isdir(tools.config.defaults["rootfs"])
20
21 def get_vendor_type(args):
22 vndk_str = helpers.props.host_get(args, "ro.vndk.version")
23 ret = "MAINLINE"
24 if vndk_str != "":
25 vndk = int(vndk_str)
26 if vndk > 19:
27 ret = "HALIUM_" + str(vndk - 19)
28
29 return ret
30
31 def setup_config(args):
32 cfg = tools.config.load(args)
33 args.arch = helpers.arch.host()
34 cfg["waydroid"]["arch"] = args.arch
35
36 preinstalled_images_paths = tools.config.defaults["preinstalled_images_paths"]
37 if not args.images_path:
38 for preinstalled_images in preinstalled_images_paths:
39 if os.path.isdir(preinstalled_images):
40 if os.path.isfile(preinstalled_images + "/system.img") and os.path.isfile(preinstalled_images + "/vendor.img"):
41 args.images_path = preinstalled_images
42 break
43 else:
44 logging.warning("Found directory {} but missing system or vendor image, ignoring...".format(preinstalled_images))
45
46 if not args.images_path:
47 args.images_path = tools.config.defaults["images_path"]
48 cfg["waydroid"]["images_path"] = args.images_path
49
50 channels_cfg = tools.config.load_channels()
51 if not args.system_channel:
52 args.system_channel = channels_cfg["channels"]["system_channel"]
53 if not args.vendor_channel:
54 args.vendor_channel = channels_cfg["channels"]["vendor_channel"]
55 if not args.rom_type:
56 args.rom_type = channels_cfg["channels"]["rom_type"]
57 if not args.system_type:
58 args.system_type = channels_cfg["channels"]["system_type"]
59
60 args.system_ota = args.system_channel + "/" + args.rom_type + \
61 "/waydroid_" + args.arch + "/" + args.system_type + ".json"
62 system_request = helpers.http.retrieve(args.system_ota)
63 if system_request[0] != 200:
64 if args.images_path not in preinstalled_images_paths:
65 raise ValueError(
66 "Failed to get system OTA channel: {}, error: {}".format(args.system_ota, system_request[0]))
67 else:
68 args.system_ota = "None"
69
70 device_codename = helpers.props.host_get(args, "ro.product.device")
71 args.vendor_type = None
72 for vendor in [device_codename, get_vendor_type(args)]:
73 vendor_ota = args.vendor_channel + "/waydroid_" + \
74 args.arch + "/" + vendor.replace(" ", "_") + ".json"
75 vendor_request = helpers.http.retrieve(vendor_ota)
76 if vendor_request[0] == 200:
77 args.vendor_type = vendor
78 args.vendor_ota = vendor_ota
79 break
80
81 if not args.vendor_type:
82 if args.images_path not in preinstalled_images_paths:
83 raise ValueError(
84 "Failed to get vendor OTA channel: {}".format(vendor_ota))
85 else:
86 args.vendor_ota = "None"
87 args.vendor_type = get_vendor_type(args)
88
89 if args.system_ota != cfg["waydroid"].get("system_ota"):
90 cfg["waydroid"]["system_datetime"] = tools.config.defaults["system_datetime"]
91 if args.vendor_ota != cfg["waydroid"].get("vendor_ota"):
92 cfg["waydroid"]["vendor_datetime"] = tools.config.defaults["vendor_datetime"]
93
94 cfg["waydroid"]["vendor_type"] = args.vendor_type
95 cfg["waydroid"]["system_ota"] = args.system_ota
96 cfg["waydroid"]["vendor_ota"] = args.vendor_ota
97 helpers.drivers.setupBinderNodes(args)
98 cfg["waydroid"]["binder"] = args.BINDER_DRIVER
99 cfg["waydroid"]["vndbinder"] = args.VNDBINDER_DRIVER
100 cfg["waydroid"]["hwbinder"] = args.HWBINDER_DRIVER
101 tools.config.save(args, cfg)
102
103 def init(args):
104 if not is_initialized(args) or args.force:
105 initializer_service = None
106 try:
107 initializer_service = tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer")
108 except dbus.DBusException:
109 pass
110 setup_config(args)
111 status = "STOPPED"
112 if os.path.exists(tools.config.defaults["lxc"] + "/waydroid"):
113 status = helpers.lxc.status(args)
114 if status != "STOPPED":
115 logging.info("Stopping container")
116 helpers.lxc.stop(args)
117 helpers.images.umount_rootfs(args)
118 if args.images_path not in tools.config.defaults["preinstalled_images_paths"]:
119 helpers.images.get(args)
120 if not os.path.isdir(tools.config.defaults["rootfs"]):
121 os.mkdir(tools.config.defaults["rootfs"])
122 helpers.lxc.setup_host_perms(args)
123 helpers.lxc.set_lxc_config(args)
124 helpers.lxc.make_base_props(args)
125 if status != "STOPPED":
126 logging.info("Starting container")
127 helpers.images.mount_rootfs(args, args.images_path)
128 helpers.lxc.start(args)
129
130 if "running_init_in_service" not in args or not args.running_init_in_service:
131 try:
132 if initializer_service:
133 initializer_service.Done()
134 except dbus.DBusException:
135 pass
136 else:
137 logging.info("Already initialized")
138
139 def wait_for_init(args):
140 helpers.ipc.create_channel("remote_init_output")
141
142 mainloop = GLib.MainLoop()
143 dbus_obj = DbusInitializer(mainloop, dbus.SystemBus(), '/Initializer', args)
144 mainloop.run()
145
146 # After init
147 dbus_obj.remove_from_connection()
148
149 class DbusInitializer(dbus.service.Object):
150 def __init__(self, looper, bus, object_path, args):
151 self.args = args
152 self.looper = looper
153 dbus.service.Object.__init__(self, bus, object_path)
154
155 @dbus.service.method("id.waydro.Initializer", in_signature='a{ss}', out_signature='', sender_keyword="sender", connection_keyword="conn")
156 def Init(self, params, sender=None, conn=None):
157 channels_cfg = tools.config.load_channels()
158 no_auth = params["system_channel"] == channels_cfg["channels"]["system_channel"] and \
159 params["vendor_channel"] == channels_cfg["channels"]["vendor_channel"]
160 if no_auth or ensure_polkit_auth(sender, conn, "id.waydro.Initializer.Init"):
161 threading.Thread(target=remote_init_server, args=(self.args, params)).start()
162 else:
163 raise PermissionError("Polkit: Authentication failed")
164
165 @dbus.service.method("id.waydro.Initializer", in_signature='', out_signature='')
166 def Done(self):
167 if is_initialized(self.args):
168 self.looper.quit()
169
170 def ensure_polkit_auth(sender, conn, privilege):
171 dbus_info = dbus.Interface(conn.get_object("org.freedesktop.DBus", "/org/freedesktop/DBus/Bus", False), "org.freedesktop.DBus")
172 pid = dbus_info.GetConnectionUnixProcessID(sender)
173 polkit = dbus.Interface(dbus.SystemBus().get_object("org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", False), "org.freedesktop.PolicyKit1.Authority")
174 try:
175 (is_auth, _, _) = polkit.CheckAuthorization(
176 ("unix-process", {
177 "pid": dbus.UInt32(pid, variant_level=1),
178 "start-time": dbus.UInt64(0, variant_level=1)}),
179 privilege, {"AllowUserInteraction": "true"},
180 dbus.UInt32(1),
181 "",
182 timeout=300)
183 return is_auth
184 except dbus.DBusException:
185 raise PermissionError("Polkit: Authentication timed out")
186
187 def background_remote_init_process(args):
188 with helpers.ipc.open_channel("remote_init_output", "wb") as channel_out:
189 class StdoutRedirect(logging.StreamHandler):
190 def write(self, s):
191 channel_out.write(str.encode(s))
192 def flush(self):
193 pass
194 def emit(self, record):
195 if record.levelno >= logging.INFO:
196 self.write(self.format(record) + self.terminator)
197
198 out = StdoutRedirect()
199 sys.stdout = sys.stderr = out
200 logging.getLogger().addHandler(out)
201
202 ctl_queue = queue.Queue()
203 def try_init(args):
204 try:
205 init(args)
206 except Exception as e:
207 print(str(e))
208 finally:
209 ctl_queue.put(0)
210
211 def poll_pipe():
212 poller = select.poll()
213 poller.register(channel_out, select.POLLERR)
214 poller.poll()
215 # When reaching here the client was terminated
216 ctl_queue.put(0)
217
218 init_thread = threading.Thread(target=try_init, args=(args,))
219 init_thread.daemon = True
220 init_thread.start()
221
222 poll_thread = threading.Thread(target=poll_pipe)
223 poll_thread.daemon = True
224 poll_thread.start()
225
226 # Join any one of the two threads
227 # Then exit the subprocess to kill the remaining thread.
228 # Can you believe this is the only way to kill a thread in python???
229 ctl_queue.get()
230
231 sys.stdout = sys.__stdout__
232 sys.stderr = sys.__stderr__
233 logging.getLogger().removeHandler(out)
234
235 def remote_init_server(args, params):
236 args.force = True
237 args.images_path = ""
238 args.rom_type = ""
239 args.system_channel = params["system_channel"]
240 args.vendor_channel = params["vendor_channel"]
241 args.system_type = params["system_type"]
242 args.running_init_in_service = True
243
244 p = multiprocessing.Process(target=background_remote_init_process, args=(args,))
245 p.daemon = True
246 p.start()
247 p.join()
248
249 def remote_init_client(args):
250 # Local imports cause Gtk is intrusive
251 import gi
252 gi.require_version("Gtk", "3.0")
253 from gi.repository import Gtk
254
255 bus = dbus.SystemBus()
256
257 if is_initialized(args):
258 try:
259 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
260 except dbus.DBusException:
261 pass
262 return
263
264 def notify_and_quit(caller):
265 if is_initialized(args):
266 try:
267 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Done()
268 except dbus.DBusException:
269 pass
270 GLib.idle_add(Gtk.main_quit)
271
272 class WaydroidInitWindow(Gtk.Window):
273 def __init__(self):
274 super().__init__(title="Initialize Waydroid")
275 channels_cfg = tools.config.load_channels()
276
277 self.set_default_size(600, 250)
278 self.set_icon_from_file(tools.config.tools_src + "/data/AppIcon.png")
279
280 grid = Gtk.Grid(row_spacing=6, column_spacing=6, margin=10, column_homogeneous=True)
281 grid.set_hexpand(True)
282 grid.set_vexpand(True)
283 self.add(grid)
284
285 sysOtaLabel = Gtk.Label("System OTA")
286 sysOtaEntry = Gtk.Entry()
287 sysOtaEntry.set_text(channels_cfg["channels"]["system_channel"])
288 grid.attach(sysOtaLabel, 0, 0, 1, 1)
289 grid.attach_next_to(sysOtaEntry ,sysOtaLabel, Gtk.PositionType.RIGHT, 2, 1)
290 self.sysOta = sysOtaEntry.get_buffer()
291
292 vndOtaLabel = Gtk.Label("Vendor OTA")
293 vndOtaEntry = Gtk.Entry()
294 vndOtaEntry.set_text(channels_cfg["channels"]["vendor_channel"])
295 grid.attach(vndOtaLabel, 0, 1, 1, 1)
296 grid.attach_next_to(vndOtaEntry, vndOtaLabel, Gtk.PositionType.RIGHT, 2, 1)
297 self.vndOta = vndOtaEntry.get_buffer()
298
299 sysTypeLabel = Gtk.Label("Android Type")
300 sysTypeCombo = Gtk.ComboBoxText()
301 sysTypeCombo.set_entry_text_column(0)
302 for t in ["VANILLA", "GAPPS"]:
303 sysTypeCombo.append_text(t)
304 sysTypeCombo.set_active(0)
305 grid.attach(sysTypeLabel, 0, 2, 1, 1)
306 grid.attach_next_to(sysTypeCombo, sysTypeLabel, Gtk.PositionType.RIGHT, 2, 1)
307 self.sysType = sysTypeCombo
308
309 downloadBtn = Gtk.Button("Download")
310 downloadBtn.connect("clicked", self.on_download_btn_clicked)
311 grid.attach(downloadBtn, 1,3,1,1)
312 self.downloadBtn = downloadBtn
313
314 doneBtn = Gtk.Button("Done")
315 doneBtn.connect("clicked", lambda x: self.destroy())
316 doneBtn.get_style_context().add_class('suggested-action')
317 grid.attach_next_to(doneBtn, downloadBtn, Gtk.PositionType.RIGHT, 1, 1)
318 self.doneBtn = doneBtn
319
320 outScrolledWindow = Gtk.ScrolledWindow()
321 outScrolledWindow.set_hexpand(True)
322 outScrolledWindow.set_vexpand(True)
323 outTextView = Gtk.TextView()
324 outTextView.set_property('editable', False)
325 outTextView.set_property('cursor-visible', False)
326 outScrolledWindow.add(outTextView)
327 grid.attach(outScrolledWindow, 0, 4, 3, 1)
328 self.outScrolledWindow = outScrolledWindow
329 self.outTextView = outTextView
330 self.outBuffer = outTextView.get_buffer()
331 self.outBuffer.create_mark("end", self.outBuffer.get_end_iter(), False)
332
333 self.open_channel = None
334
335 def scroll_to_bottom(self):
336 self.outTextView.scroll_mark_onscreen(self.outBuffer.get_mark("end"))
337
338 def on_download_btn_clicked(self, widget):
339 widget.set_sensitive(False)
340 self.doneBtn.hide()
341 self.outTextView.show()
342 init_params = (self.sysOta.get_text(), self.vndOta.get_text(), self.sysType.get_active_text())
343 init_runner = threading.Thread(target=self.run_init, args=init_params)
344 init_runner.daemon = True
345 init_runner.start()
346
347 def run_init(self, systemOta, vendorOta, systemType):
348 def draw_sync(s):
349 if s.startswith('\r'):
350 last = self.outBuffer.get_iter_at_line(self.outBuffer.get_line_count()-1)
351 last.backward_char()
352 self.outBuffer.delete(last, self.outBuffer.get_end_iter())
353 self.outBuffer.insert(self.outBuffer.get_end_iter(), s)
354 self.scroll_to_bottom()
355 def draw(s):
356 GLib.idle_add(draw_sync, s)
357
358 if self.open_channel is not None:
359 self.open_channel.close()
360 # Wait for other end to reset
361 time.sleep(1)
362
363 draw("Waiting for waydroid container service...\n")
364 try:
365 params = {
366 "system_channel": self.sysOta.get_text(),
367 "vendor_channel": self.vndOta.get_text(),
368 "system_type": self.sysType.get_active_text()
369 }
370 tools.helpers.ipc.DBusContainerService("/Initializer", "id.waydro.Initializer").Init(params, timeout=310)
371 except dbus.DBusException as e:
372 if e.get_dbus_name() == "org.freedesktop.DBus.Python.PermissionError":
373 draw(e.get_dbus_message().splitlines()[-1] + "\n")
374 else:
375 draw("The waydroid container service is not listening\n")
376 GLib.idle_add(self.downloadBtn.set_sensitive, True)
377 return
378
379 with helpers.ipc.open_channel("remote_init_output", "rb") as channel:
380 self.open_channel = channel
381 GLib.idle_add(self.downloadBtn.set_sensitive, True)
382 line = ""
383 try:
384 while True:
385 data = channel.read(1)
386 if len(data) == 0:
387 draw(line)
388 break
389 c = data.decode()
390 if c == '\r':
391 draw(line)
392 line = c
393 else:
394 line += c
395 if c == '\n':
396 draw(line)
397 line = ""
398 except:
399 draw("\nInterrupted\n")
400
401 if is_initialized(args):
402 GLib.idle_add(self.doneBtn.show)
403 draw("Done\n")
404
405
406 GLib.set_prgname("Waydroid")
407 win = WaydroidInitWindow()
408 win.connect("destroy", notify_and_quit)
409
410 win.show_all()
411 win.outTextView.hide()
412 win.doneBtn.hide()
413
414 Gtk.main()