from Components.ConfigList import ConfigListScreen
from Components.Console import Console
from Components.GUIComponent import GUIComponent
-from Components.Harddisk import harddiskmanager
+from Components.Harddisk import harddiskmanager, CheckSfdiskVer, enableUdevEvent
from Components.MenuList import MenuList
from Components.Pixmap import Pixmap, MultiPixmap
from Components.Sources.List import List
from __init__ import _
config.plugins.devicemanager = ConfigSubsection()
-config.plugins.devicemanager.hotplug_enable = ConfigEnableDisable(default=True)
config.plugins.devicemanager.mountcheck_enable = ConfigEnableDisable(default=True)
def readFile(filename):
"green": self.keySave,
}, -2)
self.onShown.append(self.setWindowTitle)
- self.old_hotplug_enable = config.plugins.devicemanager.hotplug_enable.value
def setWindowTitle(self):
self.setTitle(_("DeviceManager configuration"))
self.list = []
self.list.append(getConfigListEntry(_("Enable mount check for HDD : "), config.plugins.devicemanager.mountcheck_enable))
self.list.append(getConfigListEntry(_("Harddisk standby after : "), config.usage.hdd_standby))
- self.list.append(getConfigListEntry(_("Mount known devices automatically : "), config.plugins.devicemanager.hotplug_enable))
-
- def keySave(self):
- if config.plugins.devicemanager.hotplug_enable.value:
- if not DeviceManagerhotplugDeviceStart in harddiskmanager.on_partition_list_change:
- harddiskmanager.on_partition_list_change.append(DeviceManagerhotplugDeviceStart)
- else:
- if DeviceManagerhotplugDeviceStart in harddiskmanager.on_partition_list_change:
- harddiskmanager.on_partition_list_change.remove(DeviceManagerhotplugDeviceStart)
-
- for x in self["config"].list:
- x[1].save()
- self.close()
class DeviceManager(Screen):
skin = """
if self.currList == "partitions":
currentPartition = self.getCurrentPartition()
if currentPartition is not None:
- if currentPartition["mountpoint"] != "":
- self["key_green"].setText(_("Umount"))
- else:
- self["key_green"].setText(_("Mount"))
-
if currentPartition["fstype"] == "":
self["key_blue"].setText("")
elif currentPartition["fstype"][:3] == "ext":
partitionList.append(partitionEntry)
if len(partitionList) != 0:
self["key_red"].setText(_("Devices"))
- self["key_green"].setText(_("Mount"))
+ self["key_green"].setText(_(" "))
self["key_yellow"].setText(_("Format"))
self["key_blue"].setText(_("Check"))
self.currList = "partitions"
else:
self.session.open(MessageBox, _("No partition list found on device.\nPlease click BLUE key and do Initialize to use this device."), MessageBox.TYPE_ERROR, timeout = 10)
- def showMountPointSetup(self):
- if self.currDevice is None or self.currPartition is None:
- return
- partition = self.currPartition["partition"]
- if not os.access("/autofs/%s"%partition,0):
- self.session.open(MessageBox, _("This partition is not mountable.\nYou need to check or format this partition."), MessageBox.TYPE_ERROR, timeout = 10)
- return
- self["key_red"].setText(_("Partitions"))
- self["key_green"].setText(_("Ok"))
- self["key_yellow"].setText("")
- self["key_blue"].setText("")
- self.mountPointList = []
- currentMountPoint = self.currPartition["mountpoint"]
- if currentMountPoint == "":
- currentMountPoint = "'not mounted'"
- defaultMountPoint = self.getDefaultMountPoint()
- autoMountPoint = self.getAutoMountPoint()
- defaultMountPointEntry = (self.icon_button_green, _("Set up Default Mount Point"), _("Mount Point : %s ->%s")%(currentMountPoint, defaultMountPoint), "default", defaultMountPoint, self.divpng)
- autoMountPointEntry = (self.icon_button_green, _("Automatically set up a Mount Point"), _("Mount Point : %s -> %s")%(currentMountPoint, autoMountPoint), "auto", autoMountPoint, self.divpng)
- manuallyMountPointEntry = (self.icon_button_green, _("User manually Set up a Mount Point"), _("Mount Point : click ok button on here."), "manual", "", self.divpng)
- if not path.ismount(defaultMountPoint):
- self.mountPointList.append(defaultMountPointEntry)
- self.mountPointList.append(autoMountPointEntry)
- self.mountPointList.append(manuallyMountPointEntry)
- self.currList = "mountpoint"
- self["menu"].style = "mountpoint"
- self["menu"].setList(self.mountPointList)
-
def getCurrentDevice(self):
- if self.currList == "default":
+ try:
return self["menu"].getCurrent()[6]
- return None
+ except:
+ return None
def getCurrentPartition(self):
- if self.currList == "partitions":
+ try:
return self["menu"].getCurrent()[7]
- return None
+ except:
+ return None
def keyOk(self):
# print "keyOk"
if self.currList == "default":
self.currDevice = self.getCurrentDevice()
- if len(self.currDevice["partitions"]) == 0:
- self.session.open(MessageBox, _("No partition list found on device.\nPlease click BLUE key and do Initialize to use this device."), MessageBox.TYPE_ERROR, timeout = 10)
+ if self.currDevice is not None:
+ if len(self.currDevice["partitions"]) == 0:
+ self.session.open(MessageBox, _("No partition list found on device.\nPlease click BLUE key and do Initialize to use this device."), MessageBox.TYPE_ERROR, timeout = 10)
+ else:
+ self.showPartitionList()
else:
- self.showPartitionList()
+ self.session.open(MessageBox, _("Device not found."), MessageBox.TYPE_ERROR, timeout = 10)
elif self.currList == "partitions":
- currMountPoint = self.getCurrentPartition()["mountpoint"]
- currUuid = self.getCurrentPartition()["uuid"]
- if currMountPoint == "":
- self.currPartition = self.getCurrentPartition()
- self.showMountPointSetup()
- else:
- self.doUmount(currMountPoint, self.showPartitionList)
- elif self.currList == "mountpoint":
-# self["menu"].getCurrent() : (green_button, "menu description", "mount point description, "default", mountpoint, self.divpng)
- currEntry = self["menu"].getCurrent()[3]
- if currEntry == "default":
-# print "Setup mountpoint default!"
- self.doMount(self.currPartition, self["menu"].getCurrent()[4])
- elif currEntry == "auto":
-# print "Setup mountpoint automatically!"
- self.doMount(self.currPartition, self["menu"].getCurrent()[4])
- else:
-# print "Setup mountpoint manually!"
- self.session.openWithCallback(self.MountpointBrowserCB, MountpointBrowser)
+ pass
else:
pass
if self.currList == "partitions":
self.currDevice = None
self.showDeviceList()
- elif self.currList == "mountpoint":
- self.currPartition = None
- self.showPartitionList()
else: # currList = "default"
self.close()
def keyYellow(self):
if self.currList == "partitions":
- partition = self.getCurrentPartition()
self.choiceBoxFstype()
def keyBlue(self):
if self.currList == "default":
device = self.getCurrentDevice()
- self.session.openWithCallback(self.deviceInitCB, DeviceInit, device["blockdev"], device["size"])
+ if device is not None:
+ self.session.openWithCallback(self.deviceInitCB, DeviceInit, device["blockdev"], device["size"])
+ else:
+ self.session.open(MessageBox, _("Device not found."), MessageBox.TYPE_ERROR, timeout = 10)
elif self.currList == "partitions":
partition = self.getCurrentPartition()
- self.session.openWithCallback(self.deviceCheckCB, DeviceCheck, partition)
+ if partition is not None:
+ self.session.openWithCallback(self.deviceCheckCB, DeviceCheck, partition)
+ else:
+ self.session.open(MessageBox, _("Partition info is not found."), MessageBox.TYPE_ERROR, timeout = 10)
def keyMenu(self):
self.session.open(DeviceManagerConfiguration)
return
else:
partition = self.getCurrentPartition()
- self.session.openWithCallback(self.deviceFormatCB, DeviceFormat, partition, choice[1])
-
-# about mount funcs..
- def doUmount(self, mountpoint, callback):
- cmd = "umount %s"%mountpoint
- print "[DeviceManager] cmd : %s"%cmd
- os.system(cmd)
- if not path.ismount(mountpoint):
- devicemanagerconfig.updateConfigList()
- else:
- self.session.open(MessageBox, _("Can't umount %s. \nMaybe device or resource busy.")%mountpoint, MessageBox.TYPE_ERROR, timeout = 10)
- callback()
-
- def getDefaultMountPoint(self):
- return self.defaultMountPoint
-
- def getAutoMountPoint(self):
- mountPoint = "/media/"+self.currDevice["model"]
- mountPoint = mountPoint.replace(' ','-')
- if path.ismount(mountPoint):
- partnum = 2
- while 1:
- mountPoint_fix = mountPoint+str(partnum)
- if not path.ismount(mountPoint_fix):
- break
- partnum +=1
- mountPoint = mountPoint_fix
- return mountPoint
-
- def doMount(self, partition, mountpoint):
- try:
-# check mountpoint is in partition list.
- if mountpoint != self.getDefaultMountPoint():
- for p in harddiskmanager.partitions:
- if p.mountpoint == mountpoint:
- self.session.open(MessageBox, _("Can not use this mount point.(%s) \nPlease select another mount point.")%mountpoint, MessageBox.TYPE_ERROR, timeout = 10)
- return
-#
- device = partition["partition"]
- filesystem = partition["fstype"]
- uuid = partition["uuid"]
- if mountpoint.endswith("/"):
- mountpoint = retval[:-1]
- if mountpoint.find(' ') != -1:
- mountpoint = mountpoint.replace(' ','-')
- devpath = "/dev/"+device
- if deviceinfo.isMounted(devpath, mountpoint):
- print "[DeviceManager] '%s -> %s' is already mounted."%(devpath, mountpoint)
- return
-
-# check current device mounted on another mountpoint.
- mp_list = deviceinfo.checkMountDev(devpath)
- for mp in mp_list:
- if mp != mountpoint and path.ismount(mp):
- deviceinfo.umountByMountpoint(mp)
-# check another device mounted on configmountpoint
- devpath_list = deviceinfo.checkMountPoint(mountpoint)
- for devpath_ in devpath_list:
- if devpath_ != devpath:
- self.session.open(MessageBox, _("Mount Failed!\nCurrent path is already mounted by \"%s\"")%devpath_list[0], MessageBox.TYPE_ERROR, timeout = 10)
- return
-# do mount
- print "[DeviceManagerHotplugDevice] doMount"
- if not path.exists(mountpoint):
- os.system("mkdir %s"%mountpoint)
- if path.exists(mountpoint):
- if not path.ismount(mountpoint):
- if filesystem == "ntfs":
- cmd = "ntfs-3g %s %s"%(devpath, mountpoint)
- elif filesystem is None:
- cmd = "mount %s %s"%(devpath, mountpoint)
- else:
- cmd = "mount -t %s %s %s"%(filesystem, devpath, mountpoint)
- print "[DeviceManager] cmd : %s"%cmd
- self.DeviceManagerConsole.ePopen(cmd, self.doMountFinished, (devpath, mountpoint) )
- except:
- self.session.open(MessageBox, _("Mount Failed!\n(%s -> %s)")%(device, mountpoint), MessageBox.TYPE_ERROR, timeout = 10)
-
- def doMountFinished(self, result, retval, extra_args = None):
- (devpath, mountpoint) = extra_args
- if retval == 0:
- if not deviceinfo.isMounted(devpath, mountpoint):
-# print "[DeviceManager] %s doMount failed!"%devpath
- self.session.open(MessageBox, _("Mount Failed!\n(%s -> %s)")%(devpath, mountpoint), MessageBox.TYPE_ERROR, timeout = 10)
- return
- else:
-# make movie directory
- if mountpoint == "/media/hdd":
- movieDir = mountpoint + "/movie"
- if not pathExists(movieDir):
- print "[DeviceManager] make dir %s"%movieDir
- os.makedirs(movieDir)
- self.showPartitionList()
-# update current mount state ,devicemanager.cfg
- devicemanagerconfig.updateConfigList()
-
- def MountpointBrowserCB(self, retval = None):
- if retval and retval is not None:
- mountPoint = retval.strip().replace(' ','')
- if retval.endswith("/"):
- mountPoint = retval[:-1]
- print "Mount point from MountpointBrowser : %s"%mountPoint
- if not path.exists(mountPoint):
- self.session.open(MessageBox, _("Mount Point is not writeable.\nPath : %s")%mountPoint, MessageBox.TYPE_ERROR, timeout = 10)
-
+ if partition is not None:
+ self.session.openWithCallback(self.deviceFormatCB, DeviceFormat, partition, choice[1])
else:
- self.doMount(self.currPartition, mountPoint)
-# mount funcs end..
+ self.session.open(MessageBox, _("Partition info is not found."), MessageBox.TYPE_ERROR, timeout = 10)
# Initializing Start...
class DeviceInit(Screen):
self.devicesize = int(devicesize)
self.inputbox_partitions = 1
self.inputbox_partitionSizeList = []
- self.inputbox_partitionSizeTotal = self.inputbox_partitionSizeRemain = int(self.devicesize/1024/1024)
+ self.inputbox_partitionSizeTotal = int(self.devicesize/1024/1024)
self.msgWaiting = None
self.msgWaitingMkfs = None
self.devicenumber = 0
self.doInitializeTimer = eTimer()
self.doInitializeTimer.callback.append(self.doInitialize)
+ self.partitionType = "MBR"
+ self.maxPartNum = 4
+ self.inputbox_partitionSizeRemain = self.inputbox_partitionSizeTotal
+ self.unit = "MB"
+ self.onClose.append(enableUdevEvent)
+
def timerStart(self):
+ enableUdevEvent(False)
self.initStartTimer.start(100,True)
def confirmMessage(self):
return True
def InitializeStart(self):
+ if self.devicesize >= ( 2.2 * 1000 * 1000 * 1000 * 1000 ): # 2.2TB
+ self.partitionType = "GPT"
+ self.maxPartNum = 20
+ self.inputbox_partitionSizeRemain = 100
+ self.unit = "%"
+
self.InputPartitionSize_step1()
def InputPartitionSize_step1(self):
- self.session.openWithCallback(self.InputPartitionSize_step1_CB, InputBox, title=_("How many partitions do you want?(1-4)"), text="1", maxSize=False, type=Input.NUMBER)
+ self.session.openWithCallback(self.InputPartitionSize_step1_CB, InputBox, title=_("How many partitions do you want?(1-%d)" % self.maxPartNum), text="1", maxSize=False, type=Input.NUMBER)
def InputPartitionSize_step1_CB(self, ret):
- if ret is not None and int(ret) in range(1,5): # ret in 1~4
+ if ret is not None and int(ret) in range(1,self.maxPartNum+1): # MBR 1~4, GPT 1~20
self.inputbox_partitions = int(ret)
self.InputPartitionSize_step2()
else:
self.choiceBoxFstype()
else:
text = str(int(self.inputbox_partitionSizeRemain/(self.inputbox_partitions-len(self.inputbox_partitionSizeList) )))
- self.session.openWithCallback(self.InputPartitionSize_step2_CB, InputBox, title=_("Input size of partition %s.(Max = %d MB)")%(current_partition,self.inputbox_partitionSizeRemain ), text=text, maxSize=False, type=Input.NUMBER)
+ self.session.openWithCallback(self.InputPartitionSize_step2_CB, InputBox, title=_("Input size of partition %s.(Unit = %s, Max = %d %s)")%(current_partition, self.unit, self.inputbox_partitionSizeRemain, self.unit), text=text, maxSize=False, type=Input.NUMBER)
def InputPartitionSize_step2_CB(self, ret):
if ret is not None:
# print self.inputbox_partitionSizeList
partitionsInfo = ""
for index in range(len(self.inputbox_partitionSizeList)):
- print "partition %d : %s Bytes"%(index+1, str(self.inputbox_partitionSizeList[index]))
- partitionsInfo += "partition %d : %s MB\n"%(index+1, str(self.inputbox_partitionSizeList[index]))
+ print "partition %d : %s %s"%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit)
+ partitionsInfo += "partition %d : %s %s\n"%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit)
partitionsInfo += "filesystem type : %s"%(self.fstype)
self.session.openWithCallback(self.initInitializeConfirmCB, MessageBoxConfirm, _("%s\nStart Device Inititlization?") % partitionsInfo , MessageBox.TYPE_YESNO)
msg += _("\nDevice : %s")%self.device
msg += _("\nSize : %s MB\n")%self.inputbox_partitionSizeTotal
for index in range(len(self.inputbox_partitionSizeList)):
- msg += _("\npartition %d : %s MB")%(index+1, str(self.inputbox_partitionSizeList[index]))
+ msg += _("\npartition %d : %s %s")%(index+1, str(self.inputbox_partitionSizeList[index]), self.unit)
self.msgWaiting = self.session.openWithCallback(self.msgWaitingCB, MessageBox_2, msg, type = MessageBox.TYPE_INFO, enable_input = False)
self.doInitializeTimer.start(500,True)
def doInitialize(self):
+ def CheckPartedVer():
+ cmd = 'parted --version'
+ lines = os.popen(cmd).readlines()
+ for l in lines:
+ if l.find("parted (GNU parted)") != -1:
+ ver = l.split()[3].strip()
+ break
+ try:
+ ver = float(ver)
+ except:
+ print "[DeviceManager] check parted version Failed!"
+ return 0
+ return ver
+
+ partitions = len(self.inputbox_partitionSizeList) # get num of partition
set = ""
- partitions = len(self.inputbox_partitionSizeList)
- if partitions == 1:
- cmd = 'printf "8,\n;0,0\n;0,0\n;0,0\ny\n" | sfdisk -f -uS /dev/' + self.device
+
+ setAlign = ""
+ partedVer = CheckPartedVer()
+ if partedVer >= 2.1: # align option is supported in version 2.1 or later
+ setAlign = "--align optimal"
+ if self.devicesize < 1024 * 1000 * 1000: # 1GB
+ setAlign = "-a min"
+ else:
+ setAlign = "-a opt"
+
+ if self.partitionType == "GPT": # partition type is GPT
+ parttype = 'gpt'
else:
- for p in range(4):
- if partitions > p+1:
- set += ",%s\n"%(self.inputbox_partitionSizeList[p])
- else:
- set +=";\n"
- set+="y\n"
- cmd = 'printf "%s" | sfdisk -f -uM /dev/%s'%(set,self.device)
+ parttype = 'msdos'
+
+ if partitions == 1:
+ cmd = 'parted %s /dev/%s --script mklabel %s mkpart primary 0%% 100%%' % (setAlign, self.device, parttype)
+ else: # has multiple partitions
+ p_current = 0
+ for p in range(partitions):
+ if p == 0:
+ p_start = p_current
+ p_end = int( (long(self.inputbox_partitionSizeList[p]) * 100) / self.inputbox_partitionSizeTotal )
+ p_current = p_end
+ elif p > 0 and partitions > (p + 1):
+ p_start = p_current
+ p_end = int( (long(self.inputbox_partitionSizeList[p]) * 100) / self.inputbox_partitionSizeTotal )+ p_start
+ p_current = p_end
+ elif partitions == (p + 1):
+ p_start = p_current
+ p_end = 100
+
+ if p_start == p_end:
+ p_end +=1
+ if p_end > 100:
+ continue
+
+ set += 'mkpart primary ext2 %d%% %d%% ' % (p_start, p_end)
+ cmd = 'parted %s /dev/%s --script mklabel %s %s' % (setAlign, self.device, parttype, set)
+
self.deviceInitConsole.ePopen(cmd, self.initInitializeFinished)
def initInitializeFinished(self, result, retval, extra_args = None):
if retval == 0:
- cmd = "sfdisk -R /dev/%s ; sleep 5" % (self.device)
+ if self.partitionType == "MBR":
+ sfdiskVer = CheckSfdiskVer()
+ if sfdiskVer < 2.26: # sfdisk -R option is deprecated at sfdiskVer >= 2.26
+ cmd = 'sfdisk -R /dev/%s; sleep 5' % (self.device)
+ elif path.exists('/usr/sbin/partprobe'):
+ cmd = 'partprobe /dev/%s; sleep 5' % (self.device)
+ elif path.exists('/usr/sbin/partx'):
+ cmd = 'partx -u /dev/%s; sleep 5' % (self.device)
+ else:
+ cmd = 'sfdisk -R /dev/%s; sleep 5' % (self.device)
+ else: # is GPT
+ cmd = "sleep 5"
self.deviceInitConsole.ePopen(cmd, self.initInitializingRefreshFinished)
else:
errorMsg = "initInitializing device Error at /dev/%s"%self.device
if len(res[3]) > 3 and res[3][:2] == "sd":
self.newpartitions += 1
partitions.close()
- self.msgWaiting.run_close(True)
+ partNum = len(self.inputbox_partitionSizeList) # get num of partition
+ if self.newpartitions != partNum:
+ errorMsg = "Partitioning device Error at /dev/%s"%self.device
+ self.msgWaiting.run_close(False, errorMsg)
+ else:
+ self.msgWaiting.run_close(True)
# self.createFilesystem(self.newpartitions)
def createFilesystem(self, newpartitions):
partitions.close()
if self.fstype == "ext4":
- cmd = "/sbin/mkfs.ext4 -F "
+ cmd = "mkfs.ext4 -F "
if partitionsize > 2 * 1024 * 1024: # 2GB
cmd += "-T largefile "
cmd += "-O extent,flex_bg,large_file,uninit_bg -m1 " + fulldevicename
elif self.fstype == "ext3":
- cmd = "/sbin/mkfs.ext3 -F "
+ cmd = "mkfs.ext3 -F "
if partitionsize > 2 * 1024 * 1024:
cmd += "-T largefile "
cmd += "-m0 " + fulldevicename
elif self.fstype == "ext2":
- cmd = "/sbin/mkfs.ext2 -F "
+ cmd = "mkfs.ext2 -F "
if partitionsize > 2 * 1024 * 1024:
cmd += "-T largefile "
cmd += "-m0 " + fulldevicename
elif self.fstype == "vfat":
if partitionsize > 4 * 1024 * 1024 * 1024:
- cmd = "/usr/sbin/mkfs.vfat -I -S4096 " + fulldevicename
+ cmd = "mkfs.vfat -I -S4096 " + fulldevicename
else:
- cmd = "/usr/sbin/mkfs.vfat -I " + fulldevicename
+ cmd = "mkfs.vfat -I " + fulldevicename
+ if partitionsize > 2 * 1024 * 1024: # if partiton size larger then 2GB, use FAT32
+ cmd += " -F 32"
+
else:
self.createFilesystemFinished(None, -1, (self.device, fulldevicename))
return
msg = _("Create filesystem, please wait ...")
msg += _("\nPartition : %s") % (fulldevicename)
msg += _("\nFilesystem : %s") % (self.fstype)
- msg += _("\nSize : %d MB\n")%int(self.inputbox_partitionSizeList[self.devicenumber-1])
+ msg += _("\nDisk Size : %s MB") % (self.inputbox_partitionSizeTotal)
+ msg += _("\nPartition Size : %d %s\n") % (int(self.inputbox_partitionSizeList[self.devicenumber-1]), self.unit)
self.msgWaitingMkfs = self.session.openWithCallback(self.msgWaitingMkfsCB, MessageBox_2, msg, type = MessageBox.TYPE_INFO, enable_input = False)
self.mkfs_cmd = cmd
self.doMkfsTimer.start(500,True)
if ret == True:
self.success = True
self.msg = _("Device Initialization finished sucessfully!")
- self.updateDeviceInfo()
self.exitMessageTimer.start(100,True)
else:
self.success = False
else:
self.session.openWithCallback(self.exit, MessageBox, self.msg, MessageBox.TYPE_ERROR, timeout = 10)
- def updateDeviceInfo(self):
-# update devicemanager configs
- devicemanagerconfig.updateConfigList()
-
# Initializing end
# device check start..
self.onLayoutFinish.append(self.timerStart)
self.formatStartTimer = eTimer()
self.formatStartTimer.callback.append(self.DeviceFormatStart)
- self.setHotplugDisabled = False
self.umountTimer = eTimer()
self.umountTimer.callback.append(self.doUnmount)
+ self.onClose.append(enableUdevEvent)
def timerStart(self):
+ enableUdevEvent(False)
self.formatStartTimer.start(100,True)
def DeviceFormatStart(self):
- devicemanagerhotplug.setHotplugActive(False)
- self.setHotplugDisabled = True
print "DeviceFormatStart : ", self.partition,
print "Filesystem : ",self.newfstype
device = self.partition["partition"]
if oldfstype == newfstype:
self.changePartitionIDFinished("NORESULT", 0)
else:
- cmd = "sfdisk --change-id /dev/%s %s" % (partition[:3], partition[3:])
+ sfdiskVer = CheckSfdiskVer()
+ if sfdiskVer >= 2.26:
+ cmd = "sfdisk --part-type /dev/%s %s" % (partition[:3], partition[3:])
+ else:
+ cmd = "sfdisk --change-id /dev/%s %s" % (partition[:3], partition[3:])
+
if newfstype[:3] == "ext":
cmd += " 83"
else:
if oldfstype == newfstype:
self.refreshPartitionFinished("NORESULT", 0)
else:
- cmd = "sfdisk -R /dev/%s; sleep 5"%(device)
+ sfdiskVer = CheckSfdiskVer()
+ if sfdiskVer < 2.26: # sfdisk -R option is deprecated at sfdiskVer >= 2.26
+ cmd = "sfdisk -R /dev/%s; sleep 5" % (device)
+ elif path.exists('/usr/sbin/partprobe'):
+ cmd = 'partprobe /dev/%s; sleep 5' % (device)
+ elif path.exists('/usr/sbin/partx'):
+ cmd = 'partx -u /dev/%s; sleep 5' % (device)
+ else:
+ cmd = "sfdisk -R /dev/%s; sleep 5" % (device)
+
self.deviceFormatConsole.ePopen(cmd, self.refreshPartitionFinished)
else:
- errorMsg = _("Can not change the partition ID for %s")%device
- self.msgWaiting.run_close(False,errorMsg)
+ if result and result.find("Use GNU Parted") > 0:
+ print "[DeviceManager] /dev/%s use GNU Parted!" % device
+ self.refreshPartitionFinished("NORESULT", 0)
+ else:
+ errorMsg = _("Can not change the partition ID for %s")%device
+ self.msgWaiting.run_close(False,errorMsg)
def refreshPartitionFinished(self, result, retval, extra_args = None):
print "refreshPartitionFinished!"
newfstype = self.newfstype
if retval == 0:
if newfstype == "ext4":
- cmd = "/sbin/mkfs.ext4 -F "
+ cmd = "mkfs.ext4 -F "
if size > 2 * 1024:
cmd += "-T largefile "
cmd += "-O extent,flex_bg,large_file,uninit_bg -m1 /dev/" + partition
elif newfstype == "ext3":
- cmd = "/sbin/mkfs.ext3 -F "
+ cmd = "mkfs.ext3 -F "
if size > 2 * 1024:
cmd += "-T largefile "
cmd += "-m0 /dev/" + partition
elif newfstype == "ext2":
- cmd = "/sbin/mkfs.ext2 -F "
+ cmd = "mkfs.ext2 -F "
if size > 2 * 1024:
cmd += "-T largefile "
cmd += "-m0 /dev/" + partition
elif newfstype == "vfat":
if size > 4 * 1024 * 1024:
- cmd = "/usr/sbin/mkfs.vfat -I -S4096 /dev/" + partition
+ cmd = "mkfs.vfat -I -S4096 /dev/" + partition
else:
- cmd = "/usr/sbin/mkfs.vfat -I /dev/" + partition
+ cmd = "mkfs.vfat -I /dev/" + partition
+ if size > 2 * 1024: # if partiton size larger then 2GB, use FAT32
+ cmd += " -F 32"
self.deviceFormatConsole.ePopen(cmd, self.mkfsFinished)
else:
errorMsg = _("Can not format device /dev/%s.\nrefresh partition information failed!")%partition
self.session.openWithCallback(self.exit, MessageBox, msg, MessageBox.TYPE_ERROR, timeout = 10)
def exit(self, ret):
- if self.setHotplugDisabled == True:
- devicemanagerhotplug.setHotplugActive(True)
- self.setHotplugDisabled = False
self.close()
#device format end
blockDevice["vendor"] = vendor # str
self.blockDeviceList.append(blockDevice)
+ def SortPartList(self, partList):
+ length = len(partList)-1
+ sorted = False
+ while sorted is False:
+ sorted = True
+ for idx in range(length):
+ if int(partList[idx][3:]) > int(partList[idx+1][3:]):
+ sorted = False
+ partList[idx] , partList[idx+1] = partList[idx+1], partList[idx]
+
def getBlockDeviceInfo(self, blockdev):
devpath = "/sys/block/" + blockdev
error = False
if partition[:len(blockdev)] != blockdev:
continue
partitions.append(partition)
+ self.SortPartList(partitions)
+
except IOError:
error = True
return error, blacklisted, removable, partitions, size, model, vendor
def isMounted(self, devpath, mountpoint):
try:
- mounts = file('/proc/mounts').read().split('\n')
+ mounts = file('/proc/mounts').readlines()
for x in mounts:
if not x.startswith('/'):
continue
pass
return False
+ def isMounted_anymp(self, devpath):
+ try:
+ mounts = open('/proc/mounts', 'r').readlines()
+ for x in mounts:
+ if not x.startswith('/'):
+ continue
+ _devPart, _mountpoint = x.split()[:2]
+ if devpath == _devPart:
+ return True
+ except:
+ pass
+ return False
+
+ # check partition type is extended or swap.
+ def checkSwapExtended(self, partition):
+ blockName = partition[:-1]
+ partNum = partition[-1]
+ data = os.popen("parted /dev/%s print" % blockName).readlines()
+ for x in data:
+ info = x.strip().split()
+
+ if len(info) > 0 and info[0] == str(partNum):
+ if len(info) >= 5 and info[4].find('extended') != -1: # check Type is extended
+ return True
+ elif len(info) >= 6 and info[5].find('swap') != -1: # check File System is swap
+ return True
+
+ return False
+
def isMountable(self, partition):
- autofsPath = "/autofs/"+partition.device
- mountable = False
+ if self.checkSwapExtended(partition):
+ return False
+
try:
- os.listdir(autofsPath)
- mountable = True
+ if self.isMounted_anymp('/dev/'+partition):
+ return True
+
+ elif os.access('/autofs/'+partition, 0):
+ return True
except:
pass
- return mountable
+ return False
def isFstabAutoMounted(self, uuid, devpath, mountpoint):
# print " >> isFstabMounted, uuid : %s, devpath : %s, mountpoint : %s"%(uuid, devpath, mountpoint)
"""
dmconfigfile = resolveFilename(SCOPE_PLUGINS, "SystemPlugins/DeviceManager/devicemanager.cfg")
-class DeviceManagerConfig():
- def __init__(self):
- self.configList = []
-
- def getConfigList(self):
- return self.configList
-
- def updateConfigList(self):
- try:
- self.configList = []
- file = open("/proc/mounts")
- mounts = file.readlines()
- file.close()
- for x in mounts:
- if x.startswith("/dev/sd"):
- device = x.split()[0].split('/dev/')[1]
- mountpoint = x.split()[1]
- if mountpoint.startswith('/autofs'):
- continue
- (uuid, partitionType) = deviceinfo.getPartitionBlkidInfo(device)
- if uuid != '' and mountpoint != '':
- self.configList.append([uuid, mountpoint])
- self.saveConfig()
- except:
- print "updateConfigList failed!"
-
- def loadConfig(self):
- if not fileExists(dmconfigfile):
- os.system("touch %s" % dmconfigfile)
- self.configList = []
- data = file(dmconfigfile).read().split('\n')
- for line in data:
- if line.find(':') != -1:
- (uuid, mountpoint) = line.split(':')
- if uuid != '' and mountpoint != '':
- self.configList.append([uuid, mountpoint])
-
- def saveConfig(self):
- confFile = open(dmconfigfile,'w')
- data = ""
- for line in self.configList:
- data += "%s:%s\n"%(line[0],line[1]) # uuid, mountpoint
- confFile.write(data)
- confFile.close()
-
- def appendConfig(self, uuid, mountpoint):
- for x in self.configList:
- if x[0] == uuid or x[1] == mountpoint:
- self.configList.remove(x)
- self.configList.append([uuid, mountpoint])
-
- def removeConfig(self, value):
- for x in self.configList:
- if x[0] == value or x[1] == value:
- self.configList.remove(x)
-
-devicemanagerconfig = DeviceManagerConfig()
-
-class deviceManagerHotplug:
- def __init__(self):
- self.hotplugActive = True
-
- def setHotplugActive(self,value=True):
- if value:
- self.hotplugActive = True
- else:
- self.hotplugActive = False
-
- def printDebug(self):
- for p in harddiskmanager.partitions:
- print " # partition : %s %s %s %s %s(mp, des, f_mounted, is_hot, dev)"%(p.mountpoint, p.description, p.force_mounted, p.is_hotplug,p.device)
-
- def doMount(self, uuid, devpath, mountpoint, filesystem):
-# check current device mounted on another mountpoint.
- mp_list = []
- mp_list = deviceinfo.checkMountDev(devpath)
- for mp in mp_list:
- if mp != mountpoint and path.ismount(mp):
- deviceinfo.umountByMountpoint(mp)
-# check another device mounted on configmountpoint
- devpath_list = []
- devpath_list = deviceinfo.checkMountPoint(mountpoint)
- for devpath_ in devpath_list:
- if devpath_ != devpath:
- print "[DeviceManager] Mount Failed. (Another device is already mounted)"
- return
-# do mount
-# print "[DeviceManager] doMount"
- if not path.exists(mountpoint):
- os.system("mkdir %s"%mountpoint)
- if path.exists(mountpoint):
- if not path.ismount(mountpoint):
- if filesystem == "ntfs":
- cmd = "ntfs-3g %s %s"%(devpath, mountpoint)
- elif filesystem is None:
- cmd = "mount %s %s"%(devpath, mountpoint)
- else:
- cmd = "mount -t %s %s %s"%(filesystem, devpath, mountpoint)
- print "[DeviceManager] cmd : %s"%cmd
- os.system(cmd)
- if not deviceinfo.isMounted(devpath, mountpoint):
- print "[DeviceManager] %s doMount failed!"%devpath
- return
- else:
-# Update partition Info, add
- self.addPartitionAutofsMountpoint(devpath, mountpoint)
-
- def doUmount(self, device, mountpoint):
- devpath = "/dev/"+device
- mountpoints = deviceinfo.checkMountDev(devpath)
- if len(mountpoints) == 0:
- return
- for mp in mountpoints:
- cmd = "umount %s"%devpath
- print "[DeviceManager] cmd : %s"%cmd
- os.system(cmd)
-
- def addHotPlugDevice(self, partition):
- device = partition.device
- devpath = "/dev/"+device
-# get BlkidInfo
- (uuid, filesystem) = deviceinfo.getPartitionBlkidInfo(device)
- if uuid == "":
-# retry..
- os.system("sleep 1")
- (uuid, filesystem) = deviceinfo.getPartitionBlkidInfo(device)
- if uuid == "":
- print "[DeviceManagerHotplug] getBlkidInfo failed!"
- return
-# get configList
- devicemanagerconfig.loadConfig()
- configList = devicemanagerconfig.getConfigList()
- mountpoint = None
- for line in configList:
- if uuid == line[0].strip():
- mountpoint = line[1].strip()
- break
- if mountpoint is None:
- return
-# do mount
- if deviceinfo.isMounted(devpath, mountpoint):
- pass
-# print "[DeviceManagerHotplug] already mounted"
- else:
- self.doMount(uuid, devpath, mountpoint, filesystem)
-
- def removeHotplugDevice(self, partition):
- self.doUmount(partition.device, partition.mountpoint)
-
- def getHotplugAction(self, action, partition):
- if not self.hotplugActive or not config.plugins.devicemanager.hotplug_enable.value:
- return
- if partition.device is None or not partition.device.startswith("sd"):
- return
- print "[DeviceManagerHotplug] action : %s, device : %s"%(action, partition.device)
-
- if action == 'add':
- self.addHotPlugDevice(partition)
- elif action == 'remove':
- self.removeHotplugDevice(partition)
-
- def addPartitionAutofsMountpoint(self, devpath, mountpoint):
- device = path.basename(devpath)
- autofsMountpoint = harddiskmanager.getAutofsMountpoint(device)
-# check already appended to partition list
- for x in harddiskmanager.partitions:
- if x.mountpoint == autofsMountpoint or x.mountpoint == mountpoint:
- return
-#
- from Components.Harddisk import Partition
- physdev = path.realpath('/sys/block/' + device[:3] + '/device')[4:]
- description = harddiskmanager.getUserfriendlyDeviceName(device, physdev)
- p = Partition(mountpoint = autofsMountpoint, description = description, force_mounted = True, device = device)
- harddiskmanager.partitions.append(p)
- harddiskmanager.on_partition_list_change("add", p)
-
- def autoMountOnStartup(self):
- devicemanagerconfig.loadConfig()
- configList = devicemanagerconfig.getConfigList()
-# get blkid info
- blkiddata = []
- data = os.popen("blkid -c /dev/NULL /dev/sd*").readlines()
- for line in data:
- devpath = uuid = filesystem = ""
- devpath = line.split(':')[0]
- if line.find(" UUID=") != -1:
- uuid = line.split(" UUID=")[1].split(' ')[0]
- if line.find(" TYPE=") != -1:
- filesystem = line.split(" TYPE=")[1].split(' ')[0].strip('"')
- blkiddata.append((devpath, uuid, filesystem))
-# check configList
- for c in configList:
- uuid_cfg = c[0].strip()
- mountpoint_cfg = c[1].strip()
- for (devpath, uuid, filesystem) in blkiddata:
- if uuid_cfg == uuid:
-# do mount
- if deviceinfo.isMounted(devpath, mountpoint_cfg):
-# print "[Devicemanager startup] already mounted"
- self.addPartitionAutofsMountpoint(devpath, mountpoint_cfg)
- else:
-# print "[autoMountOnStartup] do mount(%s %s %s)"%(devpath, configmountpoint, filesystem)
- self.doMount(uuid, devpath, mountpoint_cfg, filesystem)
-
- def umountOnShutdown(self):
- devicemanagerconfig.loadConfig()
- configList = devicemanagerconfig.getConfigList()
-# get mount info
- mounts = []
- data = file('/proc/mounts').read().split('\n')
- for x in data:
- if not x.startswith('/dev/sd'):
- continue
- devpath, mountpoint = x.split()[:2]
- mounts.append((path.basename(devpath), mountpoint))
-# get blkid info
- data = self.getBlkidInfo()
-# check configList
- for c in configList:
- uuid_cfg = c[0].strip()
- mountpoint_cfg = c[1].strip()
- device_cfg = None
- if uuid_cfg in data.keys():
- device_cfg = data[uuid_cfg]
- if device_cfg is None:
- continue
- for (device, mountpoint) in mounts:
- if device_cfg == device:
- if not deviceinfo.isFstabAutoMounted(uuid_cfg, "/dev/"+device_cfg, mountpoint_cfg):
- self.doUmount(device, mountpoint)
-
- def getBlkidInfo(self):
- data = {}
- blkid_data = os.popen("blkid -c /dev/NULL /dev/sd*").read()
- for line in blkid_data.split('\n'):
-# print "[DeviceManager] getBlkidInfo line : ",line
- device = uuid = ""
- device = path.basename(line.split(':')[0])
- if line.find(" UUID=") != -1:
- blkid_uuid = line.split(" UUID=")[1].split(' ')[0]
- data[blkid_uuid] = device
- return data
-
-devicemanagerhotplug = deviceManagerHotplug()
-
-def DeviceManagerhotplugDeviceStart(action, device):
- devicemanagerhotplug.getHotplugAction(action, device)
def callBackforDeviceManager(session, callback_result = False):
if callback_result == True:
for partition in listdir(devpath):
if not partition.startswith(blockdev):
continue
+
+ if deviceinfo.checkSwapExtended(partition):
+ continue
+
partitions.append(partition)
- if os.access('/autofs/'+partition,0) is False:
+
+ if deviceinfo.isMounted_anymp('/dev/' + partition):
+ continue
+
+ if os.access('/autofs/'+partition, 0) is False:
noMountable_partitions.append(partition)
+
if len(partitions) == 0 or len(noMountable_partitions) != 0:
if noMountable_dev != "":
noMountable_dev += ' '
if kwargs.has_key("session") and config.plugins.devicemanager.mountcheck_enable.value == True:
session = kwargs["session"]
checkMounts(session)
- if config.plugins.devicemanager.hotplug_enable.value:
- harddiskmanager.on_partition_list_change.append(DeviceManagerhotplugDeviceStart)
elif reason == 1:
- if config.plugins.devicemanager.hotplug_enable.value:
- harddiskmanager.on_partition_list_change.remove(DeviceManagerhotplugDeviceStart)
+ pass
def autostart(reason, **kwargs):
if reason == 0:
try:
-# check at first enigma2 start
- if not fileExists(dmconfigfile):
+# at first enigma2 start
+ if config.misc.firstrun.value:
print "[DeviceManager] autostart : check devices at first start"
- sda_isremovable = False
- sda_UUID = ""
- os.system("touch %s"%dmconfigfile)
-# check sda
- sda_data = popen("cat /proc/partitions | grep sda1").read()
- if sda_data != '':
- sda_UUID = popen("blkid -o value -s UUID /dev/sda1").read().strip('\n')
- sda_isremovable = bool(int(readFile("/sys/block/sda/removable")))
- print "sda : %s, %s"%(sda_UUID, sda_isremovable)
- cfg = ""
- if sda_data != '':
- cfg += '"%s":/media/hdd\n'%sda_UUID
- confFile = open(dmconfigfile,'w')
- confFile.write(cfg)
- confFile.close()
if not path.exists("/media/hdd"):
- os.system("mkdir -p /media/hdd")
-# auto mount
- devicemanagerhotplug.autoMountOnStartup()
+ cmd = "mkdir -p /media/hdd"
+ print "CMD : ", cmd
+ os.system(cmd)
except:
print "[DeviceManager] autostart failed!"
elif reason == 1:
- devicemanagerhotplug.umountOnShutdown()
+ pass
def menu(menuid, **kwargs):
if menuid == "system":
class MessageBox_2_Summary(Screen):
skin="""
- <screen name="MessageBox_2_Summary" position="0,0" size="256,64" id="1">
- <widget source="parent.Text" render="Label" position="0,0" size="256,64" font="Regular;13" halign="center" valign="center" />
+ <screen name="MessageBox_2_Summary" position="0,0" size="%d,%d" id="1">
+ <widget source="parent.Text" render="Label" position="0,0" size="%d,%d" font="Regular;%d" halign="center" valign="center" />
</screen>
"""
-
+ def __init__(self, session, parent):
+ w,h = session.summary_desktop.size().width(), session.summary_desktop.size().height()
+ self.skin = self.skin % (w, h, w, h, h/7)
+ Screen.__init__(self, session, parent = parent)