source: src/mlx/update.py@ 959:45c27c0c294f

python3
Last change on this file since 959:45c27c0c294f was 958:25df1de263cd, checked in by István Váradi <ivaradi@…>, 6 years ago

More data is read in one call when reading the files to update

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