Initial commit (Vesion 0.1)
[tablet-suite] / src / backup / .svn / text-base / pcsbackupmanager.py.svn-base
1 import os
2
3 from PyQt4.QtCore import *
4 from zipfile import *
5
6 import pcsbackuputils as utils
7
8
9 HOME = os.path.expanduser("~")
10 USER_HOST = "root"
11 DEVICES_POINT = "%s/.pcsuite/devices/" % HOME
12
13
14 class PcsBackupManager(QObject):
15
16     def __init__(self):
17         QObject.__init__(self)
18         self._backupList = []
19
20     def loadBackups(self):
21         return False
22
23     def saveBackups(self):
24         return False
25
26     def getBackupList(self):
27         return None
28     
29     def createBackup(self, backup_name, path, host_ip, categories, comment=""):
30         return False
31
32     def removeBackup(self, backup_name):
33         return False
34
35     def getBackupInfo(self, backupName):
36         return None
37     
38     def renameBackup(self, backupName, newName):
39         return False
40     
41     def changeBackupComment(self, backupName, new_comment):
42         return False
43     
44     def listBackupContent(self, backupName):
45         content = []
46         backupInfo = self.getBackupInfo(backupName)
47         backupPath = backupInfo.getPath()
48         fullPath = os.path.join(str(backupPath), str(backupName))
49         
50         for entry in os.listdir(fullPath):
51             if entry.endswith(".zip"):
52                 zipfile = utils.openZip(os.path.join(fullPath, entry), "r")
53                 for member in zipfile.namelist():
54                     folders = member.split("/")
55                     memberName = "../" + "/".join([folders[-2], folders[-1]])
56                     content.append(memberName)
57         return content
58     
59     def restoreBackup(self, backupInfo, host_ip, categories):
60         """ Restore a PC backup to device with given IP address.
61         
62         Attributes:
63         String backupInfo - Object representing the backup
64         String host_ip - IP address of device.
65         Dictionary categories - dictionary with categories as keys and with
66                             value True if that category should be restored.
67                             
68         """
69         self.setRestoreInProgress(True)
70         # Set restore needed paths
71         devicePath = os.path.join(DEVICES_POINT, "%s" % host_ip)
72         mountPath = os.path.join(devicePath, "Root" )
73         tempPath = os.path.join(mountPath, "tmp/paths")
74         restScriptsPath = ("/etc/osso-backup/restore.d/always")
75         try:
76             utils.mountDevice(USER_HOST, host_ip, mountPath)
77             # Get backup location depending from backup source
78             if backupInfo == None:
79                 return False
80             if backupInfo.fromDevice:
81                 backup_path = backupInfo.getPath()
82             else:
83                 backup_path = os.path.join(str(backupInfo.getPath()), 
84                                            str(backupInfo.getName()))
85             # Get backup files list for each category and write it on a file
86             # that will be needed by restore scripts.
87             pathsDictonary = utils.getBackupFilesPath(backup_path)
88             if utils.writeBackupFilesPath(pathsDictonary, tempPath) == False:
89                 return False
90             # --- Initialize restore progress ---
91             currentSize = 0
92             # Get total number of files to restore
93             numberOfFiles = 0
94             for categ in pathsDictonary:
95                 for file in pathsDictonary[categ]:
96                     numberOfFiles += 1
97             # Get size of all categories being restored
98             totalSize = 0
99             for file in os.listdir(backup_path):
100                 if file.endswith(".zip"):
101                     categ = file[:-4]
102                     if categories[categ]:
103                         catPath = os.path.join(backup_path, file)
104                         zip = utils.openZip(catPath)
105                         for member in zip.namelist():
106                             totalSize += zip.getinfo(member).file_size
107             # Extract zip files to device
108             for entry in os.listdir(backup_path):
109                 category = entry[:-4]
110                 if entry.endswith(".zip") and categories[category]:
111                     zipPath = os.path.join(backup_path, entry)
112                     zip = utils.openZip(zipPath)
113                     # Update restore progress, extract current f print "member %s: %.2f" % (member, zip.getinfo(member).file_size)ile and emit
114                     # progress sinal
115                     for member in zip.namelist():
116                         if not self.restoreInProgress:
117                             return 0
118                         percentage = "%.1f" % self.computePercentage(totalSize,
119                                                                 currentSize)
120                         
121                         status = (percentage, category, numberOfFiles, totalSize)
122                         self.emit(SIGNAL("restoreProgress"), status)
123                         zip.extract(member, devicePath)
124                         currentSize += zip.getinfo(member).file_size
125                     percentage = "%.1f" % ((currentSize / float(totalSize)) * 100)
126                     status = (percentage, category, numberOfFiles, totalSize)
127                     self.emit(SIGNAL("restoreProgress"), status)
128                     zip.close()
129             # Execute restore scripts
130             os.system("ssh %s@%s ..%s/*.sh %s" % (USER_HOST, host_ip, 
131                                                   restScriptsPath, tempPath))
132             self.setRestoreInProgress(False)
133             # --- Restore finished ---
134         finally:
135             utils.unmountDevice(mountPath)
136             
137     
138     def computePercentage(self, totalSize, currentSize):
139         if totalSize == 0:
140             percentage = 100
141         else:
142             percentage = (currentSize / float(totalSize)) * 100
143             if percentage > 100:
144                 percentage = 100
145         return percentage
146     
147     def copy(self, sourcePath, destinationPath):
148         numberOfFiles = 0
149         for entry in os.listdir(sourcePath):
150             zipPath = os.path.join(sourcePath, entry)
151             if zipPath.endswith(".zip"):
152                 zip = utils.openZip(zipPath)
153                 numberOfFiles += len(zip.namelist())
154         totalSize = float(utils.getSize(sourcePath))
155         currentSize = 0
156         self.emit(SIGNAL("copyProgress"), ("0.00", numberOfFiles, totalSize))
157         for entry in os.listdir(sourcePath):
158             if not self.copyInProgress:
159                 utils.removePath(destinationPath)
160                 return 0
161             entryPath = os.path.join(sourcePath, entry)
162             utils.copy(entryPath, destinationPath)
163             currentSize += utils.getSize(entryPath)
164             progress = "%.2f" % ((currentSize / totalSize) * 100)
165             self.emit(SIGNAL("copyProgress"), (progress, numberOfFiles,
166                                                     totalSize))
167             
168