-
Notifications
You must be signed in to change notification settings - Fork 12
/
fslinstall.py
2022 lines (1823 loc) · 85.1 KB
/
fslinstall.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/python
# Handle unicode encoding
import locale
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()
import curses
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP
fsli_C_FAILED = 1
fsli_C_OK = 2
fsli_C_SKIP = 4
fsli_C_WARN = 3
class Version(object):
def __init__(self,version_string):
v_vals = version_string.split('.')
for v in v_vals:
if not v.isdigit():
raise ValueError('Bad version string')
self.major = int(v_vals[0])
try:
self.minor = int(v_vals[1])
except IndexError:
self.minor = 0
try:
self.patch = int(v_vals[2])
except IndexError:
self.patch = 0
try:
self.hotfix = int(v_vals[3])
except IndexError:
self.hotfix = 0
def __repr__(self):
return "Version(%s,%s,%s,%s)" % (self.major, self.minor, self.patch, self.hotfix)
def __str__(self):
if self.hotfix == 0:
return "%s.%s.%s" % (self.major, self.minor, self.patch)
else:
return "%s.%s.%s.%s" % (self.major, self.minor, self.patch, self.hotfix)
def __ge__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self > other or self == other:
return True
return False
def __le__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self < other or self == other:
return True
return False
def __cmp__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self.__lt__(other):
return -1
if self.__gt__(other):
return 1
return 0
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self.major < other.major:
return True
if self.major > other.major:
return False
if self.minor < other.minor:
return True
if self.minor > other.minor:
return False
if self.patch < other.patch:
return True
if self.patch > other.patch:
return False
if self.hotfix < other.hotfix:
return True
if self.hotfix > other.hotfix:
return False
# major, minor and patch all match so this is not less than
return False
def __gt__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self.major > other.major:
return True
if self.major < other.major:
return False
if self.minor > other.minor:
return True
if self.minor < other.minor:
return False
if self.patch > other.patch:
return True
if self.patch < other.patch:
return False
if self.hotfix > other.hotfix:
return True
if self.hotfix < other.hotfix:
return False
# major, minor and patch all match so this is not less than
return False
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self.major == other.major and self.minor == other.minor and self.patch == other.patch and self.hotfix == other.hotfix:
return True
return False
def __ne__(self, other):
if not isinstance(other, Version):
return NotImplemented
if self.__eq__(other):
return False
return True
version = Version('2.0.20')
class FslIResult(object):
SUCCESS = 0
WARN = 1
ERROR = 2
def __init__(self,result,status,message):
self.result = result
self.status = status
self.message = message
def __nonzero__(self):
self.status
class Vendor(object):
def __init__(self, name):
self.name = name
self.releases = []
class Platform(object):
def __init__(self, name):
self.name = name
self.vendors={}
def __repr__(self):
self.name
def addVendor(self,vname):
self.vendors[vname] = Vendor(vname)
class InstallFailed(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def centred_x(scr, text):
(_, width) = scr.getmaxyx()
return width/2 - len(text)/2
def init_colours():
curses.init_pair(fsli_C_FAILED, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(fsli_C_OK, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(fsli_C_WARN, curses.COLOR_YELLOW, curses.COLOR_BLACK)
curses.init_pair(fsli_C_SKIP, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
class shell_colours(object):
default = '\033[0m'
rfg_kbg = '\033[91m'
gfg_kbg = '\033[92m'
yfg_kbg = '\033[93m'
mfg_kbg = '\033[95m'
yfg_bbg = '\033[104;93m'
bfg_kbg = '\033[34m'
bold = '\033[1m'
class MsgUser(object):
__debug = False
__quiet = False
@classmethod
def debugOn(cls):
cls.__debug = True
@classmethod
def debugOff(cls):
cls.__debug = False
@classmethod
def quietOn(cls):
cls.__quiet = True
@classmethod
def quietOff(cls):
cls.__quiet = False
@classmethod
def isquiet(cls):
return cls.__quiet
@classmethod
def isdebug(cls):
return cls.__debug
@classmethod
def debug(cls, message, newline=True):
if cls.__debug:
from sys import stderr
mess = str(message)
if newline:
mess += "\n"
stderr.write(mess)
@classmethod
def message(cls, msg, tui=False):
if cls.__quiet:
return
if tui:
tui.info.addstr(msg)
tui.info.refresh()
else:
print msg
@classmethod
def question(cls, msg, tui=False):
if tui:
pass
else:
print msg,
@classmethod
def skipped(cls, msg, tui=False):
if cls.__quiet:
return
if tui:
tui.info.addstr("[Skipped] ", curses.A_BOLD | curses.color_pair(fsli_C_SKIP))
tui.info.addstr(msg)
tui.info.refresh()
else:
print "".join( (shell_colours.mfg_kbg, "[Skipped] ", shell_colours.default, msg ) )
@classmethod
def ok(cls, msg, tui=False):
if cls.__quiet:
return
if tui:
tui.info.addstr("[OK] ", curses.A_BOLD | curses.color_pair(fsli_C_OK))
tui.info.addstr(msg)
tui.info.refresh()
else:
print "".join( (shell_colours.gfg_kbg, "[OK] ", shell_colours.default, msg ) )
@classmethod
def failed(cls, msg, tui=False):
if tui:
tui.info.addstr("[FAILED] ", curses.A_BOLD | curses.color_pair(fsli_C_FAILED))
tui.info.addstr(msg)
tui.info.refresh()
else:
print "".join( (shell_colours.rfg_kbg, "[FAILED] ", shell_colours.default, msg ) )
@classmethod
def warning(cls, msg, tui=False):
if cls.__quiet:
return
if tui:
tui.info.addstr("[Warning] ", curses.A_BOLD | curses.color_pair(fsli_C_WARN) )
tui.info.addstr(msg)
tui.info.refresh()
else:
print "".join( (shell_colours.bfg_kbg, shell_colours.bold, "[Warning]", shell_colours.default, " ", msg ) )
class Progress_bar(object):
def __init__(self, tui=False, x=0, y=0, mx=1, numeric=False):
if tui:
self.screen = tui.progress
else:
self.screen = False
self.x = x
self.y = y
if self.screen:
(_,self.width) = self.screen.getmaxyx()
else:
self.width = 50
self.current = 0
self.max = mx
self.numeric = numeric
def update(self, reading):
from sys import stdout
if MsgUser.isquiet():
return
percent = reading * 100 / self.max
cr = '\r'
if not self.screen:
if not self.numeric:
bar = '#' * int(percent)
else:
bar = "/".join((str(reading), str(self.max))) + ' - ' + str(percent) + "%\033[K"
stdout.write(cr)
stdout.write(bar)
stdout.flush()
self.current = percent
else:
bar = '#' * self.width
nhash = int(self.width * (percent/100.0))
self.screen.addnstr(self.y,self.x,bar,nhash)
if percent == 100:
stdout.write(cr)
if not self.numeric:
stdout.write(" " * int(percent))
stdout.write(cr)
stdout.flush()
else:
stdout.write(" " * ( len(str(self.max))*2 + 8))
stdout.write(cr)
stdout.flush()
def tempFileName(mode='r',close=False):
'''Return a name for a temporary file - uses mkstemp to create the file and returns a tuple (file object, file name).
Opens as read-only unless mode specifies otherwise. If close is set to True will close the file before returning.
The file object is a fdopen file object so lacks a useable file name.'''
from tempfile import mkstemp
from os import fdopen
(tmpfile, fname) = mkstemp()
file_obj = fdopen(tmpfile, mode)
if close:
file_obj.close()
return (file_obj, fname)
def run_cmd_countlines(command, maxnumber, tui=False, as_root=False ):
'''Run the command and return result. Prints a progress bar scaled such that the number of output lines is a percentage of maxnumber'''
import subprocess as sp
command_line = command.split(' ')
if as_root:
command_line.insert(0, 'sudo')
cmd = sp.Popen(command_line, stdout=sp.PIPE, stderr=sp.PIPE, bufsize=0)
prog = Progress_bar(mx = maxnumber, tui = tui)
lines = 0
while cmd.poll() is None:
cmd.stdout.flush()
_ = cmd.stdout.readline()
lines += 1
prog.update(lines)
(output, error) = cmd.communicate()
if cmd.returncode:
return FslIResult('', FslIResult.ERROR, error)
return FslIResult(output, FslIResult.SUCCESS, '')
def run_cmd_dropstdout(command, as_root=False):
'''Run the command and return result.'''
import subprocess as sp
command_line = command.split(' ')
if as_root:
command_line.insert(0, 'sudo')
cmd = sp.Popen(command_line, stdout=None, stderr=sp.PIPE)
(_, error) = cmd.communicate()
if cmd.returncode:
return FslIResult('', FslIResult.ERROR, error)
return FslIResult('', FslIResult.SUCCESS, '')
def run_cmd(command, as_root=False):
'''Run the command and return result.'''
import subprocess as sp
command_line = command.split(' ')
if as_root:
command_line.insert(0, 'sudo')
cmd = sp.Popen(command_line, stdout=sp.PIPE, stderr=sp.PIPE)
MsgUser.debug("Will call %s" % (command_line))
(output, error) = cmd.communicate()
if cmd.returncode:
MsgUser.debug("An error occured (%s, %s)" % (cmd.returncode, error))
return FslIResult('', FslIResult.ERROR, error)
MsgUser.debug("Command completed successfully (%s)" % (output))
return FslIResult(output, FslIResult.SUCCESS, '')
def safe_delete(fs_object, as_root=False):
'''Delete file/folder, becoming root if necessary. Run some sanity checks on object'''
from os import path
banned_items = [ '/', '/usr', '/usr/bin', '/usr/local', '/bin',
'/sbin', '/opt', '/Library', '/System', '/System/Library',
'/var', '/tmp', '/var/tmp', '/lib', '/lib64', '/Users',
'/home', '/Applications', '/private', '/etc', '/dev',
'/Network', '/net', '/proc']
if path.isdir(fs_object):
del_opts = "-rf"
else:
del_opts = '-f'
if object in banned_items:
return FslIResult('', FslIResult, 'Will not delete %s!' % (object))
command_line = " ".join(('rm', del_opts, fs_object))
return run_cmd(command_line, as_root)
def copy_file(fname, destination, as_root):
'''Copy a file using sudo if necessary'''
from os import path
MsgUser.debug("Copying %s to %s (as root? %s)" %(fname, destination, as_root))
if path.isdir(fname):
return FslIResult('', FslIResult.ERROR, 'Source (%s) is not a file!' % (fname))
if path.isdir(destination):
# Ensure that copying into a folder we have a terminating slash
destination = destination.rstrip('/') + "/"
copy_opts = '-p'
command_line = " ".join(('cp', copy_opts, fname, destination))
return run_cmd(command_line, as_root)
def file_contains(fname, search_for):
'''Equivalent of grep'''
from re import compile,escape
regex = compile(escape(search_for))
found = False
f = open(fname, 'r')
for l in f:
if regex.search(l):
found = True
break
f.close()
return found
def file_contains_1stline(search_for, fname):
'''Equivalent of grep - returns first occurrence'''
from re import compile, escape
regex = compile(escape(search_for))
found = ''
MsgUser.debug("In file_contains_1stline.")
MsgUser.debug("Looking for %s in %s." % (search_for, fname ))
f = open(fname, 'r')
for l in f:
if regex.search(l):
found = l
break
f.close()
return found
def line_string_replace(line, search_for, replace_with):
from re import sub,escape
return sub(escape(search_for), escape(replace_with), line)
def line_starts_replace(line, search_for, replace_with):
if line.startswith(search_for):
return replace_with + '\n'
return line
def move_file(from_file, to_file, requires_root = False):
'''Move a file, using /bin/cp via sudo if requested. Will work around known bugs in python.'''
from shutil import move
from os import remove, path
result = FslIResult("", FslIResult.SUCCESS, '')
if requires_root:
cmd_result = run_cmd(" ".join(("/bin/cp",from_file,to_file)), as_root=True)
if cmd_result.status == FslIResult.ERROR:
MsgUser.debug(cmd_result.message)
result = FslIResult('', FslIResult.ERROR, "Failed to move %s (%s)" % (from_file, cmd_result.message))
else:
remove(from_file)
else:
try:
move(from_file, to_file)
except OSError, e:
# Handle bug in some python versions on OS X writing to NFS home folders
# Python tries to preserve file flags but NFS can't do this. It fails to catch
# this error and ends up leaving the file in the original and new locations!
if e.errno == 45:
# Check if new file has been created:
if path.isfile(to_file):
# Check if original exists
if path.isfile(from_file):
# Destroy original and continue
remove(from_file)
else:
cmd_result = run_cmd("/bin/cp %s %s" % (from_file, to_file), as_root=False)
if cmd_result.status == FslIResult.ERROR:
MsgUser.debug(cmd_result.message)
result = FslIResult('', FslIResult.ERROR, "Failed to copy from %s (%s)" % (from_file, cmd_result.message))
remove(from_file)
else:
raise
except:
raise
return result
def edit_file(fname, edit_function, search_for, replace_with, requires_root):
'''Search for a simple string in the file given and replace it with the new text'''
from os import remove
result = FslIResult('', FslIResult.SUCCESS, '')
try:
(tmpfile, tmpfname) = tempFileName(mode='w')
src = open(fname)
for line in src:
line = edit_function(line, search_for, replace_with)
tmpfile.write(line)
src.close()
tmpfile.close()
try:
cmd_result = move_file(tmpfname, fname, requires_root)
if cmd_result.status == FslIResult.ERROR:
MsgUser.debug(cmd_result.message)
result = FslIResult('', FslIResult.ERROR, "Failed to edit %s (%s)" % (fname, cmd_result.message))
except:
remove(tmpfname)
raise
except IOError, e:
MsgUser.debug(e.strerror)
result = FslIResult('', FslIResult.ERROR, "Failed to edit %s" % (fname))
MsgUser.debug("Modified %s (search %s; replace %s)." % (fname, search_for, replace_with))
return result
def add_to_file(fname, add_lines, requires_root):
'''Add lines to end of a file'''
from os import remove
result = FslIResult('', FslIResult.SUCCESS, '')
try:
(tmpfile, tmpfname) = tempFileName(mode='w')
src = open(fname)
for line in src:
tmpfile.write(line)
src.close()
tmpfile.write('\n')
for line in add_lines:
tmpfile.write(line)
tmpfile.write('\n')
tmpfile.close()
try:
cmd_result = move_file(tmpfname, fname, requires_root)
if cmd_result.status == FslIResult.ERROR:
MsgUser.debug(cmd_result.message)
result = FslIResult('', FslIResult.ERROR, "Failed to add to file %s (%s)" % (fname, cmd_result.message))
except:
remove(tmpfname)
raise
except IOError, e:
MsgUser.debug(e.strerror + tmpfname + fname)
result = FslIResult('', FslIResult.ERROR, "Failed to add to file %s" % (fname))
MsgUser.debug("Modified %s (added %s)" % (fname, '\n'.join(add_lines)))
return result
def create_file(fname, lines, requires_root):
'''Create a new file containing lines given'''
from os import remove
result = FslIResult('', FslIResult.SUCCESS, '')
try:
(tmpfile, tmpfname) = tempFileName(mode='w')
for line in lines:
tmpfile.write(line)
tmpfile.write('\n')
tmpfile.close()
try:
cmd_result = move_file(tmpfname, fname, requires_root)
if cmd_result.status == FslIResult.ERROR:
MsgUser.debug(cmd_result.message)
result = FslIResult('', FslIResult.ERROR, "Failed to edit %s (%s)" % (fname, cmd_result.message))
except:
remove(tmpfname)
raise
except IOError, e:
MsgUser.debug(e.strerror)
result = FslIResult('', FslIResult.ERROR, "Failed to create %s" % (fname))
MsgUser.debug("Created %s (added %s)" % (fname, '\n'.join(lines)))
return result
def find_X11():
'''Function to find X11 install on Mac OS X and confirm it is compatible. Advise user to download Xquartz if necessary'''
from os import path
from subprocess import Popen,PIPE, STDOUT
MsgUser.message("Checking for X11 windowing system (required for FSL GUIs).")
bad_versions=[]
xquartz_url = 'http://xquartz.macosforge.org/landing/'
xbins = [ 'XQuartz.app', 'X11.app' ]
xloc = '/Applications/Utilities'
xbin = ''
for x in xbins:
if path.exists('/'.join((xloc,x))):
xbin = x
if xbin != '':
# Find out what version is installed
x_v_cmd = [ '/usr/bin/mdls', '-name', 'kMDItemVersion', '/'.join((xloc, xbin)) ]
cmd = Popen(x_v_cmd, stdout=PIPE, stderr=STDOUT)
(vstring,_) = cmd.communicate()
if cmd.returncode:
MsgUser.debug("Error finding the version of X11 (%s)" % (vstring))
# App found, but can't tell version, warn the user
result = FslIResult(0, FslIResult.WARN, "X11 (required for FSL GUIs) is installed but I can't tell what the version is.")
else:
# Returns:
# kMDItemVersion = "2.3.6"\n
(_,_,version) = vstring.strip().split()
if version.startswith('"'):
version = version[1:-1]
if version in bad_versions:
result = FslIResult(0, FslIResult.WARN, "X11 (required for FSL GUIs) is a version that is known to cause problems. We suggest you upgrade to the latest XQuartz release from %s" % (xquartz_url))
else:
MsgUser.debug("X11 found and is not a bad version (%s: %s)." %(xbin, version))
result = FslIResult(0, FslIResult.SUCCESS, 'X11 software (required for FSL GUIs) is installed.')
else:
# No X11 found, warn the user
result = FslIResult(0, FslIResult.WARN, "The FSL GUIs require the X11 window system which I can't find in the usual places. You can download a copy from %s - you will need to install this before the GUIs will function" % (xquartz_url))
return result
class UnsupportedOs(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Os(object):
'''Work out which platform we are running on'''
def __init__(self):
import os
if os.name != 'posix': raise UnsupportedOs('We only support OS X/Linux')
import platform
self.os = platform.system().lower()
self.arch = platform.machine()
self.applever = ''
if self.os == 'darwin':
self.vendor = 'apple'
self.version = Version(platform.release())
(self.applever,_,_) = platform.mac_ver()
if self.arch == 'Power Macintosh': raise UnsupportedOs('We no longer support PowerPC')
self.glibc = ''
self.bits = ''
elif self.os == 'linux':
if hasattr(platform, 'linux_distribution'):
# We have a modern python (>2.4)
(self.vendor, version, _) = platform.linux_distribution(full_distribution_name=0)
else:
(self.vendor, version, _) = platform.dist()
self.vendor = self.vendor.lower()
self.version = Version(version)
self.glibc = platform.libc_ver()
if self.arch == 'x86_64':
self.bits = '64'
else:
self.bits = '32'
raise UnsupportedOs("We no longer support 32 bit Linux. If you must use 32 bit Linux then try building from our sources.")
else:
raise UnsupportedOs("We don't support this OS, you should try building from our sources.")
# Now check for supported OS
def is_writeable(location):
'''Check if we can write to the location given'''
import tempfile, errno
writeable = True
try:
tfile = tempfile.NamedTemporaryFile(mode='w+b', dir=location)
tfile.close()
except OSError,e:
if e.errno == errno.EACCES:
writeable = False
else:
raise
return writeable
def is_writeable_as_root(location):
'''Check if sudo can write to a given location'''
# This requires us to use sudo
from os import remove, path
(f, fname) = tempFileName(mode='w')
f.write("FSL")
f.close()
result = False
tmptarget = '/'.join((location, path.basename(fname)))
MsgUser.debug( " ".join(('/bin/cp', fname, tmptarget)) )
cmd_result = run_cmd(" ".join(('/bin/cp', fname, tmptarget)), as_root=True)
if cmd_result.status == FslIResult.SUCCESS:
result = True
remove(fname)
cmd_result = run_cmd(" ".join(('/bin/rm', '-f', tmptarget)), as_root=True)
else:
MsgUser.debug( cmd_result.message )
remove(fname)
result = False
MsgUser.debug("Writeable as root? %s" % (result))
return result
def md5File(filename):
'''Returns the MD5 sum of the given file.'''
try:
import hashlib
fhash = hashlib.md5()
bs = fhash.block_size
except ImportError:
import md5
fhash = md5.new()
# For efficiency read file in 8K blocks
bs = 8192
f = open(filename,'rb')
while True:
nextblk = f.read(bs)
if not nextblk:
break
fhash.update(nextblk)
f.close()
return fhash.hexdigest()
def parsemd5sumfile(md5string):
'''Returns MD5 sum extracted from the output of md5(sum) from OS X/Linux platforms'''
if md5string.startswith('MD5'):
# OSX format
(_,_,_,md5) = md5string.split()
else:
(md5,_) = md5string.split()
return md5
def checkmd5Sum(filename, md5F):
'''Cross-platform verification of md5 sum. Takes file to check and file containing the output of md5(sum) on your platform for the file'''
fileMD5 = md5File(filename)
f = open(md5F)
md5sum = f.readline().strip()
f.close()
# Linux has format MD5 (*)filename
# OS X has format MD5 (filename) = MD5
md5 = parsemd5sumfile(md5sum)
MsgUser.debug( "Comparing: %s to %s" % (fileMD5, md5))
return fileMD5 == md5
def open_url(url, start=0, timeout=20):
import urllib2
import socket
socket.setdefaulttimeout(timeout)
MsgUser.debug("Attempting to download %s." % (url))
try:
req = urllib2.Request(url)
if start != 0:
req.headers['Range'] = 'bytes=%s-' % (start)
rf = urllib2.urlopen(req)
except urllib2.HTTPError, e:
MsgUser.debug("%s %s" % (url, e.msg))
return FslIResult(False, FslIResult.ERROR, "Cannot find file %s on server (%s). Try again later." % (url, e.msg))
except urllib2.URLError, e:
errno = e.reason.args[0]
message = e.reason.args[1]
if errno == 8:
# Bad host name
MsgUser.debug("%s %s" % (url, 'Unable to find FSL download server in the DNS'))
else:
# Other error
MsgUser.debug("%s %s" % (url, message))
return FslIResult(False, FslIResult.ERROR, "Cannot find %s (%s). Try again later." % (url, message))
except socket.timeout, e:
MsgUser.debug(e)
return FslIResult(False, FslIResult.ERROR, "Failed to contact FSL web site. Try again later.")
return FslIResult(rf, FslIResult.SUCCESS,'')
def download_file(url, localf, timeout=20, tui=False):
'''Get a file from the url given storing it in the local file specified'''
import socket, time
result = open_url(url, 0, timeout)
if result.status == FslIResult.SUCCESS:
rf = result.result
else:
return result
metadata = rf.info()
rf_size = int(metadata.getheaders("Content-Length")[0])
dl_size = 0
block = 16384
if tui:
(y,x) = tui.getyx()
else:
x = 0
y= 0
pb = Progress_bar( tui, x, y, rf_size, numeric=True)
for attempt in range(1,6):
# Attempt download 5 times before giving up
pause = timeout
try:
try:
lf = open(localf, 'ab')
except:
return FslIResult(False, FslIResult.ERROR, "Failed to create temporary file.")
while True:
buf = rf.read(block)
if not buf:
break
dl_size += len(buf)
lf.write(buf)
pb.update( dl_size )
lf.close()
except (IOError, socket.timeout), e:
MsgUser.debug(e.strerror)
MsgUser.message("\nDownload failed re-trying (%s)..." % attempt)
pause = 0
if dl_size != rf_size:
time.sleep(pause)
MsgUser.message("\nDownload failed re-trying (%s)..." % attempt)
result = open_url(url, dl_size, timeout)
if result.status == FslIResult.ERROR:
MsgUser.debug(result.message)
else:
rf = result.result
else:
break
if dl_size != rf_size:
return FslIResult(False, FslIResult.ERROR, "Failed to download file.")
return FslIResult(True, FslIResult.SUCCESS, '')
def getAndReportMD5(url):
from os import remove
(_, md5fname) = tempFileName(mode='w',close=True)
a_result = download_file(url, md5fname)
if a_result.status == FslIResult.SUCCESS:
MD5file = open(md5fname)
MD5sum = MD5file.readline().strip()
MD5file.close()
remove(md5fname)
MsgUser.message("MD5 checksum is: %s" % (parsemd5sumfile(MD5sum)))
else:
MsgUser.debug("Failed to download checksum.")
return
def getAndVerifyMD5(url, checkF):
from os import remove
result = FslIResult(True, FslIResult.SUCCESS, '')
(_,md5fname) = tempFileName(mode='w',close=True)
a_result = download_file(url, md5fname)
if a_result.status == FslIResult.SUCCESS:
if not checkmd5Sum(checkF, md5fname):
MsgUser.debug("Failed to verify %s." % (checkF))
result = FslIResult(False, FslIResult.ERROR, 'File %s appears to be corrupt.' % (checkF))
else:
MsgUser.debug("%s verified." % (checkF))
result = FslIResult(True, FslIResult.SUCCESS, 'File verified.')
else:
MsgUser.debug("Unable to download checksum for %s" % (checkF))
result = FslIResult(False, FslIResult.WARN, 'Unable to download checksum for %s.' % (checkF))
remove(md5fname)
return result
def fastest_mirror(main_site='http://fsl.fmrib.ox.ac.uk/fsldownloads/',
mirror_file='fslmirrorlist.txt',
timeout=20,
serverport=80):
'''Find the fastest mirror for FSL downloads.'''
import urllib2
import socket
from time import time
MsgUser.debug("Calculating fastest mirror")
socket.setdefaulttimeout(timeout)
download_url=main_site
if not main_site.endswith('/'):
main_site += '/'
mirror_url=main_site + mirror_file
# Get the mirror list from the url
fastestmirrors = {}
try:
response = urllib2.urlopen(url=mirror_url)
except urllib2.HTTPError, e:
MsgUser.debug("%s %s" % (mirror_url, e.msg))
return FslIResult('', FslIResult.ERROR, "Failed to download mirror list (%s). Try again later." % (e.msg))
except urllib2.URLError, e:
if isinstance(e.reason, socket.timeout):
MsgUser.debug("Time out trying %s" % (mirror_url))
else:
MsgUser.debug(e.reason.args[1])
return FslIResult('', FslIResult.ERROR, "Failed to find main FSL web site. Try again later.")
except socket.timeout, e:
MsgUser.debug(e)
return FslIResult('', FslIResult.ERROR, "Failed to contact FSL web site. Try again later.")
except:
raise
mirrorlist = response.read().strip().split('\n')
MsgUser.debug("Received the following mirror list %s" % (mirrorlist))
if len(mirrorlist) == 0:
mirrorlist[0]=download_url
try:
servers = dict([ (k.split('/')[2], k.split('/',3)[3]) for k in mirrorlist])
except IndexError:
return FslIResult('', FslIResult.ERROR, "Failed to get a valid list of FSL mirror sites. Are you connected to the internet?")
# Check timings from the urls specified
if len(servers) > 1:
for mirror in servers.keys():
MsgUser.debug( "Trying %s" % (mirror) )
then = time()
try:
mysock=socket.create_connection((mirror, serverport), timeout)
pingtime = time() - then
mysock.close()
fastestmirrors[pingtime] = mirror
MsgUser.debug("Mirror responded in %s seconds" % (pingtime))
except socket.gaierror, e:
MsgUser.debug("%s can't be resolved" % (e))
except socket.timeout, e:
MsgUser.debug(e)
if len(fastestmirrors) == 0:
return FslIResult('', FslIResult.ERROR, 'Failed to contact any download sites.')
host = fastestmirrors[min(fastestmirrors.keys())]
download_url = '/'.join(('http:/', host, servers[host]))
else:
download_url = mirrorlist[0]
return FslIResult(download_url, FslIResult.SUCCESS, 'Success')
def get_web_version(download_url, timeout=20):
'''Download the file given by download_url and return the version info held within'''
import urllib2
import socket
socket.setdefaulttimeout(timeout)
MsgUser.debug("Looking for latest version at %s." % (download_url))
try:
response = urllib2.urlopen(url=download_url)
except urllib2.HTTPError, e:
MsgUser.debug("%s %s" % (download_url, e.msg))
return FslIResult(False, FslIResult.ERROR, "Cannot find file %s on server (%s). Try again later." % (download_url, e.msg))
except urllib2.URLError, e:
errno = e.reason.args[0]
message = e.reason.args[1]
if errno == 8:
# Bad host name
MsgUser.debug("%s %s" % (download_url, 'Unable to find FSL download server in the DNS'))
else:
# Other error
MsgUser.debug("%s %s" % (download_url, message))
return FslIResult(Version('0.0.0'), FslIResult.ERROR, "Failed to find FSL web site. Try again later.")
try:
v_line = response.read().strip()
server_v = Version(v_line)
MsgUser.debug("Found a version number of %s." % (server_v))
result = FslIResult(server_v, FslIResult.SUCCESS, 'Success')
except ValueError, e:
MsgUser.debug(str(e) + " %s\n" % (v_line))
result = FslIResult(Version('0.0.0'), FslIResult.ERROR, 'Server reported bad version (%s)' %(v_line))
return result
def get_fsldir():
'''Find the installed version of FSL using FSLDIR or location of this script'''
from os import path, environ
try:
fsldir = environ['FSLDIR']
if not path.exists( fsldir ):
# FSLDIR environment variable is incorrect!
MsgUser.warning('FSLDIR environment variable is corrupt, ignoring...')
MsgUser.debug('FSLDIR is set to %s - this folder does not appear to exist' % (fsldir) )
fsldir = ''
except KeyError:
# FSLDIR not set for this user's environment - try to find FSL
# Installer should be in FSLDIR/etc
fsldir = path.dirname(path.dirname( path.realpath( __file__ )))
v_file = "/".join((fsldir,'etc/fslversion'))
if not path.exists( v_file ):
# No FSL install found
fsldir = ''
return fsldir
def tarf_version(tarfile):
'''Takes the path to a tar(gz) FSL install file and works out what version it is.'''
from os import path