8dfa7fe61c4959b3f7d53213c62d9626cd65b71d
[tablet-suite] / src / backup / .svn / text-base / pcsbackuputils.py.svn-base
1
2 from pcsbackupinfo import *
3 import zipfile
4 import os
5 import xml.dom.minidom
6
7
8 def copyOssoBackupConfigFiles(destination, mountPath):    
9     """ Copy all osso-backup .conf files to the given path. The device must be
10     already mounted in the mountPath.
11     
12     Attributes:
13     - String mountPath - Path of the folder where the device is mounted
14     - String destination - Destination folder path where config files should be
15             copied to.
16             
17     """
18     os.system("cp %s/etc/osso-backup/applications/*.conf %s" %
19         (mountPath, destination))
20           
21      
22 def mountDevice(user, ip, path):
23     # Mount device file system using sshfs in the given path
24     try:
25         if not os.path.exists(path):
26             createFolder(path)
27         os.system('sshfs %s@%s:/ %s' % (user, ip, path))
28     except:
29         raise Exception("Error while mounting device file system")
30
31
32 def unmountDevice(path):
33     try:
34         os.system('fusermount -uz %s' % path)
35     except:
36         raise Exception("Error while unmounting device file system")
37         
38         
39 def createFolder(complete_path):
40     if not os.path.exists(complete_path):
41         os.makedirs(complete_path)
42
43     # FIXME
44     return True
45
46
47 def removePath(complete_path):
48     for entry in os.listdir(complete_path):
49         if os.path.isdir(entry):
50             removePath(os.path.join(complete_path, entry))
51         else:
52             os.remove(os.path.join(complete_path, entry))
53     os.rmdir(complete_path)
54    
55     
56 def getDeviceBackupList(mountPoint):
57     """This function return a list of backupInfo objects for each backup found
58     in the mount point.
59     
60     """
61     deviceBackups = []
62     mmc1 = '%s/media/mmc1/backups' % mountPoint
63     mmc2 = '%s/media/mmc2/backups' % mountPoint
64     
65     if os.path.exists(mmc1):
66         deviceBackups += _getDeviceBackupsInfo(mmc1)
67     if os.path.exists(mmc2):
68         deviceBackups += _getDeviceBackupsInfo(mmc2)
69         
70     return deviceBackups
71         
72         
73 def copy(original, destination):
74     original = original.replace(" ", "\ ")
75     destination = destination.replace(" ", "\ ")
76     createFolder(destination)
77     os.system("cp %s %s" % (original, destination))
78
79
80 def getSize(path):
81     if not os.path.exists(path):
82         return False
83     if os.path.isdir(path):
84         files_and_folders = os.listdir(path)
85         sum_size = 0
86         for entry in files_and_folders:
87             if os.path.isdir(os.path.join(path, entry)):
88                 sum_size += getSize(os.path.join(path, entry))
89             else:
90                 try:
91                     sum_size += os.stat(os.path.join(path, entry)).st_size
92                 except:
93                     sum_size += 1
94         return sum_size
95     else:
96         return os.stat(path).st_size
97
98         
99 def getBackupFilesPath(backupPath):
100     dic = {}
101     for entry in os.listdir(backupPath):
102         if entry.endswith(".zip"):
103             zip = openZip(os.path.join(backupPath, entry))
104             dic[entry.replace(".zip", "")] = zip.namelist()
105     return dic
106
107
108 def getBackupCategories(backupInfo):
109     backupPath = str(backupInfo.path)
110     if not backupInfo.fromDevice:
111         backupPath = os.path.join(backupPath, str(backupInfo._name))
112     categoriesList = []
113     for entry in os.listdir(backupPath):
114         if entry.endswith(".zip"):
115             categoriesList.append(entry.replace(".zip", ""))
116     return categoriesList
117
118
119 def writeBackupFilesPath(paths_dictionary, file_path):
120     try:
121         file = open(file_path, "w")
122     except:
123         return False
124     for category in paths_dictionary.keys():
125         file.write("[" + category + "]\n")
126         for path in paths_dictionary[category]:
127             file.write(path + "\n")
128     
129     file.close()
130     
131 def openZip(zipPath, mode="r"):
132     """ Open a .zip file using python ZipFile library.
133         
134         Attributes:
135             String zipPath - The directory path to the file
136             String mode - "w" to open file for writting.
137                         "a" to open file for appending.
138                         "r" to open file for reading.
139                 
140     """
141     try:
142         zip = zipfile.ZipFile(zipPath, mode)
143         return zip
144     except zipfile.BadZipfile, msg:
145         raise IOError("Problem while opening %s: %s" % (zipPath, msg))
146     except:
147         raise
148
149 def closeZip(zipfile):
150     zipfile.close()
151     
152 def zip(zipfile, path):
153     # Compress the file in the given path to the zipfile
154     try:
155         zipfile.write(path.encode('UTF'))
156         return True
157     except:
158         return False
159     
160 def rebootDevice(deviceIp):
161     return os.system("ssh root@%s reboot" % deviceIp) == 0
162     
163
164 def _parseMetadata(metadata_path):
165     document = xml.dom.minidom.parse(metadata_path)
166     node = document.getElementsByTagName("size")[0]
167     size = int(str(node.firstChild.nodeValue))
168     node = document.getElementsByTagName("timestamp")[0]
169     objDate = datetime.fromtimestamp(float(str(node.firstChild.nodeValue)))
170     return size, str(objDate)
171
172 def _getDeviceBackupsInfo(memoryCardPath):
173     deviceBackups = []
174     for backup in os.listdir(memoryCardPath):
175         temporaryFolder = os.path.join(memoryCardPath, backup)
176         if os.path.isdir(temporaryFolder):
177             metadataPath = os.path.join(temporaryFolder,'backup.metadata')
178             if os.path.exists(metadataPath):
179                 size, date = _parseMetadata(metadataPath)
180                 backupInfo = PcsBackupInfo(backup, temporaryFolder, size)
181                 backupInfo.setDate(date)
182                 deviceBackups.append(backupInfo)
183     return deviceBackups
184