source: src/mlx/update.py@ 785:7fa99e74e8ab

version_0.37_maint
Last change on this file since 785:7fa99e74e8ab was 785:7fa99e74e8ab, checked in by István Váradi <ivaradi@…>, 8 years ago

Made the update procedure more resilient to errors

File size: 21.2 KB
Line 
1
2from config import Config
3from util import utf2unicode
4
5import os
6import sys
7import urllib2
8import tempfile
9import socket
10import subprocess
11import hashlib
12import traceback
13
14if os.name=="nt":
15 import win32api
16
17#------------------------------------------------------------------------------
18
19## @package mlx.update
20#
21# Automatic update handling.
22#
23# The program can update itself automatically. For this purpose it maintains a
24# manifest of the files installed containing the relative paths, sizes and
25# checksums of each files. When the program starts up, this manifest file is
26# downloaded from the update server and is compared to the local one. Then the
27# updated and new files are downloaded with names that are created by appending
28# the checksum to the actual name, so as not to overwrite any existing files at
29# this stage. If all files are downloaded, the downloaded files are renamed to
30# their real names. On Windows, the old file is removed first to avoid trouble
31# with 'busy' files. If removing a file fails, the file will be moved to a
32# temporary directory, that will be removed when the program starts the next
33# time.
34
35#------------------------------------------------------------------------------
36
37manifestName = "MLXMANIFEST"
38toremoveName = "toremove"
39
40#------------------------------------------------------------------------------
41
42class Manifest(object):
43 """The manifest of the files.
44
45 The manifest file consists of one line for each file. Each line contains 3
46 items separated by tabs:
47 - the path of the file relative to the distribution's root
48 - the size of the file
49 - the MD5 sum of the file."""
50 def __init__(self):
51 """Construct the manifest."""
52 self._files = {}
53
54 @property
55 def files(self):
56 """Get an iterator over the files.
57
58 Each file is returned as a 3-tuple with items as in the file."""
59 for (path, (size, sum)) in self._files.iteritems():
60 yield (path, size, sum)
61
62 def copy(self):
63 """Create a copy of the manifest."""
64 manifest = Manifest()
65 manifest._files = self._files.copy()
66 return manifest
67
68 def addFile(self, path, size, sum):
69 """Add a file to the manifest."""
70 self._files[path] = (size, sum)
71
72 def addFiles(self, baseDirectory, subdirectory):
73 """Add the files in the given directory and subdirectories of it to the
74 manifest."""
75 directory = baseDirectory
76 for d in subdirectory: directory = os.path.join(directory, d)
77
78 for entry in os.listdir(directory):
79 fullPath = os.path.join(directory, entry)
80 if os.path.isfile(fullPath):
81 size = os.stat(fullPath).st_size
82 sum = hashlib.md5()
83 with open(fullPath, "rb") as f:
84 while True:
85 data = f.read(4096)
86 if data: sum.update(data)
87 else: break
88 self.addFile("/".join(subdirectory + [entry]), size,
89 sum.hexdigest())
90 elif os.path.isdir(fullPath):
91 self.addFiles(baseDirectory, subdirectory + [entry])
92
93 def readFrom(self, file):
94 """Read a manifest from the given file object."""
95 for line in iter(file.readline, ""):
96 (path, size, sum) = line.strip().split("\t")
97 self._files[path] = (int(size), sum)
98
99 def writeInto(self, file):
100 """Write the manifest into the file at the given path."""
101 for (path, (size, sum)) in self._files.iteritems():
102 file.write("%s\t%d\t%s\n" % (path, size, sum))
103
104 def compare(self, other):
105 """Compare this manifest with the other one.
106
107 This returns a tuple of two lists:
108 - the files that are either different or are present in other, but not
109 here. Each file is returned as a 3-tuple as with other functions, the
110 size and sum are those of the new file.
111 - the paths of the files that are present here, but not in other."""
112 modifiedAndNew = []
113 for (path, otherSize, otherSum) in other.files:
114 if path in self._files:
115 (size, sum) = self._files[path]
116 if size!=otherSize or sum!=otherSum:
117 modifiedAndNew.append((path, otherSize, otherSum))
118 else:
119 modifiedAndNew.append((path, otherSize, otherSum))
120
121 removed = [path for path in self._files if path not in other._files]
122
123 return (modifiedAndNew, removed)
124
125 def __contains__(self, path):
126 """Determine if the given path is in the manifest."""
127 return path in self._files
128
129 def __getitem__(self, path):
130 """Get data of the file with the given path."""
131 return self._files[path] if path in self._files else None
132
133#------------------------------------------------------------------------------
134
135class ClientListener(object):
136 """A listener that sends any requests via a socket."""
137 def __init__(self, sock):
138 """Construct the listener."""
139 self._sock = sock
140
141 def downloadingManifest(self):
142 """Called when the downloading of the manifest has started."""
143 self._send(["downloadingManifest"])
144
145 def downloadedManifest(self):
146 """Called when the manifest has been downloaded."""
147 self._send(["downloadedManifest"])
148
149 def needSudo(self):
150 """Called when an admin-level program must be called to complete the
151 update.
152
153 This is not valid from a client, as that client is supposed to be the
154 admin-level program :)"""
155 assert False
156
157 def setTotalSize(self, numToModifyAndNew, totalSize, numToRemove,
158 numToRemoveLocal):
159 """Called when starting the downloading of the files."""
160 self._send(["setTotalSize", str(numToModifyAndNew), str(totalSize),
161 str(numToRemove), str(numToRemoveLocal)])
162
163 def setDownloaded(self, downloaded):
164 """Called periodically after downloading a certain amount of data."""
165 self._send(["setDownloaded", str(downloaded)])
166
167 def startRenaming(self):
168 """Called when the renaming of the downloaded files is started."""
169 self._send(["startRenaming"])
170
171 def renamed(self, path, count):
172 """Called when a file has been renamed."""
173 self._send(["renamed", path, str(count)])
174
175 def startRemoving(self):
176 """Called when the removing of files has started."""
177 self._send(["startRemoving"])
178
179 def removed(self, path, count):
180 """Called when a file has been removed."""
181 self._send(["removed", path, str(count)])
182
183 def writingManifest(self):
184 """Called when we have started writing the manifest."""
185 self._send(["writingManifest"])
186
187 def done(self):
188 """Called when the update has completed."""
189 self._send(["done"])
190
191 def failed(self, what):
192 """Called when something has failed."""
193 self._send(["failed", what])
194
195 def _send(self, words):
196 """Send the given words via the socket."""
197 self._sock.send("\t".join(words) + "\n")
198
199#------------------------------------------------------------------------------
200
201def readLocalManifest(directory):
202 """Read the local manifest from the given directory."""
203 manifestPath = os.path.join(directory, manifestName)
204
205 manifest = Manifest()
206 try:
207 with open(manifestPath, "rt") as f:
208 manifest.readFrom(f)
209 except Exception, e:
210 print "Error reading the manifest, ignoring:", utf2unicode(str(e))
211 manifest = Manifest()
212
213 return manifest
214
215#------------------------------------------------------------------------------
216
217def prepareUpdate(directory, updateURL, listener):
218 """Prepare the update by downloading the manifest and comparing it with the
219 local one."""
220 manifest = readLocalManifest(directory)
221
222 updateURL += "/" + os.name
223
224 listener.downloadingManifest()
225 f = None
226 try:
227 updateManifest = Manifest()
228 f= urllib2.urlopen(updateURL + "/" + manifestName)
229 updateManifest.readFrom(f)
230
231 except Exception, e:
232 error = utf2unicode(str(e))
233 print >> sys.stderr, "Error downloading manifest:", error
234 listener.failed(error)
235 return None
236 finally:
237 if f is not None: f.close()
238
239 listener.downloadedManifest()
240
241 (modifiedAndNew, removed) = manifest.compare(updateManifest)
242
243 return (manifest, updateManifest, modifiedAndNew, removed)
244
245#------------------------------------------------------------------------------
246
247def getToremoveFiles(directory):
248 """Add the files to remove from the toremove directory."""
249 toremove = []
250 toremoveDirectory = os.path.join(directory, toremoveName)
251 if os.path.isdir(toremoveDirectory):
252 for entry in os.listdir(toremoveDirectory):
253 toremove.append(os.path.join(toremoveName, entry))
254 return toremove
255
256#------------------------------------------------------------------------------
257
258def createLocalPath(directory, path):
259 """Create a local path from the given manifest path."""
260 localPath = directory
261 for element in path.split("/"):
262 localPath = os.path.join(localPath, element)
263 return localPath
264
265#------------------------------------------------------------------------------
266
267def getToremoveDir(toremoveDir, directory):
268 """Get the path of the directory that will contain the files that are to be
269 removed."""
270 if toremoveDir is None:
271 toremoveDir = os.path.join(directory, toremoveName)
272 try:
273 os.mkdir(toremoveDir)
274 except:
275 pass
276
277 return toremoveDir
278
279#------------------------------------------------------------------------------
280
281def removeFile(toremoveDir, directory, path):
282 """Remove the file at the given path or store it in a temporary directory.
283
284 If the removal of the file fails, it will be stored in a temporary
285 directory. This is useful for files thay may be open and cannot be removed
286 right away."""
287 try:
288 os.remove(path)
289 except:
290 try:
291 sum = hashlib.md5()
292 sum.update(path)
293 toremoveDir = getToremoveDir(toremoveDir, directory)
294 targetPath = os.path.join(toremoveDir, sum.hexdigest())
295 try:
296 os.remove(targetPath)
297 except:
298 pass
299 os.rename(path, targetPath)
300 except Exception, e:
301 print "Cannot remove file " + path + ": " + utf2unicode(str(e))
302
303#------------------------------------------------------------------------------
304
305def updateFiles(directory, updateURL, listener,
306 manifest, modifiedAndNew, removed, localRemoved):
307 """Update the files according to the given information."""
308 totalSize = 0
309 for (path, size, sum) in modifiedAndNew:
310 totalSize += size
311
312 listener.setTotalSize(len(modifiedAndNew), totalSize,
313 len(removed), len(localRemoved))
314
315 downloaded = 0
316 fin = None
317 toremoveDir = None
318
319 try:
320 updateURL += "/" + os.name
321
322 for (path, size, sum) in modifiedAndNew:
323 targetFile = createLocalPath(directory, path)
324 targetFile += "."
325 targetFile += sum
326
327 targetDirectory = os.path.dirname(targetFile)
328 if not os.path.isdir(targetDirectory):
329 os.makedirs(targetDirectory)
330
331 with open(targetFile, "wb") as fout:
332 fin = urllib2.urlopen(updateURL + "/" + path)
333 while True:
334 data = fin.read(4096)
335 if not data:
336 break
337 fout.write(data)
338 downloaded += len(data)
339 listener.setDownloaded(downloaded)
340 fin.close()
341 fin = None
342
343 listener.startRenaming()
344 count = 0
345 for (path, size, sum) in modifiedAndNew:
346 targetFile = createLocalPath(directory, path)
347
348 downloadedFile = targetFile + "." + sum
349 if os.name=="nt" and os.path.isfile(targetFile):
350 removeFile(toremoveDir, directory, targetFile)
351 os.rename(downloadedFile, targetFile)
352 count += 1
353 listener.renamed(path, count)
354
355 listener.startRemoving()
356 count = 0
357 removed += localRemoved
358 removed.sort(reverse = True)
359 for path in removed:
360 removePath = createLocalPath(directory, path)
361 removeFile(toremoveDir, directory, removePath)
362
363 removeDirectory = os.path.dirname(removePath)
364 try:
365 os.removedirs(removeDirectory)
366 except:
367 pass
368
369 count += 1
370 listener.removed(path, count)
371
372 listener.writingManifest()
373
374 manifestPath = os.path.join(directory, manifestName)
375 with open(manifestPath, "wt") as f:
376 manifest.writeInto(f)
377
378 listener.done()
379 except Exception, e:
380 exc = traceback.format_exc()
381 print >> sys.stderr, utf2unicode(exc)
382
383 error = utf2unicode(str(e))
384 print >> sys.stderr, "Error:", error
385
386 listener.failed(error)
387
388#------------------------------------------------------------------------------
389
390def isDirectoryWritable(directory):
391 """Determine if the given directory can be written."""
392 checkFile = os.path.join(directory, "writable.chk")
393 try:
394 f = open(checkFile, "wt")
395 f.close()
396 return True
397 except Exception, e:
398 return False
399 finally:
400 try:
401 os.remove(checkFile)
402 except:
403 pass
404
405#------------------------------------------------------------------------------
406
407def processMLXUpdate(buffer, listener):
408 """Process the given buffer supposedly containing a list of commands."""
409 endsWithLine = buffer[-1]=="\n"
410 lines = buffer.splitlines()
411
412 if endsWithLine:
413 buffer = ""
414 else:
415 buffer = lines[-1]
416 lines = lines[:-1]
417
418 for line in lines:
419 words = line.split("\t")
420 try:
421 command = words[0]
422 if command=="downloadingManifest":
423 listener.downloadingManifest()
424 elif command=="downloadedManifest":
425 listener.downloadedManifest()
426 elif command=="setTotalSize":
427 listener.setTotalSize(int(words[1]), long(words[2]),
428 int(words[3]), int(words[4]))
429 elif command=="setDownloaded":
430 listener.setDownloaded(long(words[1]))
431 elif command=="startRenaming":
432 listener.startRenaming()
433 elif command=="renamed":
434 listener.renamed(words[1], int(words[2]))
435 elif command=="startRemoving":
436 listener.startRemoving()
437 elif command=="removed":
438 listener.removed(words[1], int(words[2]))
439 elif command=="writingManifest":
440 listener.writingManifest()
441 elif command=="done":
442 listener.done()
443 elif command=="failed":
444 listener.failed(words[1])
445 except Exception, e:
446 print >> sys.stderr, "Failed to parse line '%s': %s" % \
447 (line, utf2unicode(str(e)))
448
449 return buffer
450
451#------------------------------------------------------------------------------
452
453def sudoUpdate(directory, updateURL, listener, manifest):
454 """Perform the update via the mlxupdate program."""
455 manifestFD = None
456 manifestFile = None
457 serverSocket = None
458 mlxUpdateSocket = None
459 try:
460 (manifestFD, manifestFile) = tempfile.mkstemp()
461 f = os.fdopen(manifestFD, "wt")
462 try:
463 manifest.writeInto(f)
464 finally:
465 f.close()
466 manifestFD = None
467
468 serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
469 serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
470 serverSocket.bind(("127.0.0.1", 0))
471 (_host, port) = serverSocket.getsockname()
472 serverSocket.listen(1)
473
474
475 if os.name=="nt":
476 win32api.ShellExecute(0, "open", os.path.join(directory, "mlxupdate"),
477 str(port) + " " + manifestFile + " " + updateURL, "", 1)
478 else:
479 process = subprocess.Popen([os.path.join(directory, "mlxupdate"),
480 str(port), manifestFile, updateURL],
481 shell = os.name=="nt")
482
483 (mlxUpdateSocket, _) = serverSocket.accept()
484 serverSocket.close()
485 serverSocket = None
486
487 buffer = ""
488 while True:
489 data = mlxUpdateSocket.recv(4096)
490 if not data:
491 break;
492
493 buffer += data
494 buffer = processMLXUpdate(buffer, listener)
495
496 mlxUpdateSocket.close()
497 mlxUpdateSocket = None
498
499 if os.name!="nt":
500 process.wait()
501
502 except Exception, e:
503 error = utf2unicode(str(e))
504 print >> sys.stderr, "Failed updating:", error
505 listener.failed(error)
506 finally:
507 if serverSocket is not None:
508 try:
509 serverSocket.close()
510 except:
511 pass
512 if mlxUpdateSocket is not None:
513 try:
514 mlxUpdateSocket.close()
515 except:
516 pass
517 if manifestFD is not None:
518 try:
519 os.close(manifestFD)
520 except:
521 pass
522 if manifestFile is not None:
523 try:
524 os.remove(manifestFile)
525 except:
526 pass
527
528
529#------------------------------------------------------------------------------
530
531def update(directory, updateURL, listener, fromGUI = False):
532 """Perform the update."""
533 try:
534 result = prepareUpdate(directory, updateURL, listener)
535 if result is None:
536 return
537
538 (manifest, updateManifest, modifiedAndNew, removed) = result
539 localRemoved = getToremoveFiles(directory)
540
541 if not modifiedAndNew and not removed and not localRemoved:
542 listener.done()
543 return
544
545 if fromGUI and not isDirectoryWritable(directory):
546 if listener.needSudo():
547 sudoUpdate(directory, updateURL, listener, updateManifest)
548 else:
549 updateFiles(directory, updateURL, listener, updateManifest,
550 modifiedAndNew, removed, localRemoved)
551 except Exception, e:
552 exc = traceback.format_exc()
553 print >> sys.stderr, utf2unicode(exc)
554
555 error = utf2unicode(str(e))
556 print >> sys.stderr, "Update error:", error
557
558 listener.failed(error)
559
560#------------------------------------------------------------------------------
561
562def updateProcess():
563 """This is called in the child process, when we need a child process."""
564 try:
565 clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
566 clientSocket.connect(("127.0.0.1", int(sys.argv[1])))
567
568 directory = os.path.dirname(sys.argv[0])
569
570 manifest = readLocalManifest(directory)
571
572 updateManifest = Manifest()
573 with open(sys.argv[2], "rt") as f:
574 updateManifest.readFrom(f)
575
576 (modifiedAndNew, removed) = manifest.compare(updateManifest)
577 localRemoved = getToremoveFiles(directory)
578
579 updateFiles(directory, sys.argv[3],
580 ClientListener(clientSocket),
581 updateManifest, modifiedAndNew, removed, localRemoved)
582 except:
583 exc = traceback.format_exc()
584 print >> sys.stderr, utf2unicode(exc)
585
586#------------------------------------------------------------------------------
587
588def buildManifest(directory):
589 """Build a manifest from the contents of the given directory, into the
590 given directory."""
591
592 manifestPath = os.path.join(directory, manifestName)
593 try:
594 os.remove(manifestPath)
595 except:
596 pass
597
598 manifest = Manifest()
599 manifest.addFiles(directory, [])
600 with open(manifestPath, "wt") as f:
601 manifest.writeInto(f)
602
603#------------------------------------------------------------------------------
604
605# if __name__ == "__main__":
606# manifest1 = Manifest()
607# manifest1.addFile("file1.exe", 3242, "40398754589435345934")
608# manifest1.addFile("dir/file2.zip", 45645, "347893245873456987")
609# manifest1.addFile("dir/file3.txt", 123, "3432434534534534")
610
611# with open("manifest1", "wt") as f:
612# manifest1.writeInto(f)
613
614# manifest2 = Manifest()
615# manifest2.addFile("file1.exe", 4353, "390734659834756349876")
616# manifest2.addFile("dir/file2.zip", 45645, "347893245873456987")
617# manifest2.addFile("dir/file4.log", 2390, "56546546546546")
618
619# with open("manifest2", "wt") as f:
620# manifest2.writeInto(f)
621
622# manifest1 = Manifest()
623# with open("manifest1", "rt") as f:
624# manifest1.readFrom(f)
625
626# manifest2 = Manifest()
627# with open("manifest2", "rt") as f:
628# manifest2.readFrom(f)
629
630# (modifiedAndNew, removed) = manifest1.compare(manifest2)
631
632# for (path, size, sum) in modifiedAndNew:
633# print "modified or new:", path, size, sum
634
635# for path in removed:
636# print "removed:", path
637
638#------------------------------------------------------------------------------
Note: See TracBrowser for help on using the repository browser.