ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/crab_util.py
Revision: 1.109
Committed: Thu Feb 4 10:34:24 2010 UTC (15 years, 2 months ago) by spiga
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_7_1_pre5
Branch point for: CRAB_2_7_1_branch
Changes since 1.108: +65 -54 lines
Log Message:
fixed check quota logic to works also if user area is not AFS

File Contents

# User Rev Content
1 spiga 1.80 ##########################################################################
2 nsmirnov 1.1 #
3     # C O N V E N I E N C E F U N C T I O N S
4     #
5     ###########################################################################
6    
7 slacapra 1.12 import string, sys, os, time
8 spiga 1.100 import ConfigParser, re, select, fcntl
9 ewv 1.89 import statvfs
10 spiga 1.100 from subprocess import Popen, PIPE, STDOUT
11 nsmirnov 1.1
12 nsmirnov 1.2 import common
13 slacapra 1.30 from crab_exceptions import CrabException
14 spiga 1.42 from ServerConfig import *
15 nsmirnov 1.1
16     ###########################################################################
17     def parseOptions(argv):
18     """
19     Parses command-line options.
20     Returns a dictionary with specified options as keys:
21     -opt1 --> 'opt1' : None
22     -opt2 val --> 'opt2' : 'val'
23     -opt3=val --> 'opt3' : 'val'
24     Usually called as
25     options = parseOptions(sys.argv[1:])
26     """
27     options = {}
28     argc = len(argv)
29     i = 0
30     while ( i < argc ):
31     if argv[i][0] != '-':
32     i = i + 1
33     continue
34     eq = string.find(argv[i], '=')
35     if eq > 0 :
36     opt = argv[i][:eq]
37     val = argv[i][eq+1:]
38     pass
39     else:
40     opt = argv[i]
41     val = None
42     if ( i+1 < argc and argv[i+1][0] != '-' ):
43     i = i + 1
44     val = argv[i]
45     pass
46     pass
47     options[opt] = val
48     i = i + 1
49     pass
50     return options
51    
52 slacapra 1.47 def loadConfig(file, config):
53 nsmirnov 1.1 """
54     returns a dictionary with keys of the form
55     <section>.<option> and the corresponding values
56     """
57 slacapra 1.47 #config={}
58 nsmirnov 1.1 cp = ConfigParser.ConfigParser()
59     cp.read(file)
60     for sec in cp.sections():
61     for opt in cp.options(sec):
62 spiga 1.79 ## temporary check. Allow compatibility
63 ewv 1.89 new_sec = sec
64 spiga 1.79 if sec == 'EDG':
65 spiga 1.80 print ('\tWARNING: The [EDG] section is now deprecated.\n\tPlease remove it and use [GRID] instead.\n')
66 ewv 1.89 new_sec = 'GRID'
67 spiga 1.79 config[new_sec+'.'+opt] = string.strip(cp.get(sec,opt))
68 nsmirnov 1.1 return config
69    
70     ###########################################################################
71     def isInt(str):
72     """ Is the given string an integer ?"""
73     try: int(str)
74     except ValueError: return 0
75     return 1
76    
77     ###########################################################################
78     def isBool(str):
79     """ Is the given string 0 or 1 ?"""
80     if (str in ('0','1')): return 1
81     return 0
82    
83     ###########################################################################
84 nsmirnov 1.3 def parseRange(range):
85     """
86     Takes as the input a string with two integers separated by
87     the minus sign and returns the tuple with these numbers:
88     'n1-n2' -> (n1, n2)
89     'n1' -> (n1, n1)
90     """
91     start = None
92     end = None
93     minus = string.find(range, '-')
94     if ( minus < 0 ):
95     if isInt(range):
96     start = int(range)
97     end = start
98     pass
99     pass
100     else:
101     if isInt(range[:minus]) and isInt(range[minus+1:]):
102     start = int(range[:minus])
103     end = int(range[minus+1:])
104     pass
105     pass
106     return (start, end)
107    
108     ###########################################################################
109 nsmirnov 1.4 def parseRange2(range):
110     """
111     Takes as the input a string in the form of a comma-separated
112     numbers and ranges
113     and returns a list with all specified numbers:
114     'n1' -> [n1]
115     'n1-n2' -> [n1, n1+1, ..., n2]
116     'n1,n2-n3,n4' -> [n1, n2, n2+1, ..., n3, n4]
117     """
118 slacapra 1.30 result = []
119     if not range: return result
120 nsmirnov 1.4
121     comma = string.find(range, ',')
122     if comma == -1: left = range
123     else: left = range[:comma]
124    
125     (n1, n2) = parseRange(left)
126     while ( n1 <= n2 ):
127 slacapra 1.11 try:
128 slacapra 1.30 result.append(n1)
129 slacapra 1.11 n1 += 1
130     pass
131     except:
132     msg = 'Syntax error in range <'+range+'>'
133     raise CrabException(msg)
134 nsmirnov 1.4
135     if comma != -1:
136 slacapra 1.11 try:
137 slacapra 1.30 result.extend(parseRange2(range[comma+1:]))
138 slacapra 1.11 pass
139     except:
140     msg = 'Syntax error in range <'+range+'>'
141     raise CrabException(msg)
142 nsmirnov 1.4
143 slacapra 1.30 return result
144 nsmirnov 1.4
145     ###########################################################################
146 nsmirnov 1.1 def findLastWorkDir(dir_prefix, where = None):
147    
148     if not where: where = os.getcwd() + '/'
149     # dir_prefix usually has the form 'crab_0_'
150     pattern = re.compile(dir_prefix)
151    
152 slacapra 1.76 file_list = [f for f in os.listdir(where) if os.path.isdir(f) and pattern.match(f)]
153 nsmirnov 1.1
154     if len(file_list) == 0: return None
155    
156     file_list.sort()
157    
158 slacapra 1.76 wdir = where + file_list[-1]
159 nsmirnov 1.1 return wdir
160    
161     ###########################################################################
162 mcinquil 1.99 def checkCRABVersion(current, url = "http://cmsdoc.cern.ch/cms/LCG/crab/config/", fileName = "allowed_releases.conf"):
163 mcinquil 1.98 """
164     _checkCRABVersion_
165    
166     compare current release with allowed releases
167     format of allowed release: ['2.6.5','2.6.6','2.7.*']
168     """
169     match_result = False
170     from Downloader import Downloader
171 spiga 1.107 blacklist = Downloader(url)
172 spiga 1.106 result =eval(blacklist.config(fileName))
173 mcinquil 1.98 current_dot = current.split('.')
174     for version in result:
175     if version.find('.') != -1:
176     version_dot = version.split('.')
177     for compare in map(None, current_dot, version_dot):
178     if compare[1].find('*') != -1:
179     return True
180     elif int(compare[0]) != int(compare[1]):
181     break
182     elif version == '*':
183     return True
184     return False
185    
186     ###########################################################################
187 nsmirnov 1.1 def importName(module_name, name):
188     """
189     Import a named object from a Python module,
190     i.e., it is an equivalent of 'from module_name import name'.
191     """
192     module = __import__(module_name, globals(), locals(), [name])
193     return vars(module)[name]
194    
195     ###########################################################################
196 slacapra 1.16 def readable(fd):
197 ewv 1.44 return bool(select.select([fd], [], [], 0))
198 slacapra 1.16
199     ###########################################################################
200     def makeNonBlocking(fd):
201     fl = fcntl.fcntl(fd, fcntl.F_GETFL)
202     try:
203     fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY)
204     except AttributeError:
205     fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.FNDELAY)
206    
207     ###########################################################################
208 spiga 1.100 def setPgid():
209 nsmirnov 1.1 """
210 spiga 1.100 preexec_fn for Popen to set subprocess pgid
211    
212     """
213    
214     os.setpgid( os.getpid(), 0 )
215    
216 spiga 1.109 def runCommand(command, printout=0, timeout=None,errorCode=False):
217 spiga 1.100 """
218     _executeCommand_
219    
220     Util it execute the command provided in a popen object with a timeout
221 nsmirnov 1.1 """
222 fanzago 1.15
223 spiga 1.100 start = time.time()
224     p = Popen( command, shell=True, \
225     stdin=PIPE, stdout=PIPE, stderr=STDOUT, \
226     close_fds=True, preexec_fn=setPgid )
227    
228     # playing with fd
229     fd = p.stdout.fileno()
230     flags = fcntl.fcntl(fd, fcntl.F_GETFL)
231     fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
232    
233     # return values
234     timedOut = False
235     outc = []
236    
237     while 1:
238     (r, w, e) = select.select([fd], [], [], timeout)
239    
240     if fd not in r :
241     timedOut = True
242     break
243 slacapra 1.11
244 spiga 1.100 read = p.stdout.read()
245     if read != '' :
246     outc.append( read )
247     else :
248 slacapra 1.16 break
249 spiga 1.100
250     if timedOut :
251     stop = time.time()
252     try:
253     os.killpg( os.getpgid(p.pid), signal.SIGTERM)
254     os.kill( p.pid, signal.SIGKILL)
255     p.wait()
256     p.stdout.close()
257     except OSError, err :
258 spiga 1.101 common.logger.info(
259 spiga 1.100 'Warning: an error occurred killing subprocess [%s]' \
260     % str(err) )
261    
262     raise TimeOut( command, ''.join(outc), timeout, start, stop )
263    
264     try:
265     p.wait()
266     p.stdout.close()
267     except OSError, err:
268 spiga 1.101 common.logger.info( 'Warning: an error occurred closing subprocess [%s] %s %s' \
269 spiga 1.100 % (str(err), ''.join(outc), p.returncode ))
270    
271     returncode = p.returncode
272     if returncode != 0 :
273     msg = 'Command: %s \n failed with exit code %s \n'%(command,returncode)
274 edelmann 1.105 msg += str(''.join(outc))
275 spiga 1.109 if not errorCode:
276     common.logger.info( msg )
277     return None
278     if errorCode:
279     if returncode is None :returncode=-66666
280     return returncode,''.join(outc)
281 spiga 1.101
282 spiga 1.100 return ''.join(outc)
283    
284 nsmirnov 1.4
285 slacapra 1.11 ####################################
286 gutsche 1.20 def makeCksum(filename) :
287     """
288 ewv 1.44 make check sum using filename and content of file
289 gutsche 1.20 """
290    
291 ewv 1.44 from zlib import crc32
292     hashString = filename
293 gutsche 1.20
294 ewv 1.44 inFile = open(filename, 'r')
295     hashString += inFile.read()
296     inFile.close()
297 gutsche 1.20
298 ewv 1.44 cksum = str(crc32(hashString))
299 gutsche 1.20 return cksum
300    
301 ewv 1.52
302 gutsche 1.32 def spanRanges(jobArray):
303     """
304     take array of job numbers and concatenate 1,2,3 to 1-3
305     return string
306     """
307    
308     output = ""
309 mcinquil 1.35 jobArray.sort()
310 ewv 1.44
311 gutsche 1.32 previous = jobArray[0]-1
312     for job in jobArray:
313     if previous+1 == job:
314     previous = job
315     if len(output) > 0 :
316     if output[-1] != "-":
317     output += "-"
318     else :
319     output += str(previous)
320     else:
321     output += str(previous) + "," + str(job)
322 mcinquil 1.35 #output += "," + str(job)
323 gutsche 1.32 previous = job
324     if len(jobArray) > 1 :
325     output += str(previous)
326    
327     return output
328    
329 spiga 1.40 def displayReport(self, header, lines, xml=''):
330 ewv 1.44
331 spiga 1.49 counter = 0
332     printline = ''
333     printline+= header
334 spiga 1.87 msg = '\n%s'%printline
335 spiga 1.49
336     for i in range(len(lines)):
337     if counter != 0 and counter%10 == 0 :
338 slacapra 1.84 msg += '-------------------------------------------------------------------------------------------------------\n'
339 spiga 1.82 msg+= '%s\n'%lines[i]
340 spiga 1.49 counter += 1
341     if xml != '' :
342 spiga 1.40 fileName = common.work_space.shareDir() + xml
343     task = common._db.getTask()
344     taskXML = common._db.serializeTask(task)
345 spiga 1.87 common.logger.log(10-1, taskXML)
346 spiga 1.40 f = open(fileName, 'w')
347     f.write(taskXML)
348     f.close()
349     pass
350 spiga 1.82 common.logger.info(msg)
351 spiga 1.39
352 spiga 1.42 def CliServerParams(self):
353 slacapra 1.45 """
354     Init client-server interactions
355     """
356     self.srvCfg = {}
357 slacapra 1.63 ## First I have to check if the decision has been already taken...
358     task = common._db.getTask()
359 slacapra 1.81 if task['serverName']!=None and task['serverName']!="":
360 slacapra 1.63 self.cfg_params['CRAB.server_name']=task['serverName']
361 slacapra 1.81
362     if self.cfg_params.has_key('CRAB.server_name'):
363     self.srvCfg = ServerConfig(self.cfg_params['CRAB.server_name']).config()
364     elif self.cfg_params.has_key('CRAB.use_server'):
365 slacapra 1.77 serverName=self.cfg_params.get('CRAB.server_name','default')
366 slacapra 1.62 if self.cfg_params.has_key('CRAB.server_name'):
367     serverName=self.cfg_params['CRAB.server_name']
368     else:
369     serverName='default'
370     self.srvCfg = ServerConfig(serverName).config()
371 slacapra 1.61 else:
372     msg = 'No server selected or port specified.\n'
373     msg += 'Please specify a server in the crab cfg file'
374     raise CrabException(msg)
375     return
376 slacapra 1.81 # save the serverName for future use
377     opsToBeSaved={}
378     opsToBeSaved['serverName']=self.srvCfg['serverGenericName']
379     common._db.updateTask_(opsToBeSaved)
380 slacapra 1.45
381 slacapra 1.61 self.server_admin = str(self.srvCfg['serverAdmin'])
382     self.server_dn = str(self.srvCfg['serverDN'])
383 spiga 1.58
384 slacapra 1.61 self.server_name = str(self.srvCfg['serverName'])
385     self.server_port = int(self.srvCfg['serverPort'])
386 slacapra 1.45
387 slacapra 1.61 self.storage_name = str(self.srvCfg['storageName'])
388     self.storage_path = str(self.srvCfg['storagePath'])
389 mcinquil 1.97
390 slacapra 1.61 self.storage_proto = str(self.srvCfg['storageProtocol'])
391 mcinquil 1.97 if self.cfg_params.has_key('USER.client'):
392     self.storage_proto = self.cfg_params['USER.client'].lower()
393    
394 slacapra 1.61 self.storage_port = str(self.srvCfg['storagePort'])
395 spiga 1.39
396 ewv 1.44 def bulkControl(self,list):
397 slacapra 1.45 """
398     Check the BULK size and reduce collection ...if needed
399     """
400     max_size = 400
401     sub_bulk = []
402     if len(list) > int(max_size):
403     n_sub_bulk = int( int(len(list) ) / int(max_size) )
404 mcinquil 1.53 for n in xrange(n_sub_bulk):
405 slacapra 1.45 first =n*int(max_size)
406     last = (n+1)*int(max_size)
407     sub_bulk.append(list[first:last])
408     if len(list[last:-1]) < 50:
409     for pp in list[last:-1]:
410     sub_bulk[n_sub_bulk-1].append(pp)
411 spiga 1.43 else:
412 mcinquil 1.53 sub_bulk.append(list[last:])
413 slacapra 1.45 else:
414     sub_bulk.append(list)
415    
416     return sub_bulk
417 ewv 1.89
418 slacapra 1.45
419 spiga 1.69 def getUserName():
420 spiga 1.66 """
421     extract user name from either SiteDB or Unix
422     """
423 mcinquil 1.96 if common.scheduler.name().upper() in ['LSF', 'CAF', 'SGE', 'PBS']:
424 ewv 1.89 common.logger.log(10-1, "Using as username the Unix user name")
425     userName = unixUserName()
426 spiga 1.66 else :
427 ewv 1.89 userName = gethnUserNameFromSiteDB()
428    
429     return userName
430 spiga 1.66
431 spiga 1.58
432 ewv 1.89 def unixUserName():
433 spiga 1.58 """
434     extract username from whoami
435     """
436     try:
437 ewv 1.89 userName = runCommand("whoami")
438     userName = string.strip(userName)
439 spiga 1.58 except:
440     msg = "Error. Problem with whoami command"
441     raise CrabException(msg)
442 ewv 1.89 return userName
443    
444 spiga 1.66
445 spiga 1.69 def getDN():
446 spiga 1.66 """
447     extract DN from user proxy's identity
448     """
449     try:
450     userdn = runCommand("voms-proxy-info -identity")
451     userdn = string.strip(userdn)
452     #search for a / to avoid picking up warning messages
453     userdn = userdn[userdn.find('/'):]
454     except:
455     msg = "Error. Problem with voms-proxy-info -identity command"
456     raise CrabException(msg)
457     return userdn.split('\n')[0]
458    
459 ewv 1.89
460 spiga 1.69 def gethnUserNameFromSiteDB():
461 spiga 1.66 """
462     extract user name from SiteDB
463     """
464     from WMCore.Services.SiteDB.SiteDB import SiteDBJSON
465     hnUserName = None
466 spiga 1.69 userdn = getDN()
467 ewv 1.89 params = { 'cacheduration' : 24,
468     'logger' : common.logger() }
469     mySiteDB = SiteDBJSON(params)
470 ewv 1.90 msg_ = "there is no user name associated to DN %s in SiteDB.\n" % userdn
471     msg_ += "You need to register in SiteDB with the instructions at https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB"
472 spiga 1.66 try:
473     hnUserName = mySiteDB.dnUserName(dn=userdn)
474 ewv 1.89 except Exception, text:
475     msg = "Error extracting user name from SiteDB: %s\n" % text
476     msg += " Check that you are registered in SiteDB, see https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB\n"
477     msg += ' or %s' % msg_
478 spiga 1.66 raise CrabException(msg)
479     if not hnUserName:
480 ewv 1.89 msg = "Error. %s" % msg_
481 spiga 1.66 raise CrabException(msg)
482     return hnUserName
483    
484    
485 slacapra 1.45 def numberFile(file, txt):
486     """
487     append _'txt' before last extension of a file
488     """
489     txt=str(txt)
490     p = string.split(file,".")
491     # take away last extension
492     name = p[0]
493     for x in p[1:-1]:
494     name=name+"."+x
495     # add "_txt"
496     if len(p)>1:
497     ext = p[len(p)-1]
498     result = name + '_' + txt + "." + ext
499     else:
500     result = name + '_' + txt
501 spiga 1.43
502 slacapra 1.45 return result
503 spiga 1.46
504     def readTXTfile(self,inFileName):
505     """
506     read file and return a list with the content
507     """
508     out_list=[]
509     if os.path.exists(inFileName):
510     f = open(inFileName, 'r')
511     for line in f.readlines():
512 ewv 1.52 out_list.append(string.strip(line))
513 spiga 1.46 f.close()
514     else:
515     msg = ' file '+str(inFileName)+' not found.'
516 ewv 1.52 raise CrabException(msg)
517 spiga 1.46 return out_list
518    
519     def writeTXTfile(self, outFileName, args):
520     """
521     write a file with the given content ( args )
522     """
523     outFile = open(outFileName,"a")
524     outFile.write(str(args))
525     outFile.close()
526     return
527    
528 spiga 1.54 def readableList(self,rawList):
529 ewv 1.64 """
530     Turn a list of numbers into a string like 1-5,7,9,12-20
531     """
532     if not rawList:
533     return ''
534    
535 slacapra 1.56 listString = str(rawList[0])
536     endRange = ''
537     for i in range(1,len(rawList)):
538     if rawList[i] == rawList[i-1]+1:
539     endRange = str(rawList[i])
540     else:
541     if endRange:
542     listString += '-' + endRange + ',' + str(rawList[i])
543     endRange = ''
544     else:
545     listString += ',' + str(rawList[i])
546     if endRange:
547     listString += '-' + endRange
548     endRange = ''
549 ewv 1.64
550 slacapra 1.56 return listString
551 spiga 1.54
552 spiga 1.51 def getLocalDomain(self):
553 ewv 1.52 """
554 slacapra 1.56 Get local domain name
555 ewv 1.52 """
556 spiga 1.51 import socket
557 slacapra 1.88 tmp=socket.getfqdn()
558 spiga 1.51 dot=string.find(tmp,'.')
559     if (dot==-1):
560     msg='Unkown domain name. Cannot use local scheduler'
561     raise CrabException(msg)
562     localDomainName = string.split(tmp,'.',1)[-1]
563 ewv 1.52 return localDomainName
564 spiga 1.51
565 slacapra 1.56 #######################################################
566     # Brian Bockelman bbockelm@cse.unl.edu
567     # Module to check the avaialble disk space on a specified directory.
568     #
569    
570     def has_freespace(dir_name, needed_space_kilobytes):
571     enough_unix_quota = False
572     enough_quota = False
573     enough_partition = False
574     enough_mount = False
575     try:
576 spiga 1.109 enough_mount = check_mount(dir_name, needed_space_kilobytes)
577     except Exception,e :
578     common.logger.log(10-1,e)
579 slacapra 1.56 enough_mount = True
580     try:
581     enough_quota = check_quota(dir_name, needed_space_kilobytes)
582 spiga 1.109 except Exception, e:
583     common.logger.log(10-1,e)
584 slacapra 1.56 enough_quota = True
585     try:
586     enough_partition = check_partition(dir_name,
587     needed_space_kilobytes)
588 spiga 1.109 except Exception, e:
589     common.logger.log(10-1,e)
590 slacapra 1.56 enough_partition = True
591     try:
592     enough_unix_quota = check_unix_quota(dir_name,
593     needed_space_kilobytes)
594 spiga 1.109 except Exception, e:
595     common.logger.log(10-1,e)
596 slacapra 1.56 enough_unix_quota = True
597     return enough_mount and enough_quota and enough_partition \
598     and enough_unix_quota
599    
600     def check_mount(dir_name, needed_space_kilobytes):
601     try:
602     vfs = os.statvfs(dir_name)
603     except:
604     raise Exception("Unable to query VFS for %s." % dir_name)
605     dev_free = vfs[statvfs.F_FRSIZE] * vfs[statvfs.F_BAVAIL]
606     return dev_free/1024 > needed_space_kilobytes
607    
608     def check_quota(dir_name, needed_space_kilobytes):
609 spiga 1.109 err,results = runCommand("/usr/bin/fs lq %s" % dir_name,errorCode=True)
610     if results and err == 0 :
611     try:
612     results = results.split('\n')[1].split()
613     quota, used = results[1:3]
614     avail = int(quota) - int(used)
615     return avail > needed_space_kilobytes
616     except:
617     raise Exception("Unable to parse AFS output.")
618     elif results and err !=0:
619     raise Exception(results)
620 slacapra 1.56
621     def check_partition(dir_name, needed_space_kilobytes):
622 spiga 1.109 err,results = runCommand("/usr/bin/fs diskfree %s" % dir_name,errorCode=True)
623     if results and err==0:
624     try:
625     results = results.split('\n')[1].split()
626     avail = results[3]
627     return int(avail) > needed_space_kilobytes
628     except:
629     raise Exception("Unable to parse AFS output.")
630     elif results and err !=0:
631     raise Exception(results)
632 slacapra 1.56
633     def check_unix_quota(dir_name, needed_space_kilobytes):
634 spiga 1.109 err0, results0 = runCommand("df %s" % dir_name,errorCode=True)
635     if results0 and err0==0:
636     fs = results0.split('\n')[1].split()[0]
637     err,results = runCommand("quota -Q -u -g",errorCode=True)
638     if err != 0:
639     raise Exception(results)
640     has_info = False
641     for line in results.splitlines():
642     info = line.split()
643     if info[0] in ['Filesystem', 'Disk']:
644     continue
645     if len(info) == 1:
646     filesystem = info[0]
647     has_info = False
648     if len(info) == 6:
649     used, limit = info[0], max(info[1], info[2])
650     has_info = True
651     if len(info) == 7:
652     filesystem, used, limit = info[0], info[1], max(info[2], info[3])
653     has_info = True
654     if has_info:
655     if filesystem != fs:
656     continue
657     avail = int(limit) - int(used)
658     if avail < needed_space_kilobytes:
659     return False
660     elif results0 and err0 !=0:
661     raise Exception(results0)
662 slacapra 1.56 return True
663 spiga 1.54
664 slacapra 1.57 def getGZSize(gzipfile):
665     # return the uncompressed size of a gzipped file
666     import struct
667     f = open(gzipfile, "rb")
668     if f.read(2) != "\x1f\x8b":
669     raise IOError("not a gzip file")
670     f.seek(-4, 2)
671 ewv 1.64 return struct.unpack("<i", f.read())[0]
672 slacapra 1.57
673 spiga 1.60 def showWebMon(server_name):
674 spiga 1.72 taskName = common._db.queryTask('name')
675 spiga 1.60 msg = ''
676 spiga 1.71 msg +='You can also follow the status of this task on :\n'
677 spiga 1.72 msg +='\tCMS Dashboard: http://dashb-cms-job-task.cern.ch/taskmon.html#task=%s\n'%(taskName)
678 ewv 1.64 if server_name != '' :
679 spiga 1.71 msg += '\tServer page: http://%s:8888/logginfo\n'%server_name
680 spiga 1.72 msg += '\tYour task name is: %s \n'%taskName
681 spiga 1.60 return msg
682    
683 slacapra 1.86 def SE2CMS(dests):
684 slacapra 1.85 """
685     Trasnsform a list of SE grid name into a list SE according to CMS naming convention
686     input: array of SE grid names
687     output: array of SE CMS names
688     """
689     from ProdCommon.SiteDB.CmsSiteMapper import SECmsMap
690     se_cms = SECmsMap()
691     SEDestination = [se_cms[d] for d in dests]
692     return SEDestination
693 spiga 1.60
694 slacapra 1.86 def CE2CMS(dests):
695     """
696     Trasnsform a list of CE grid name into a list SE according to CMS naming convention
697     input: array of CE grid names
698     output: array of CE CMS names
699     """
700     from ProdCommon.SiteDB.CmsSiteMapper import CECmsMap
701     ce_cms = CECmsMap()
702     CEDestination = [ce_cms[d] for d in dests]
703     return CEDestination
704    
705 spiga 1.95 def checkLcgUtils( ):
706 mcinquil 1.94 """
707     _checkLcgUtils_
708     check the lcg-utils version and report
709     """
710     import commands
711     cmd = "lcg-cp --version | grep lcg_util"
712     status, output = commands.getstatusoutput( cmd )
713     num_ver = -1
714     if output.find("not found") == -1 or status == 0:
715     temp = output.split("-")
716     version = ""
717     if len(temp) >= 2:
718     version = output.split("-")[1]
719     temp = version.split(".")
720     if len(temp) >= 1:
721     num_ver = int(temp[0])*10
722     num_ver += int(temp[1])
723     return num_ver
724    
725 spiga 1.95 def setLcgTimeout( ):
726     """
727     """
728     opt = ' -t 600 '
729     if checkLcgUtils() >= 17: opt=' --connect-timeout 600 '
730     return opt
731    
732 spiga 1.101
733 gutsche 1.20 ####################################
734 nsmirnov 1.4 if __name__ == '__main__':
735     print 'sys.argv[1] =',sys.argv[1]
736     list = parseRange2(sys.argv[1])
737     print list
738 slacapra 1.29 cksum = makeCksum("crab_util.py")
739     print cksum
740 ewv 1.44