forked from sqall01/alertR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alertRinstaller.py
1409 lines (1032 loc) · 36.6 KB
/
alertRinstaller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python2
# written by sqall
# twitter: https://twitter.com/sqall01
# blog: http://blog.h4des.org
# github: https://github.com/sqall01
#
# Licensed under the GNU Public License, version 2.
import socket
import ssl
import httplib
import os
import sys
import time
import logging
import json
import hashlib
import tempfile
import shutil
import stat
import math
import importlib
import threading
import optparse
################ GLOBAL CONFIGURATION DATA ################
# used log level
# valid log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL
loglevel = logging.INFO
# repository information
host = "raw.githubusercontent.com"
port = 443
serverPath = "/sqall01/alertR/master/"
################ GLOBAL CONFIGURATION DATA ################
# ca certificate of used github repository
# (/etc/ssl/certs/DigiCert_High_Assurance_EV_Root_CA.pem)
caCertificate = "-----BEGIN CERTIFICATE-----\n" \
+ "MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\n" \
+ "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \
+ "d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n" \
+ "ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\n" \
+ "MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n" \
+ "LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n" \
+ "RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n" \
+ "+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\n" \
+ "PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\n" \
+ "xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\n" \
+ "Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\n" \
+ "hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\n" \
+ "EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\n" \
+ "MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\n" \
+ "FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n" \
+ "nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n" \
+ "eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n" \
+ "hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n" \
+ "Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n" \
+ "vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n" \
+ "+OkuE6N36B9K\n" \
+ "-----END CERTIFICATE-----\n"
# internal class that is used as an enum to represent the type of file update
class _FileUpdateType:
NEW = 1
DELETE = 2
MODIFY = 3
# HTTPSConnection like class that verifies server certificates
class VerifiedHTTPSConnection(httplib.HTTPSConnection):
# needs socket and ssl lib
def __init__(self, host, port=None, servercert_file=None,
key_file=None, cert_file=None, strict=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
httplib.HTTPSConnection.__init__(self, host, port, key_file,
cert_file, strict, timeout)
self.servercert_file = servercert_file
# overwrites the original version of httplib (python 2.6)
def connect(self):
"Connect to a host on a given (SSL) port."
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
# the only thing that has to be changed in the original function from
# httplib (tell ssl.wrap_socket to verify server certificate)
self.sock = ssl.wrap_socket(sock, self.key_file,
self.cert_file, cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.servercert_file)
# this class processes all actions concerning the update process
class Updater:
def __init__(self, host, port, serverPath, caFile, instance,
targetLocation):
# used for logging
self.fileName = os.path.basename(__file__)
# the updater object is not thread safe
self.updaterLock = threading.Semaphore(1)
# set global configured data
self.version = 0
self.rev = 0
self.instance = instance
self.instanceLocation = targetLocation
# set update server configuration
self.host = host
self.port = port
self.serverPath = serverPath
self.caFile = caFile
# needed to keep track of the newest version
self.newestVersion = self.version
self.newestRev = self.rev
self.newestFiles = None
self.lastChecked = 0.0
self.repoInstanceLocation = None
# size of the download chunks
self.chunkSize = 4096
# internal function that acquires the lock
def _acquireLock(self):
logging.debug("[%s]: Acquire lock." % self.fileName)
self.updaterLock.acquire()
# internal function that releases the lock
def _releaseLock(self):
logging.debug("[%s]: Release lock." % self.fileName)
self.updaterLock.release()
# internal function that checks which files are new and which files have
# to be updated
#
# return a dict of files that are affected by this update (and how) or None
def _checkFilesToUpdate(self):
# check if the last version information check was done shortly before
# or was done at all
# => if not get the newest version information
if ((time.time() - self.lastChecked) > 60
or self.newestFiles == None):
if self._getNewestVersionInformation() is False:
logging.error("[%s]: Not able to get version "
% self.fileName
+ "information for checking files.")
return None
counterUpdate = 0
counterNew = 0
# get all files that have to be updated
filesToUpdate = dict()
for clientFile in self.newestFiles.keys():
# check if file already exists
# => check if file has to be updated
if os.path.exists(self.instanceLocation + clientFile):
f = open(self.instanceLocation + clientFile, 'r')
sha256Hash = self._sha256File(f)
f.close()
# check if file has changed
# => if not ignore it
if sha256Hash == self.newestFiles[clientFile]:
logging.debug("[%s]: Not changed: '%s'"
% (self.fileName, clientFile))
continue
# => if it has changed add it to the list of files to update
else:
logging.debug("[%s]: New version: '%s'"
% (self.fileName, clientFile))
filesToUpdate[clientFile] = _FileUpdateType.MODIFY
counterUpdate += 1
# => if the file does not exist, just add it
else:
logging.debug("[%s]: New file: '%s'"
% (self.fileName, clientFile))
filesToUpdate[clientFile] = _FileUpdateType.NEW
counterNew += 1
logging.info("[%s]: Files to modify: %d; New files: %d"
% (self.fileName, counterUpdate, counterNew))
return filesToUpdate
# internal function that checks the needed permissions to
# perform the update
#
# return True or False
def _checkFilePermissions(self, filesToUpdate):
# check permissions for each file that is affected by this update
for clientFile in filesToUpdate.keys():
# check if the file just has to be modified
if filesToUpdate[clientFile] == _FileUpdateType.MODIFY:
# check if the file is not writable
# => cancel update
if not os.access(self.instanceLocation + clientFile, os.W_OK):
logging.error("[%s]: File '%s' is not writable."
% (self.fileName, clientFile))
return False
logging.debug("[%s]: File '%s' is writable."
% (self.fileName, clientFile))
# check if the file is new and has to be created
elif filesToUpdate[clientFile] == _FileUpdateType.NEW:
logging.debug("[%s]: Checking write permissions for new "
% self.fileName
+ "file: '%s'"
% clientFile)
folderStructure = clientFile.split("/")
# check if the new file is located in the root directory
# of the instance
# => check root directory of the instance for write permissions
if len(folderStructure) == 1:
if not os.access(self.instanceLocation, os.W_OK):
logging.error("[%s]: Folder './' is not "
% self.fileName
+ "writable.")
return False
logging.debug("[%s]: Folder './' is writable."
% self.fileName)
# if new file is not located in the root directory
# of the instance
# => check all folders on the way to the new file for write
# permissions
else:
tempPart = ""
for filePart in folderStructure:
# check if folder exists
if os.path.exists(self.instanceLocation + tempPart
+ "/" + filePart):
# check if folder is not writable
# => cancel update
if not os.access(self.instanceLocation + tempPart
+ "/" + filePart, os.W_OK):
logging.error("[%s]: Folder '.%s/%s' is not "
% (self.fileName, tempPart, filePart)
+ "writable.")
return False
logging.debug("[%s]: Folder '.%s/%s' is writable."
% (self.fileName, tempPart, filePart))
tempPart += "/"
tempPart += filePart
# check if the file has to be deleted
elif filesToUpdate[clientFile] == _FileUpdateType.DELETE:
raise NotImplementedError("Feature not yet implemented.")
return True
# internal function that creates sub directories in the target directory
# for the given file location
#
# return True or False
def _createSubDirectories(self, fileLocation, targetDirectory):
folderStructure = fileLocation.split("/")
if len(folderStructure) != 1:
try:
i = 0
tempPart = ""
while i < (len(folderStructure) - 1):
# check if the sub directory already exists
# => if not create it
if not os.path.exists(targetDirectory + tempPart + "/"
+ folderStructure[i]):
logging.debug("[%s]: Creating directory '%s/%s/%s'."
% (self.fileName, targetDirectory, tempPart,
folderStructure[i]))
os.mkdir(targetDirectory + tempPart + "/"
+ folderStructure[i])
# if the sub directory already exists then check
# if it is a directory
# => raise an exception if it is not
elif not os.path.isdir(targetDirectory + tempPart + "/"
+ folderStructure[i]):
raise ValueError("Location '%s' already exists "
% (tempPart + "/" + folderStructure[i])
+ "and is not a directory.")
# only log if sub directory already exists
else:
logging.debug("[%s]: Directory '%s/%s/%s' already "
% (self.fileName, targetDirectory, tempPart,
folderStructure[i])
+ "exists.")
tempPart += "/"
tempPart += folderStructure[i]
i += 1
except Exception as e:
logging.exception("[%s]: Creating directory structure for "
% self.fileName
+ "'%s' failed."
% fileLocation)
return False
return True
# internal function that downloads the given file into a temporary file
# and checks if the given hash is correct
#
# return None or the handle to the temporary file
def _downloadFile(self, fileLocation, fileHash):
logging.info("[%s]: Downloading file: '%s'"
% (self.fileName, fileLocation))
# create temporary file
try:
fileHandle = tempfile.TemporaryFile()
except Exception as e:
logging.exception("[%s]: Creating temporary file failed."
% self.fileName)
return None
# download file from server
conn = VerifiedHTTPSConnection(self.host, self.port, self.caFile)
try:
conn.request("GET", self.serverPath + "/"
+ self.repoInstanceLocation + "/" + fileLocation)
response = conn.getresponse()
# check if server responded correctly
# => download file
if response.status == 200:
# get the size of the response
fileSize = -1
try:
headers = response.getheaders()
for header in headers:
if header[0] == "content-length":
fileSize = int(header[1])
break
except:
fileSize = -1
# check if the file size was part of the header
# and we can output the status of the download
showStatus = False
if fileSize > 0:
showStatus = True
maxChunks = int(math.ceil(float(fileSize)
/ float(self.chunkSize)))
# actually download file
chunkCount = 0
printedPercentage = 0
while True:
chunk = response.read(self.chunkSize)
if not chunk:
break
fileHandle.write(chunk)
# output status of the download
chunkCount += 1
if showStatus:
if chunkCount > maxChunks:
showStatus = False
logging.warning("[%s]: Concent information of "
% self.fileName
+ "received header flawed. Stopping "
+ "to show download status.")
continue
else:
percentage = int((float(chunkCount)
/ float(maxChunks)) * 100)
if (percentage / 10) > printedPercentage:
printedPercentage = percentage / 10
logging.info("[%s]: Download: %d%%"
% (self.fileName, printedPercentage * 10))
else:
raise ValueError("Server response code not 200 (was %d)."
% response.status)
except Exception as e:
logging.exception("[%s]: Downloading file '%s' from the "
% (self.fileName, fileLocation)
+ "server failed.")
return None
# calculate sha256 hash of the downloaded file
fileHandle.seek(0)
sha256Hash = self._sha256File(fileHandle)
fileHandle.seek(0)
# check if downloaded file has the correct hash
if sha256Hash != fileHash:
logging.error("[%s]: Temporary file does not have the "
% self.fileName
+ "correct hash.")
return None
logging.info("[%s]: Successfully downloaded file: '%s'"
% (self.fileName, fileLocation))
return fileHandle
# internal function that calculates the sha256 hash of the file
def _sha256File(self, fileHandle):
fileHandle.seek(0)
sha256 = hashlib.sha256()
while True:
data = fileHandle.read(128)
if not data:
break
sha256.update(data)
return sha256.hexdigest()
# internal function that gets the newest version information from the
# online repository
#
# return True or False
def _getNewestVersionInformation(self):
conn = VerifiedHTTPSConnection(self.host, self.port, self.caFile)
# get repository information from the server
repoInfoString = ""
try:
conn.request("GET", self.serverPath + "/repoInfo.json")
response = conn.getresponse()
# check if server responded correctly
if response.status == 200:
repoInfoString = response.read()
else:
raise ValueError("Server response code not 200 (was %d)."
% response.status)
except Exception as e:
logging.exception("[%s]: Getting repository information failed."
% self.fileName)
return False
# parse repository information string
try:
jsonData = json.loads(repoInfoString)
if not isinstance(jsonData, dict):
raise ValueError("Received repository information is "
+ "not of type dict.")
if not self.instance in jsonData["instances"].keys():
raise ValueError("Instance '%s' is not managed by "
% self.instance
+ "used repository.")
self.repoInstanceLocation = str(
jsonData["instances"][self.instance]["location"])
except Exception as e:
logging.exception("[%s]: Parsing repository information failed."
% self.fileName)
return False
# get version string from the server
versionString = ""
try:
conn.request("GET", self.serverPath + "/"
+ self.repoInstanceLocation + "/instanceInfo.json")
response = conn.getresponse()
# check if server responded correctly
if response.status == 200:
versionString = response.read()
else:
raise ValueError("Server response code not 200 (was %d)."
% response.status)
except Exception as e:
logging.exception("[%s]: Getting version information failed."
% self.fileName)
return False
# parse version information string
try:
jsonData = json.loads(versionString)
version = float(jsonData["version"])
rev = int(jsonData["rev"])
newestFiles = jsonData["files"]
if not isinstance(newestFiles, dict):
raise ValueError("Key 'files' is not of type dict.")
except Exception as e:
logging.exception("[%s]: Parsing version information failed."
% self.fileName)
return False
logging.debug("[%s]: Newest version information: %.3f-%d."
% (self.fileName, version, rev))
# check if the version on the server is newer than the used one
# or we have no information about the files
# => update information
if (version > self.newestVersion or
(rev > self.newestRev and version == self.newestVersion)
or self.newestFiles is None):
# update newest known version information
self.newestVersion = version
self.newestRev = rev
self.newestFiles = newestFiles
self.lastChecked = time.time()
return True
# function that gets the newest version information from the
# online repository
def getNewestVersionInformation(self):
self._acquireLock()
result = self._getNewestVersionInformation()
self._releaseLock()
return result
# function that updates this instance of the alertR infrastructure
def updateInstance(self):
self._acquireLock()
# check all files that have to be updated
filesToUpdate = self._checkFilesToUpdate()
if filesToUpdate is None:
logging.error("[%s] Checking files for update failed."
% self.fileName)
self._releaseLock()
return False
if len(filesToUpdate) == 0:
logging.info("[%s] No files have to be updated."
% self.fileName)
self._releaseLock()
return True
# check file permissions of the files that have to be updated
if self._checkFilePermissions(filesToUpdate) is False:
logging.info("[%s] Checking file permissions failed."
% self.fileName)
self._releaseLock()
return False
# download all files that have to be updated
downloadedFileHandles = dict()
for fileToUpdate in filesToUpdate.keys():
# only download file if it is new or has to be modified
if (filesToUpdate[fileToUpdate] == _FileUpdateType.NEW
or filesToUpdate[fileToUpdate] == _FileUpdateType.MODIFY):
# download new files, if one file fails
# => close all file handles and abort update process
downloadedFileHandle = self._downloadFile(fileToUpdate,
self.newestFiles[fileToUpdate])
if downloadedFileHandle is None:
logging.error("[%s]: Downloading files from the "
% self.fileName
+ "repository failed. Aborting update process.")
# close all temporary file handles
# => temporary file is automatically deleted
for fileHandle in downloadedFileHandles.keys():
downloadedFileHandles[fileHandle].close()
self._releaseLock()
return False
else:
downloadedFileHandles[fileToUpdate] = downloadedFileHandle
# copy all files to the correct location
for fileToUpdate in filesToUpdate.keys():
# check if the file has to be deleted
if filesToUpdate[fileToUpdate] == _FileUpdateType.DELETE:
raise NotImplementedError("Not yet implemented.")
# check if the file is new
# => create all sub directories (if they are missing)
elif filesToUpdate[fileToUpdate] == _FileUpdateType.NEW:
self._createSubDirectories(fileToUpdate, self.instanceLocation)
# copy file to correct location
try:
logging.debug("[%s]: Copying file '%s' to alertR instance "
% (self.fileName, fileToUpdate)
+ "directory.")
dest = open(self.instanceLocation + "/" + fileToUpdate, 'wb')
shutil.copyfileobj(downloadedFileHandles[fileToUpdate], dest)
dest.close()
except Exception as e:
logging.exception("[%s]: Copying file '%s' failed."
% (self.fileName, fileToUpdate))
self._releaseLock()
return False
# check if the hash of the copied file is correct
f = open(self.instanceLocation + "/" + fileToUpdate, 'r')
sha256Hash = self._sha256File(f)
f.close()
if sha256Hash != self.newestFiles[fileToUpdate]:
logging.error("[%s]: Hash of file '%s' is not correct "
% (self.fileName, fileToUpdate)
+ "after copying.")
self._releaseLock()
return False
# change permission of files that have to be executable
if (fileToUpdate == "alertRclient.py"
or fileToUpdate == "alertRserver.py"):
logging.debug("[%s]: Changing permissions of '%s'."
% (self.fileName, fileToUpdate))
try:
os.chmod(self.instanceLocation + "/" + fileToUpdate,
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
except Exception as e:
logging.exception("[%s]: Changing permissions of '%s' "
% (self.fileName, fileToUpdate)
+ "failed.")
self._releaseLock()
return False
# close all temporary file handles
# => temporary file is automatically deleted
for fileHandle in downloadedFileHandles.keys():
downloadedFileHandles[fileHandle].close()
self._releaseLock()
return True
# this function asks the user for confirmation
def userConfirmation():
while True:
try:
localInput = raw_input("(y/n): ")
except KeyboardInterrupt:
print "Bye."
sys.exit(0)
except:
continue
if localInput.strip().upper() == "Y":
return True
elif localInput.strip().upper() == "N":
return False
else:
print "Invalid input."
# this function checks if the dependencies are satisfied
def checkDependencies(dependencies):
fileName = os.path.basename(__file__)
# check if all pip dependencies are met
if "pip" in dependencies.keys():
for pip in dependencies["pip"]:
importName = pip["import"]
packet = pip["packet"]
# only get version if it exists
version = None
if "version" in pip.keys():
version = pip["version"]
# try to import needed module
temp = None
try:
logging.info("[%s]: Checking module '%s'."
% (fileName, importName))
temp = importlib.import_module(importName)
except Exception as e:
logging.error("[%s]: Module '%s' not installed."
% (fileName, importName))
print
print "The needed module '%s' is not installed." % importName,
print "You can install the module by executing",
print "'pip install %s'" % packet,
print "(if you do not have installed pip, you can install it",
print "on Debian like systems by executing",
print "'apt-get install python-pip')."
return False
# if a version string is given in the instance information
# => check if the installed version satisfies the needed version
if not version is None:
installedVersion = temp.__version__.split(".")
neededVersion = version.split(".")
maxLength = 0
if len(installedVersion) > len(neededVersion):
maxLength = len(installedVersion)
else:
maxLength = len(neededVersion)
# check the needed version and the installed version
versionCorrect = True
versionCheckFailed = False
try:
for i in range(maxLength):
if int(installedVersion[i]) > int(neededVersion[i]):
versionCorrect = True
break
elif int(installedVersion[i]) < int(neededVersion[i]):
versionCorrect = False
break
except Exception as e:
logging.error("[%s]: Could not verify installed version "
% fileName
+ "of module '%s'."
% importName)
versionCheckFailed = True
# if the version check failed, ask the user for confirmation
if versionCheckFailed is True:
print
print "Could not automatically verify the installed",
print "version of the module '%s'." % importName,
print "You have to verify the version yourself."
print
print "Installed version: %s" % temp.__version__
print "Needed version: %s" % version
print
print "Do you have a version installed that satisfies",
print "the needed version?"
if not userConfirmation():
versionCorrect = False
# if the version is not correct => abort the next checks
if versionCorrect is False:
print
print "The needed version '%s'" % version,
print "of module '%s' is not satisfied" % importName,
print "(you have version '%s'" % temp.__version__,
print "installed)."
print "Please update your installed version of the pip",
print "packet '%s'." % packet
return False
# check if all other dependencies are met
if "other" in dependencies.keys():
for other in dependencies["other"]:
importName = other["import"]
# only get version if it exists
version = None
if "version" in other.keys():
version = other["version"]
# check if the version has to be checked manually
# (this can happen for example if the module has no
# __version__ string or can only be imported as 'root')
if other["manual"] is True:
print
print "Can not automatically verify the installed",
print "version of the module '%s'." % importName,
print "You have to verify the version and if",
print "it is installed yourself."
print
print "Needed version: %s" % version
print
print "Do you have a version installed that satisfies",
print "the needed version?"
if not userConfirmation():
versionCorrect = False
# check the installed module automatically
else:
# try to import needed module
temp = None
try:
logging.info("[%s]: Checking module '%s'."
% (fileName, importName))
temp = importlib.import_module(importName)
except Exception as e:
logging.error("[%s]: Module '%s' not installed."
% (fileName, importName))
print
print "The needed module '%s' is not" % importName,
print "installed. You need to install it before",
print "you can use this alertR instance."
return False
# if a version string is given in the instance information
# => check if the installed version satisfies the
# needed version
if not version is None:
installedVersion = temp.__version__.split(".")
neededVersion = version.split(".")
maxLength = 0
if len(installedVersion) > len(neededVersion):
maxLength = len(installedVersion)
else:
maxLength = len(neededVersion)
# check the needed version and the installed version
versionCorrect = True
versionCheckFailed = False
try:
for i in range(maxLength):
if (int(installedVersion[i]) >
int(neededVersion[i])):
versionCorrect = True
break
elif (int(installedVersion[i]) <
int(neededVersion[i])):
versionCorrect = False
break
except Exception as e:
logging.error("[%s]: Could not verify installed "
% fileName
+ "version of module '%s'."
% importName)
versionCheckFailed = True
# if the version check failed, ask the user
# for confirmation
if versionCheckFailed is True:
print
print "Could not automatically verify the installed",
print "version of the module '%s'." % importName,
print "You have to verify the version yourself."
print
print "Installed version: %s" % temp.__version__
print "Needed version: %s" % version
print
print "Do you have a version installed that satisfies",
print "the needed version?"
if not userConfirmation():
versionCorrect = False
# if the version is not correct => abort the next checks
if versionCorrect is False:
print
print "The needed version '%s'" % version,
print "of module '%s' is not satisfied" % importName,
print "(you have version '%s'" % temp.__version__,
print "installed)."
print "Please update your installed version."