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