-
Notifications
You must be signed in to change notification settings - Fork 49
/
ImageManager.py
1821 lines (1663 loc) · 88.1 KB
/
ImageManager.py
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from urllib.parse import urlparse
from urllib.request import urlopen
import json
import tempfile
import struct
from enigma import eTimer, fbClass
from os import path, stat, system, mkdir, makedirs, listdir, remove, rename, rmdir, sep as ossep, statvfs, chmod, walk
from shutil import copy, copyfile, move, rmtree
from time import localtime, time, strftime, mktime
from Components.ActionMap import ActionMap
from Components.Button import Button
from Components.ChoiceList import ChoiceList, ChoiceEntryComponent
from Components.config import config, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigText, ConfigNumber, NoSave, ConfigClock, configfile
from Components.Console import Console
from Components.Harddisk import harddiskmanager, getProcMounts
from Components.Label import Label
from Components.MenuList import MenuList
from Components.Sources.StaticText import StaticText
from Components.SystemInfo import SystemInfo
import Components.Task
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Setup import Setup
from Screens.Standby import TryQuitMainloop
from Screens.TaskView import JobView
from Screens.TextBox import TextBox
from Tools.Directories import fileExists, pathExists, fileHas
import Tools.CopyFiles
from Tools.HardwareInfo import HardwareInfo
from Tools.Multiboot import GetImagelist
from Tools.Notifications import AddPopupWithCallback
def getMountChoices():
choices = []
for p in harddiskmanager.getMountedPartitions():
if path.exists(p.mountpoint):
d = path.normpath(p.mountpoint)
entry = (p.mountpoint, d)
if p.mountpoint != "/" and entry not in choices:
choices.append(entry)
choices.sort()
return choices
def getMountDefault(choices):
choices = {x[1]: x[0] for x in choices}
default = choices.get("/media/hdd") or choices.get("/media/usb")
return default
def __onPartitionChange(*args, **kwargs):
global choices
choices = getMountChoices()
config.imagemanager.backuplocation.setChoices(choices=choices, default=getMountDefault(choices))
defaultprefix = SystemInfo["distro"]
config.imagemanager = ConfigSubsection()
config.imagemanager.autosettingsbackup = ConfigYesNo(default=True)
choices = getMountChoices()
config.imagemanager.backuplocation = ConfigSelection(choices=choices, default=getMountDefault(choices))
config.imagemanager.extensive_location_search = ConfigYesNo(default=False)
harddiskmanager.on_partition_list_change.append(__onPartitionChange) # to update backuplocation choices on mountpoint change
config.imagemanager.backupretry = ConfigNumber(default=30)
config.imagemanager.backupretrycount = NoSave(ConfigNumber(default=0))
config.imagemanager.folderprefix = ConfigText(default=defaultprefix, fixed_size=False)
config.imagemanager.nextscheduletime = NoSave(ConfigNumber(default=0))
config.imagemanager.repeattype = ConfigSelection(default="daily", choices=[("daily", _("Daily")), ("weekly", _("Weekly")), ("monthly", _("30 Days"))])
config.imagemanager.schedule = ConfigYesNo(default=False)
config.imagemanager.scheduletime = ConfigClock(default=0) # 1:00
config.imagemanager.query = ConfigYesNo(default=True)
config.imagemanager.lastbackup = ConfigNumber(default=0)
config.imagemanager.number_to_keep = ConfigNumber(default=0)
# Add a method for users to download images directly from their own build servers.
# Script must be able to handle urls in the form http://domain/scriptname/boxname.
# Format of the JSON output from the script must be the same as the official urls above.
# The option will only show once a url has been added.
config.imagemanager.imagefeed_MyBuild = ConfigText(default="", fixed_size=False)
config.imagemanager.login_as_OpenBh_developer = ConfigYesNo(default=False)
config.imagemanager.developer_username = ConfigText(default="username", fixed_size=False)
config.imagemanager.developer_password = ConfigText(default="password", fixed_size=False)
DISTRO = 0
URL = 1
ACTION = 2
if SystemInfo["imagetype"] == "release":
FEED_URLS = [
("OpenBh", "https://images.openbh.net/json/%s", "getMachineMake"),
("OpenViX", "https://www.openvix.co.uk/json/%s", "getMachineMake"),
("OpenATV", "https://images.mynonpublic.com/openatv/json/%s", "getMachineMake"),
("OpenPLi", "http://downloads.openpli.org/json/%s", "HardwareInfo"),
]
elif SystemInfo["imagetype"] == "community":
FEED_URLS = [
("OpenBh", "https://images.blackhole-community.com/json/%s", "getMachineMake"),
("OpenViX", "https://www.openvix.co.uk/json/%s", "getMachineMake"),
("OpenATV", "https://images.mynonpublic.com/openatv/json/%s", "getMachineMake"),
("OpenPLi", "http://downloads.openpli.org/json/%s", "HardwareInfo"),
]
autoImageManagerTimer = None
if path.exists(config.imagemanager.backuplocation.value + "imagebackups/imagerestore"):
try:
rmtree(config.imagemanager.backuplocation.value + "imagebackups/imagerestore")
except Exception:
pass
TMPDIR = config.imagemanager.backuplocation.value + "imagebackups/" + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-mount"
if path.exists(TMPDIR + "/root") and path.ismount(TMPDIR + "/root"):
try:
system("umount " + TMPDIR + "/root")
except Exception:
pass
def ImageManagerautostart(reason, session=None, **kwargs):
"""called with reason=1 to during /sbin/shutdown.sysvinit, with reason=0 at startup?"""
global autoImageManagerTimer
global _session
if reason == 0:
print("[ImageManager] AutoStart Enabled")
if session is not None:
_session = session
if autoImageManagerTimer is None:
autoImageManagerTimer = AutoImageManagerTimer(session)
else:
if autoImageManagerTimer is not None:
print("[ImageManager] Stop")
autoImageManagerTimer.stop()
class tmp:
dir = None
def checkImageFiles(files):
return len([x for x in files if "kernel" in x and ".bin" in x or x in ("zImage", "uImage", "root_cfe_auto.bin", "root_cfe_auto.jffs2", "oe_kernel.bin", "oe_rootfs.bin", "e2jffs2.img", "rootfs.tar.bz2", "rootfs.ubi", "rootfs.bin")]) >= 2
BackupTime = 0
class OpenBhImageManager(Screen):
skin = ["""<screen name="OpenBhImageManager" position="center,center" size="%d,%d">
<ePixmap pixmap="skin_default/buttons/red.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/yellow.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/blue.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<widget name="key_red" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/>
<widget name="key_green" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/>
<widget name="key_yellow" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/>
<widget name="key_blue" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#18188b" transparent="1"/>
<ePixmap pixmap="skin_default/buttons/key_menu.png" position="%d,%d" size="%d,%d" alphatest="blend" transparent="1" zPosition="3" scale="1" />
<widget name="lab1" position="%d,%d" size="%d,%d" font="Regular; %d" zPosition="2" transparent="0" halign="center"/>
<widget name="list" position="%d,%d" size="%d,%d" font="Regular;%d" scrollbarMode="showOnDemand"/>
<widget name="backupstatus" position="%d,%d" size="%d,%d" font="Regular;%d" zPosition="5"/>
<applet type="onLayoutFinish">
self["list"].instance.setItemHeight(%d)
</applet>
</screen>""",
560, 400, # screen
0, 0, 140, 40, # colors
140, 0, 140, 40,
280, 0, 140, 40,
420, 0, 140, 40,
0, 0, 140, 40, 20,
140, 0, 140, 40, 20,
280, 0, 140, 40, 20,
420, 0, 140, 40, 20,
0, 45, 35, 25, # menu key
0, 50, 560, 50, 18, # lab1
10, 105, 540, 260, 20, # list
10, 370, 400, 30, 20, # backupstatus
26,
] # noqa: E124
def __init__(self, session):
Screen.__init__(self, session)
self.setTitle(_("Image manager"))
self["lab1"] = Label()
self["backupstatus"] = Label()
self["key_red"] = Button(_("Delete"))
self["key_green"] = Button("Full Backup")
self["key_yellow"] = Button(_("Downloads"))
self["key_blue"] = Button(_("Flash"))
self["key_menu"] = StaticText(_("MENU"))
self["key_info"] = StaticText(_("INFO"))
self["infoactions"] = ActionMap(["SetupActions"], {
"info": self.showInfo,
}, -1)
self["defaultactions"] = ActionMap(["OkCancelActions", "MenuActions"], {
"cancel": self.close,
"menu": self.createSetup,
}, -1)
self["mainactions"] = ActionMap(["ColorActions", "OkCancelActions", "DirectionActions", "KeyboardInputActions"], {
"red": self.keyDelete,
"green": self.GreenPressed,
"yellow": self.doDownload,
"ok": self.keyRestore,
"blue": self.keyRestore,
"up": self.refreshUp,
"down": self.refreshDown,
"left": self.keyLeft,
"right": self.keyRight,
"upRepeated": self.refreshUp,
"downRepeated": self.refreshDown,
"leftRepeated": self.keyLeft,
"rightRepeated": self.keyRight,
}, -1)
self["mainactions"].setEnabled(False)
self.BackupRunning = False
self.mountAvailable = False
self.BackupDirectory = " "
if SystemInfo["canMultiBoot"]:
self.mtdboot = SystemInfo["MBbootdevice"]
self.onChangedEntry = []
if choices:
self["list"] = MenuList(list=[((_("No images found on the selected download server...if password check validity")), "Waiter")])
else:
self["list"] = MenuList(list=[((_(" Press 'Menu' to select a storage device - none available")), "Waiter")])
self["key_red"].hide()
self["key_green"].hide()
self["key_yellow"].hide()
self["key_blue"].hide()
self.populate_List()
self.activityTimer = eTimer()
self.activityTimer.timeout.get().append(self.backupRunning)
self.activityTimer.startLongTimer(10)
self.Console = Console()
self.ConsoleB = Console(binary=True)
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next backup: ")
self["backupstatus"].setText(str(backuptext))
if self.selectionChanged not in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import PluginBrowserSummary
return PluginBrowserSummary
def selectionChanged(self):
item = self["list"].getCurrent() # (name, link)
desc = self["backupstatus"].text
if item:
name = item[0]
else:
name = ""
for cb in self.onChangedEntry:
cb(name, desc)
def backupRunning(self):
self.BackupRunning = False
if self.mountAvailable:
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image manager")):
self.BackupRunning = True
break
if self.BackupRunning:
self["key_green"].setText(_("View progress"))
else:
self["key_green"].setText(_("Full backup"))
self["key_green"].show()
else:
self["key_green"].hide()
self.activityTimer.startLongTimer(5)
self.refreshList() # display any new images that may have been sent too the box since the list was built
def refreshUp(self):
self["list"].moveUp()
def refreshDown(self):
self["list"].moveDown()
def keyLeft(self):
self["list"].pageUp()
self.selectionChanged()
def keyRight(self):
self["list"].pageDown()
self.selectionChanged()
def refreshList(self):
if self.BackupDirectory == " ":
return
imglist = []
imagesDownloadedList = self.getImagesDownloaded()
for image in imagesDownloadedList:
imglist.append((image["name"], image["link"]))
if imglist:
self["key_red"].show()
self["key_blue"].show()
else:
self["key_red"].hide()
self["key_blue"].hide()
self["list"].setList(imglist)
self["list"].show()
self.selectionChanged()
def getJobName(self, job):
return "%s: %s (%d%%)" % (job.getStatustext(), job.name, int(100 * job.progress / float(job.end)))
def showJobView(self, job):
Components.Task.job_manager.in_background = False
self.session.openWithCallback(self.JobViewCB, JobView, job, cancelable=False, backgroundable=True, afterEventChangeable=False, afterEvent="close")
def JobViewCB(self, in_background):
Components.Task.job_manager.in_background = in_background
def populate_List(self):
if config.imagemanager.backuplocation.value.endswith("/"):
mount = config.imagemanager.backuplocation.value, config.imagemanager.backuplocation.value[:-1]
else:
mount = config.imagemanager.backuplocation.value + "/", config.imagemanager.backuplocation.value
hdd = "/media/hdd/", "/media/hdd"
if mount not in config.imagemanager.backuplocation.choices.choices and hdd not in config.imagemanager.backuplocation.choices.choices:
self["mainactions"].setEnabled(False)
self.mountAvailable = False
self["key_green"].hide()
self["lab1"].setText(_("Device: None available") + "\n" + _("Press 'Menu' to select a storage device"))
else:
if mount not in config.imagemanager.backuplocation.choices.choices:
self.BackupDirectory = "/media/hdd/imagebackups/"
config.imagemanager.backuplocation.value = "/media/hdd/"
config.imagemanager.backuplocation.save()
self["lab1"].setText(_("The chosen location does not exist, using /media/hdd.") + "\n" + _("Select an image to flash."))
else:
self.BackupDirectory = config.imagemanager.backuplocation.value + "imagebackups/"
s = statvfs(config.imagemanager.backuplocation.value)
free = (s.f_bsize * s.f_bavail) // (1024 * 1024)
self["lab1"].setText(_("Device: ") + config.imagemanager.backuplocation.value + " " + _("Free space:") + " " + str(free) + _("MB") + "\n" + _("Select an image to flash."))
try:
if not path.exists(self.BackupDirectory):
mkdir(self.BackupDirectory, 0o755)
if path.exists(self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-swapfile_backup"):
system("swapoff " + self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-swapfile_backup")
remove(self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-swapfile_backup")
self.refreshList()
except Exception:
self["lab1"].setText(_("Device: ") + config.imagemanager.backuplocation.value + "\n" + _("There is a problem with this device. Please reformat it and try again."))
self["mainactions"].setEnabled(True)
self.mountAvailable = True
self["key_green"].show()
def createSetup(self):
self.session.openWithCallback(self.setupDone, ImageManagerSetup)
def doDownload(self):
choices = [(x[DISTRO], x) for x in FEED_URLS]
message = _("From which image library do you want to download?")
self.session.openWithCallback(self.doDownloadCallback, MessageBox, message, list=choices, default=1, simple=True)
def doDownloadCallback(self, retval): # retval will be the config element (or False, in the case of aborting the MessageBox).
if retval:
self.session.openWithCallback(self.refreshList, ImageManagerDownload, self.BackupDirectory, retval)
def setupDone(self, retval=None):
self.populate_List()
self.doneConfiguring()
def doneConfiguring(self):
now = int(time())
if config.imagemanager.schedule.value:
if autoImageManagerTimer is not None:
print("[ImageManager] Backup Schedule Enabled at", strftime("%c", localtime(now)))
autoImageManagerTimer.backupupdate()
else:
if autoImageManagerTimer is not None:
global BackupTime
BackupTime = 0
print("[ImageManager] Backup Schedule Disabled at", strftime("%c", localtime(now)))
autoImageManagerTimer.backupstop()
if BackupTime > 0:
t = localtime(BackupTime)
backuptext = _("Next backup: ") + strftime(_("%a %e %b %-H:%M"), t)
else:
backuptext = _("Next backup: ")
self["backupstatus"].setText(str(backuptext))
def keyDelete(self):
self.sel = self["list"].getCurrent() # (name, link)
if self.sel is not None:
self["list"].moveToIndex(self["list"].getSelectionIndex() if len(self["list"].list) > self["list"].getSelectionIndex() + 1 else max(len(self["list"].list) - 2, 0)) # hold the selection current possition if the list is long enough, else go to last item
try:
# print("[ImageManager][keyDelete] selected image=%s" % (self.sel[1]))
if self.sel[1].endswith(".zip"):
remove(self.sel[1])
else:
rmtree(self.sel[1])
except:
self.session.open(MessageBox, _("Delete failure - check device available."), MessageBox.TYPE_INFO, timeout=10)
self.refreshList()
def GreenPressed(self):
backup = None
self.BackupRunning = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image manager")):
backup = job
self.BackupRunning = True
if self.BackupRunning and backup:
self.showJobView(backup)
else:
self.keyBackup()
def keyBackup(self):
if SystemInfo["boxtype"] == "dual":
message = _("Do you want to create a full image backup?\nThis can take upto 25 minutes to complete.")
else:
message = _("Do you want to create a full image backup?\nThis can take about 6 minutes to complete.")
ybox = self.session.openWithCallback(self.doBackup, MessageBox, message, MessageBox.TYPE_YESNO)
ybox.setTitle(_("Backup confirmation"))
def doBackup(self, answer):
if answer is True:
self.ImageBackup = ImageBackup(self.session)
Components.Task.job_manager.AddJob(self.ImageBackup.createBackupJob())
self.BackupRunning = True
self["key_green"].setText(_("View progress"))
self["key_green"].show()
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Image manager")):
break
self.showJobView(job)
def getImagesDownloaded(self):
def getImages(files):
for file in files:
imagesFound.append({'link': file, 'name': file.split(ossep)[-1], 'mtime': stat(file).st_mtime})
def checkMachineNameInFilename(filename):
return model in filename or "-" + device_name + "-" in filename
model = SystemInfo["machinebuild"]
device_name = HardwareInfo().get_device_name()
imagesFound = []
if config.imagemanager.extensive_location_search.value:
mediaList = ['/media/%s' % x for x in listdir('/media')] + (['/media/net/%s' % x for x in listdir('/media/net')] if path.isdir('/media/net') else []) + (['/media/autofs/%s' % x for x in listdir('/media/autofs')] if path.isdir('/media/autofs') else [])
else:
mediaList = [config.imagemanager.backuplocation.value]
for media in mediaList:
try: # /media/autofs/xxx will crash listdir if "xxx" is inactive (e.g. dropped network link). os.access reports True for "xxx" so it seems we are forced to try/except here.
medialist = listdir(media)
except FileNotFoundError:
continue
getImages([path.join(media, x) for x in medialist if path.splitext(x)[1] == ".zip" and checkMachineNameInFilename(x)])
for folder in ["imagebackups", "downloaded_images", "images"]:
if folder in medialist:
media2 = path.join(media, folder)
if path.isdir(media2) and not path.islink(media2) and not path.ismount(media2):
getImages([path.join(media2, x) for x in listdir(media2) if path.splitext(x)[1] == ".zip" and checkMachineNameInFilename(x)])
imagesFound.sort(key=lambda x: x['mtime'], reverse=True)
# print("[ImageManager][getImagesDownloaded] imagesFound=%s" % imagesFound)
return imagesFound
def doSettingsBackup(self):
from Plugins.SystemPlugins.OBH.BackupManager import BackupFiles
self.BackupFiles = BackupFiles(self.session, backuptype=BackupFiles.TYPE_IMAGEMANAGER)
Components.Task.job_manager.AddJob(self.BackupFiles.createBackupJob())
Components.Task.job_manager.in_background = False
for job in Components.Task.job_manager.getPendingJobs():
if job.name.startswith(_("Backup manager")):
break
self.session.openWithCallback(self.keyRestore3, JobView, job, cancelable=False, backgroundable=False, afterEventChangeable=False, afterEvent="close")
def keyRestore(self):
self.sel = self["list"].getCurrent() # (name, link)
if not self.sel:
return
print("[ImageManager][keyRestore] self.sel SystemInfo['MultiBootSlot']", self.sel[0], " ", SystemInfo["MultiBootSlot"])
if SystemInfo["MultiBootSlot"] == 0 and self.isVuKexecCompatibleImage(self.sel[0]): # only if Vu multiboot has been enabled and the image is compatible
message = [_("Are you sure you want to overwrite the Recovery image?")]
if "VuSlot0" in self.sel[0]:
callback = self.keyRestoreVuSlot0Image
message.append(_("This change will overwrite all eMMC Slots."))
choices = None
else:
callback = self.keyRestorez0
message.append(_("We advise flashing the new image to a Regular MultiBoot Slot and restoring a settings backup."))
message.append(_("Select 'Flash Regular Slot' to flash a Regular MultiBoot Slot or select 'Overwrite Recovery' to overwrite the Recovery image."))
choices = [(_("Flash Regular Slot"), False), (_("Overwrite Recovery"), True)]
ybox = self.session.openWithCallback(self.keyRestorez0, MessageBox, "\n".join(message), default=False, list=choices)
ybox.setTitle(_("Restore confirmation"))
else:
self.keyRestore1()
def keyRestoreVuSlot0Image(self, retval):
if retval:
self.keyRestorez1(retval=False)
def keyRestorez0(self, retval):
print("[ImageManager][keyRestorez0] retval", retval)
if retval:
message = (_("Do you want to backup eMMC Slots?\nThis will take 1 -> 5 minutes per eMMC Slot"))
ybox = self.session.openWithCallback(self.keyRestorez1, MessageBox, message, default=False)
ybox.setTitle(_("Copy eMMC slots confirmation"))
else:
self.keyRestore1()
def keyRestorez1(self, retval):
if retval:
self.VuKexecCopyimage()
else:
self.multibootslot = 0 # set slot0 to be flashed
self.Console.ePopen("umount /proc/cmdline", self.keyRestore3) # tell ofgwrite not Vu Multiboot
def keyRestore1(self):
self.HasSDmmc = False
self.multibootslot = 1
self.MTDKERNEL = SystemInfo["mtdkernel"]
self.MTDROOTFS = SystemInfo["mtdrootfs"]
recordings = self.session.nav.getRecordings()
if not recordings:
next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime()
if recordings or (next_rec_time > 0 and (next_rec_time - time()) < 360):
message = _("Recording(s) are in progress or coming up in few seconds!\nDo you still want to flash image\n%s?") % self.sel[0]
else:
message = _("Do you want to flash image\n%s") % self.sel[0]
if SystemInfo["canMultiBoot"] is False:
if config.imagemanager.autosettingsbackup.value:
self.doSettingsBackup()
else:
self.keyRestore3()
if SystemInfo["HasHiSi"]:
if pathExists("/dev/sda4"):
self.HasSDmmc = True
imagedict = GetImagelist()
choices = []
currentimageslot = SystemInfo["MultiBootSlot"]
for x in imagedict.keys():
choices.append(((_("slot%s %s - %s (current image)") if x == currentimageslot else _("slot%s %s - %s")) % (x, SystemInfo["canMultiBoot"][x]["slotname"], imagedict[x]["imagename"]), (x)))
self.session.openWithCallback(self.keyRestore2, MessageBox, message, list=choices, default=False, simple=True)
def keyRestore2(self, retval):
if retval:
if SystemInfo["canMultiBoot"]:
self.multibootslot = retval
print("ImageManager", retval)
self.MTDKERNEL = SystemInfo["canMultiBoot"][self.multibootslot]["kernel"].split("/")[2]
if SystemInfo["HasMultibootMTD"]:
self.MTDROOTFS = SystemInfo["canMultiBoot"][self.multibootslot]["root"]
else:
self.MTDROOTFS = SystemInfo["canMultiBoot"][self.multibootslot]["root"].split("/")[2]
if SystemInfo["HasHiSi"] and SystemInfo["MultiBootSlot"] > 4 and self.multibootslot < 4:
self.session.open(MessageBox, _("ImageManager - %s - cannot flash eMMC slot from sd card slot.") % SystemInfo["boxtype"], MessageBox.TYPE_INFO, timeout=10)
return
if self.sel:
if SystemInfo["MultiBootSlot"] != 0 and config.imagemanager.autosettingsbackup.value:
self.doSettingsBackup()
else:
self.keyRestore3()
else:
self.session.open(MessageBox, _("There is no image to flash."), MessageBox.TYPE_INFO, timeout=10)
def keyRestore3(self, *args, **kwargs):
self.restore_infobox = self.session.open(MessageBox, _("Please wait while the flash prepares."), MessageBox.TYPE_INFO, timeout=240, enable_input=False)
if "/media/autofs" in config.imagemanager.backuplocation.value or "/media/net" in config.imagemanager.backuplocation.value:
self.TEMPDESTROOT = tempfile.mkdtemp(prefix="imageRestore")
else:
self.TEMPDESTROOT = self.BackupDirectory + "imagerestore"
if self.sel[1].endswith(".zip"):
if not path.exists(self.TEMPDESTROOT):
mkdir(self.TEMPDESTROOT, 0o755)
self.Console.ePopen("unzip -o %s -d %s" % (self.sel[1], self.TEMPDESTROOT), self.keyRestore4)
else:
self.TEMPDESTROOT = self.sel[1]
self.keyRestore4(0, 0)
def keyRestore4(self, result, retval, extra_args=None):
if retval == 0:
self.session.openWithCallback(self.restore_infobox.close, MessageBox, _("Flash image unzip successful."), MessageBox.TYPE_INFO, timeout=4)
MAINDEST = "%s/%s" % (self.TEMPDESTROOT, SystemInfo["imagedir"])
if pathExists("%s/SDAbackup" % MAINDEST) and self.multibootslot != 1:
self.session.open(MessageBox, _("Multiboot only able to restore this backup to mmc slot1"), MessageBox.TYPE_INFO, timeout=20)
print("[ImageManager] SF8008 mmc restore to SDcard failed:\n", end=' ')
self.close()
else:
self.keyRestore6(0)
else:
self.session.openWithCallback(self.restore_infobox.close, MessageBox, _("Unzip error (also sent to any debug log):\n%s") % result, MessageBox.TYPE_INFO, timeout=20)
print("[ImageManager] unzip failed:\n", result)
self.close()
def keyRestore6(self, ret):
MAINDEST = "%s/%s" % (self.TEMPDESTROOT, SystemInfo["imagedir"])
print("[ImageManager] MAINDEST=%s" % MAINDEST)
def findImageFiles(path):
for path, subDirs, files in walk(path):
if not subDirs and files:
return checkImageFiles(files) and path
MAINDEST = findImageFiles(MAINDEST)
print("[ImageManager] FIXED MAINDEST=%s" % MAINDEST)
CMD = "/usr/bin/ofgwrite -r -k '%s'" % MAINDEST # normal non multiboot receiver
if SystemInfo["canMultiBoot"]:
if self.multibootslot == 0 and SystemInfo["HasKexecMultiboot"]: # reset Vu Multiboot slot0
kz0 = SystemInfo["mtdkernel"]
rz0 = SystemInfo["mtdrootfs"]
CMD = "/usr/bin/ofgwrite -k%s -r%s '%s'" % (kz0, rz0, MAINDEST) # slot0 treat as kernel/root only multiboot receiver
elif SystemInfo["HasHiSi"] and SystemInfo["canMultiBoot"][self.multibootslot]["rootsubdir"] is None: # sf8008 type receiver using SD card in multiboot
CMD = "/usr/bin/ofgwrite -r%s -k%s -m0 '%s'" % (self.MTDROOTFS, self.MTDKERNEL, MAINDEST)
print("[ImageManager] running commnd:%s slot = %s" % (CMD, self.multibootslot))
if fileExists("/boot/STARTUP") and fileExists("/boot/STARTUP_6"):
copyfile("/boot/STARTUP_%s" % self.multibootslot, "/boot/STARTUP")
elif SystemInfo["HasKexecMultiboot"]:
if SystemInfo["HasKexecUSB"] and "mmcblk" not in self.MTDROOTFS:
CMD = "/usr/bin/ofgwrite -r%s -kzImage -s'%s/linuxrootfs' -m%s '%s'" % (self.MTDROOTFS, SystemInfo["boxtype"][2:], self.multibootslot, MAINDEST)
else:
CMD = "/usr/bin/ofgwrite -r%s -kzImage -m%s '%s'" % (self.MTDROOTFS, self.multibootslot, MAINDEST)
print("[ImageManager] running commnd:%s slot = %s" % (CMD, self.multibootslot))
else:
CMD = "/usr/bin/ofgwrite -r -k -m%s '%s'" % (self.multibootslot, MAINDEST) # Normal multiboot
elif SystemInfo["HasH9SD"]:
if fileHas("/proc/cmdline", "root=/dev/mmcblk0p1") is True and fileExists("%s/rootfs.tar.bz2" % MAINDEST): # h9 using SD card
CMD = "/usr/bin/ofgwrite -rmmcblk0p1 '%s'" % MAINDEST
elif fileExists("%s/rootfs.ubi" % MAINDEST) and fileExists("%s/rootfs.tar.bz2" % MAINDEST): # h9 no SD card - build has both roots causes ofgwrite issue
rename("%s/rootfs.tar.bz2" % MAINDEST, "%s/xx.txt" % MAINDEST)
print("[ImageManager] running commnd:", CMD)
self.Console.ePopen(CMD, self.ofgwriteResult)
fbClass.getInstance().lock()
def ofgwriteResult(self, result, retval, extra_args=None):
fbClass.getInstance().unlock()
print("[ImageManager] ofgwrite retval :", retval)
if retval == 0:
if SystemInfo["HasHiSi"] and SystemInfo["HasRootSubdir"] is False and self.HasSDmmc is False: # sf8008 receiver 1 eMMC parition, No SD card
self.session.open(TryQuitMainloop, 2)
if SystemInfo["HasMultibootFlags"]:
print("[ImageManager] setting slot %s to flag file\n" % self.multibootslot)
with open('/dev/block/by-name/flag', 'wb') as f:
f.write(struct.pack("B", int(self.multibootslot)))
if SystemInfo["canMultiBoot"]:
print("[ImageManager] slot %s result %s\n" % (self.multibootslot, result))
tmp_dir = tempfile.mkdtemp(prefix="ImageManagerFlash")
Console().ePopen("mount %s %s" % (self.mtdboot, tmp_dir))
if pathExists(path.join(tmp_dir, "STARTUP")):
copyfile(path.join(tmp_dir, SystemInfo["canMultiBoot"][self.multibootslot]["startupfile"].replace("boxmode=12'", "boxmode=1'")), path.join(tmp_dir, "STARTUP"))
else:
self.session.open(MessageBox, _("Multiboot ERROR! - no STARTUP in boot partition."), MessageBox.TYPE_INFO, timeout=20)
Console().ePopen('umount %s' % tmp_dir)
if not path.ismount(tmp_dir):
rmdir(tmp_dir)
self.session.open(TryQuitMainloop, 2)
else:
self.session.open(TryQuitMainloop, 2)
else:
self.session.openWithCallback(self.restore_infobox.close, MessageBox, _("ofgwrite error (also sent to any debug log):\n%s") % result, MessageBox.TYPE_INFO, timeout=20)
print("[ImageManager] OFGWriteResult failed:\n", result)
def dualBoot(self):
rootfs2 = False
kernel2 = False
with open("/proc/mtd")as f:
L = f.readlines()
for x in L:
if "rootfs2" in x:
rootfs2 = True
if "kernel2" in x:
kernel2 = True
if rootfs2 and kernel2:
return True
else:
return False
def isVuKexecCompatibleImage(self, name):
retval = False
if "VuSlot0" in name:
retval = True
else:
name_split = name.split("-")
if len(name_split) > 1 and name_split[0] in ("openbh", "openvix") and name[-8:] == "_usb.zip": # "_usb.zip" only in build server images
parts = name_split[1].split(".")
if len(parts) > 1 and parts[0].isnumeric() and parts[1].isnumeric():
version = float(parts[0] + "." + parts[1])
if name_split[0] == "openbh" and version > 5.1:
retval = True
if name_split[0] == "openvix" and (version > 6.3 or version == 6.3 and len(parts) > 2 and parts[2].isnumeric() and int(parts[2]) > 2): # greater than 6.2.002
retval = True
return retval
def VuKexecCopyimage(self):
installedHDD = False
with open("/proc/mounts", "r") as fd:
lines = fd.readlines()
result = [line.strip().split(" ") for line in lines]
print("[ImageManager][VuKexecCopyimage] result", result)
for item in result:
if '/media/hdd' in item[1] and "/dev/sd" in item[0]:
installedHDD = True
break
if installedHDD and pathExists("/media/hdd"):
if not pathExists("/media/hdd/%s" % SystemInfo["boxtype"]):
mkdir("/media/hdd/%s" % SystemInfo["boxtype"])
for slotnum in range(1, 4):
if pathExists("/linuxrootfs%s" % slotnum):
if pathExists("/media/hdd/%s/linuxrootfs%s/" % (SystemInfo["boxtype"], slotnum)):
rmtree("/media/hdd/%s/linuxrootfs%s" % (SystemInfo["boxtype"], slotnum), ignore_errors=True)
Console().ePopen("cp -R /linuxrootfs%s . /media/hdd/%s/" % (slotnum, SystemInfo["boxtype"]))
if not installedHDD:
self.session.open(MessageBox, _("ImageManager - no HDD unable to backup Vu Multiboot eMMC slots"), MessageBox.TYPE_INFO, timeout=5)
self.multibootslot = 0 # set slot0 to be flashed
self.Console.ePopen("umount /proc/cmdline", self.keyRestore3) # tell ofgwrite not Vu Multiboot
def infoText(self):
# add info text sentence by sentence to make translators job easier
return " ".join([
_("FULL IMAGE BACKUP"),
"\n\n" +
_("A full image backup can be created at any time."),
"\n\n" +
_("The backup creates a snapshot of the image exactly as it is at the current instant."),
"\n\n" +
_("It allows making changes to the box with the knowledge that the box can be safely reverted back to a previous known working state."),
"\n\n" +
_("To make an image backup select GREEN from Image Manager main screen."),
"\n\n\n" +
_("IMAGE DOWNLOADS"),
"\n\n" +
_("Image Manager allows downloading images from OpenBh image server and from a range of other distros."),
"\n\n" +
_("To be able to download any image local storage must already be configured, HDD, USB or SD card (if supported), and also be selected as the 'Backup location' in Image Manager setup menu."),
"\n\n" +
_("To start a download select YELLOW from Image Manager main screen, then select the distro, and finally which image to download."),
"\n\n" +
_("The image will then be downloaded to the 'Backup location'."),
"\n\n" +
_("Please note, images are large, generally over 100 MB so downloading over a slow or unstable connection is prohibitive."),
"\n\n" +
_("Also, instead to downloading, it is possible to send a zipped image to the 'Backup location' by FTP."),
"\n\n\n" +
_("FLASHING"),
"\n\n" +
_("Before flashing an image 'Automatic settings backup' should be enabled in Image Manager setup menu."),
"\n\n" +
_("This will make a backup of the current settings and plugins which can be used later when setting up the new image in the First Install Wizard."),
"\n\n" +
_("To flash an image first select it from the list of images in the Image Manager main screen (the image will need to have already been downloaded) and then press BLUE."),
"\n\n" +
_("After confirming, an automatic backup will be made and then the image will be flashed."),
"\n\n" +
_("Upon completion the receiver will reboot and display the First Install Wizard."),
"\n\n" +
_("From here the settings backup and plugins can be restored just by selecting that option."),
"\n\n\n" +
_("RECOVERY MODE"),
"\n\n" +
_("This only applies to Vu+ 4K models."),
"\n\n" +
_("Backups of the RECOVERY image will contain a copy of all the client images."),
"\n\n" +
_("When flashing from the recovery image it is possible to flash it to the recovery slot."),
"\n\n" +
_("The new image will overwrite the previous one including any client images that were also configured, so care needs to be taken to make any full image backups (including client images) before overwriting the recovery image."),
])
def showInfo(self):
self.session.open(TextBox, self.infoText(), self.title + " - " + _("info"))
class AutoImageManagerTimer:
def __init__(self, session):
self.session = session
self.backuptimer = eTimer()
self.backuptimer.callback.append(self.BackuponTimer)
self.backupactivityTimer = eTimer()
self.backupactivityTimer.timeout.get().append(self.backupupdatedelay)
now = int(time())
global BackupTime
if config.imagemanager.schedule.value:
print("[ImageManager] Backup Schedule Enabled at ", strftime("%c", localtime(now)))
if now > 1262304000:
self.backupupdate()
else:
print("[ImageManager] Backup Time not yet set.")
BackupTime = 0
self.backupactivityTimer.start(36000)
else:
BackupTime = 0
print("[ImageManager] Backup Schedule Disabled at", strftime("(now=%c)", localtime(now)))
self.backupactivityTimer.stop()
def backupupdatedelay(self):
self.backupactivityTimer.stop()
self.backupupdate()
def getBackupTime(self):
backupclock = config.imagemanager.scheduletime.value
#
# Work out the time of the *NEXT* backup - which is the configured clock
# time on the nth relevant day after the last recorded backup day.
# The last backup time will have been set as 12:00 on the day it
# happened. All we use is the actual day from that value.
#
lastbkup_t = int(config.imagemanager.lastbackup.value)
if config.imagemanager.repeattype.value == "daily":
nextbkup_t = lastbkup_t + 24 * 3600
elif config.imagemanager.repeattype.value == "weekly":
nextbkup_t = lastbkup_t + 7 * 24 * 3600
elif config.imagemanager.repeattype.value == "monthly":
nextbkup_t = lastbkup_t + 30 * 24 * 3600
nextbkup = localtime(nextbkup_t)
return int(mktime((nextbkup.tm_year, nextbkup.tm_mon, nextbkup.tm_mday, backupclock[0], backupclock[1], 0, nextbkup.tm_wday, nextbkup.tm_yday, nextbkup.tm_isdst)))
def backupupdate(self, atLeast=0):
self.backuptimer.stop()
global BackupTime
BackupTime = self.getBackupTime()
now = int(time())
if BackupTime > 0:
if BackupTime < now + atLeast:
self.backuptimer.startLongTimer(60) # Backup missed - run it 60s from now
print("[ImageManager] Backup Time overdue - running in 60s")
else:
delay = BackupTime - now # Backup in future - set the timer...
self.backuptimer.startLongTimer(delay)
else:
BackupTime = -1
print("[ImageManager] Backup Time set to", strftime("%c", localtime(BackupTime)), strftime("(now=%c)", localtime(now)))
return BackupTime
def backupstop(self):
self.backuptimer.stop()
def BackuponTimer(self):
self.backuptimer.stop()
now = int(time())
wake = self.getBackupTime()
# If we're close enough, we're okay...
if wake - now < 60:
print("[ImageManager] Backup onTimer occured at", strftime("%c", localtime(now)))
from Screens.Standby import inStandby
if not inStandby and config.imagemanager.query.value:
if SystemInfo["boxtype"] == "dual":
message = _("Your %s %s is about to create a full image backup, this can take upto 25 minutes to complete.\nDo you want to allow this?") % (SystemInfo["displaybrand"], SystemInfo["machinename"])
else:
message = _("Your %s %s is about to create a full image backup, this can take about 6 minutes to complete.\nDo you want to allow this?") % (SystemInfo["displaybrand"], SystemInfo["machinename"])
ybox = self.session.openWithCallback(self.doBackup, MessageBox, message, MessageBox.TYPE_YESNO, timeout=30)
ybox.setTitle("Scheduled backup.")
else:
print("[ImageManager] in Standby or no querying, so just running backup", strftime("%c", localtime(now)))
self.doBackup(True)
else:
print("[ImageManager] We are not close enough", strftime("%c", localtime(now)))
self.backupupdate(60)
def doBackup(self, answer):
now = int(time())
if answer is False:
if config.imagemanager.backupretrycount.value < 2:
print("[ImageManager] Number of retries", config.imagemanager.backupretrycount.value)
print("[ImageManager] Backup delayed.")
repeat = config.imagemanager.backupretrycount.value
repeat += 1
config.imagemanager.backupretrycount.setValue(repeat)
BackupTime = now + (int(config.imagemanager.backupretry.value) * 60)
print("[ImageManager] Backup Time now set to", strftime("%c", localtime(BackupTime)), strftime("(now=%c)", localtime(now)))
self.backuptimer.startLongTimer(int(config.imagemanager.backupretry.value) * 60)
else:
atLeast = 60
print("[ImageManager] Enough Retries, delaying till next schedule.", strftime("%c", localtime(now)))
self.session.open(MessageBox, _("Enough retries, delaying till next schedule."), MessageBox.TYPE_INFO, timeout=10)
config.imagemanager.backupretrycount.setValue(0)
self.backupupdate(atLeast)
else:
print("[ImageManager] Running Backup", strftime("%c", localtime(now)))
self.ImageBackup = ImageBackup(self.session)
Components.Task.job_manager.AddJob(self.ImageBackup.createBackupJob())
# Note that fact that the job has been *scheduled*.
# We do *not* just note successful completion, as that would
# result in a loop on issues such as disk-full.
# Also all that we actually want to know is the day, not the time, so
# we actually remember midday, which avoids problems around DLST changes
# for backups scheduled within an hour of midnight.
#
sched = localtime(time())
sched_t = int(mktime((sched.tm_year, sched.tm_mon, sched.tm_mday, 12, 0, 0, sched.tm_wday, sched.tm_yday, sched.tm_isdst)))
config.imagemanager.lastbackup.value = sched_t
config.imagemanager.lastbackup.save()
# self.close()
class ImageBackup(Screen):
skin = ["""
<screen name="OpenBhImageManager" position="center,center" size="%d,%d">
<ePixmap pixmap="skin_default/buttons/red.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/green.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/yellow.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<ePixmap pixmap="skin_default/buttons/blue.png" position="%d,%d" size="%d,%d" alphatest="blend" scale="1"/>
<widget name="key_red" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#9f1313" transparent="1"/>
<widget name="key_green" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#1f771f" transparent="1"/>
<widget name="key_yellow" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#a08500" transparent="1"/>
<widget name="key_blue" position="%d,%d" zPosition="1" size="%d,%d" font="Regular;%d" halign="center" valign="center" backgroundColor="#18188b" transparent="1"/>
<widget name="lab1" position="%d,%d" size="%d,%d" font="Regular; %d" zPosition="2" transparent="0" halign="center"/>
<widget name="list" position="%d,%d" size="%d,%d" font="Regular;%d" scrollbarMode="showOnDemand"/>
<applet type="onLayoutFinish">
self["list"].instance.setItemHeight(%d)
</applet>
</screen>""",
560, 400, # screen
0, 0, 140, 40, # colors
140, 0, 140, 40,
280, 0, 140, 40,
420, 0, 140, 40,
0, 0, 140, 40, 20,
140, 0, 140, 40, 20,
280, 0, 140, 40, 20,
420, 0, 140, 40, 20,
0, 50, 560, 50, 18, # lab1
10, 105, 540, 260, 20, # list
26,
] # noqa: E124
def __init__(self, session, updatebackup=False):
Screen.__init__(self, session)
self.Console = Console()
self.ConsoleB = Console(binary=True)
self.BackupDevice = config.imagemanager.backuplocation.value
print("[ImageManager] Device: " + self.BackupDevice)
self.BackupDirectory = config.imagemanager.backuplocation.value + "imagebackups/"
print("[ImageManager] Directory: " + self.BackupDirectory)
self.BackupDate = strftime("%Y%m%d_%H%M%S", localtime())
self.WORKDIR = self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-temp"
self.TMPDIR = self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + "-mount"
backupType = "-"
if updatebackup:
backupType = "-SoftwareUpdate-"
imageSubBuild = ""
if SystemInfo["imagetype"] == "developer":
imageSubBuild = ".%s" % SystemInfo["imagedevbuild"]
self.MAINDESTROOT = self.BackupDirectory + config.imagemanager.folderprefix.value + "-" + SystemInfo["machinebuild"] + "-" + SystemInfo["imagetype"] + backupType + SystemInfo["imageversion"] + "." + SystemInfo["imagebuild"] + imageSubBuild + "-" + self.BackupDate
self.KERNELFILE = SystemInfo["kernelfile"]
self.ROOTFSFILE = SystemInfo["rootfile"]
self.MAINDEST = self.MAINDESTROOT + "/" + SystemInfo["imagedir"] + "/"
self.MAINDEST2 = self.MAINDESTROOT + "/"
self.MODEL = SystemInfo["machinebuild"]
self.MCBUILD = SystemInfo["model"]
self.IMAGEDISTRO = SystemInfo["distro"]
self.DISTROVERSION = SystemInfo["imageversion"]
self.DISTROBUILD = SystemInfo["imagebuild"]
self.KERNELBIN = SystemInfo["kernelfile"]
self.UBINIZE_ARGS = SystemInfo["ubinize"]
self.MKUBIFS_ARGS = SystemInfo["mkubifs"]
self.ROOTFSTYPE = SystemInfo["imagefs"].strip()
self.ROOTFSSUBDIR = "none"
self.VuSlot0 = ""
self.EMMCIMG = "none"
self.MTDBOOT = "none"
if SystemInfo["canBackupEMC"]:
(self.EMMCIMG, self.MTDBOOT) = SystemInfo["canBackupEMC"]
print("[ImageManager] canBackupEMC:", SystemInfo["canBackupEMC"])
self.KERN = "mmc"
self.rootdir = 0
if SystemInfo["canMultiBoot"]:
slot = SystemInfo["MultiBootSlot"]
print("[ImageManager] slot: ", slot)
if SystemInfo["HasKexecMultiboot"]:
self.MTDKERNEL = SystemInfo["mtdkernel"] if slot == 0 else SystemInfo["canMultiBoot"][slot]["kernel"]
self.MTDROOTFS = SystemInfo["mtdrootfs"] if slot == 0 else SystemInfo["canMultiBoot"][slot]["root"].split("/")[2]
self.VuSlot0 = "-VuSlot0" if slot == 0 else ""
else:
self.MTDKERNEL = SystemInfo["canMultiBoot"][slot]["kernel"].split("/")[2]
if SystemInfo["HasMultibootMTD"]:
self.MTDROOTFS = SystemInfo["canMultiBoot"][slot]["root"] # sfx60xx ubi0:ubifs not mtd=
elif not SystemInfo["HasKexecMultiboot"]:
self.MTDROOTFS = SystemInfo["canMultiBoot"][slot]["root"].split("/")[2]
if SystemInfo["HasRootSubdir"] and slot != 0:
self.ROOTFSSUBDIR = SystemInfo["canMultiBoot"][slot]["rootsubdir"]
else:
self.MTDKERNEL = SystemInfo["mtdkernel"]
self.MTDROOTFS = SystemInfo["mtdrootfs"]
if SystemInfo["model"] in ("gb7252"):
self.GB4Kbin = "boot.bin"
self.GB4Krescue = "rescue.bin"
if "sda" in self.MTDKERNEL:
self.KERN = "sda"
print("[ImageManager] HasKexecMultiboot:", SystemInfo["HasKexecMultiboot"])
print("[ImageManager] Model:", self.MODEL)
print("[ImageManager] Machine Build:", self.MCBUILD)
print("[ImageManager] Kernel File:", self.KERNELFILE)
print("[ImageManager] Root File:", self.ROOTFSFILE)
print("[ImageManager] MTD Kernel:", self.MTDKERNEL)
print("[ImageManager] MTD Root:", self.MTDROOTFS)
print("[ImageManager] ROOTFSSUBDIR:", self.ROOTFSSUBDIR)
print("[ImageManager] ROOTFSTYPE:", self.ROOTFSTYPE)
print("[ImageManager] MAINDESTROOT:", self.MAINDESTROOT)
print("[ImageManager] MAINDEST:", self.MAINDEST)
print("[ImageManager] MAINDEST2:", self.MAINDEST2)