ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/crab_util.py
Revision: 1.116
Committed: Tue Nov 9 13:20:10 2010 UTC (14 years, 5 months ago) by mcinquil
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_7_6_patch1, CRAB_2_7_6
Changes since 1.115: +6 -0 lines
Log Message:
Fix allowed release format

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 spiga 1.113 import string, sys, os, time, signal
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 spiga 1.111 result=[]
170 mcinquil 1.98 match_result = False
171     from Downloader import Downloader
172 spiga 1.107 blacklist = Downloader(url)
173 spiga 1.111 try:
174     result =eval(blacklist.config(fileName))
175     except:
176     common.logger.info("ERROR: Problem reading allowed releases file...")
177 mcinquil 1.98 current_dot = current.split('.')
178     for version in result:
179     if version.find('.') != -1:
180     version_dot = version.split('.')
181 mcinquil 1.116 temp = False
182 mcinquil 1.98 for compare in map(None, current_dot, version_dot):
183     if compare[1].find('*') != -1:
184     return True
185     elif int(compare[0]) != int(compare[1]):
186 mcinquil 1.116 temp = False
187 mcinquil 1.98 break
188 mcinquil 1.116 else:
189     temp = True
190     if temp:
191     return temp
192 mcinquil 1.98 elif version == '*':
193     return True
194     return False
195    
196     ###########################################################################
197 mcinquil 1.115 def getCentralConfigLink(linkname, url = "http://cmsdoc.cern.ch/cms/LCG/crab/config/", fileName = "URLs.conf"):
198     """
199     _getCentralConfigLink_
200    
201     This retrieves the remote URLs file containing a dictionary of a central manager URLs
202     {
203     'reportLogURL': 'http://gangamon.cern.ch/django/cmserrorreports/',
204     'dashbTaskMon': 'http://dashb-cms-job-task.cern.ch/taskmon.html#task=',
205     'servTaskMon' : 'http://glidein-mon.t2.ucsd.edu:8080/dashboard/ajaxproxy.jsp?p='
206     }
207     """
208     result = {}
209     from Downloader import Downloader
210     links = Downloader(url)
211     try:
212     result = eval(links.config(fileName))
213     common.logger.debug(str(result))
214     except:
215     common.logger.info("ERROR: Problem reading URLs releases file...")
216     if result.has_key(linkname):
217     return result[linkname]
218     common.logger.info("ERROR: Problem reading URLs releases file: no %s present!" % linkname)
219     return ''
220    
221     ###########################################################################
222 nsmirnov 1.1 def importName(module_name, name):
223     """
224     Import a named object from a Python module,
225     i.e., it is an equivalent of 'from module_name import name'.
226     """
227     module = __import__(module_name, globals(), locals(), [name])
228     return vars(module)[name]
229    
230     ###########################################################################
231 slacapra 1.16 def readable(fd):
232 ewv 1.44 return bool(select.select([fd], [], [], 0))
233 slacapra 1.16
234     ###########################################################################
235     def makeNonBlocking(fd):
236     fl = fcntl.fcntl(fd, fcntl.F_GETFL)
237     try:
238     fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NDELAY)
239     except AttributeError:
240     fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.FNDELAY)
241    
242     ###########################################################################
243 spiga 1.100 def setPgid():
244 nsmirnov 1.1 """
245 spiga 1.100 preexec_fn for Popen to set subprocess pgid
246    
247     """
248    
249     os.setpgid( os.getpid(), 0 )
250    
251 spiga 1.109 def runCommand(command, printout=0, timeout=None,errorCode=False):
252 spiga 1.100 """
253     _executeCommand_
254    
255     Util it execute the command provided in a popen object with a timeout
256 nsmirnov 1.1 """
257 fanzago 1.15
258 spiga 1.100 start = time.time()
259     p = Popen( command, shell=True, \
260     stdin=PIPE, stdout=PIPE, stderr=STDOUT, \
261     close_fds=True, preexec_fn=setPgid )
262    
263     # playing with fd
264     fd = p.stdout.fileno()
265     flags = fcntl.fcntl(fd, fcntl.F_GETFL)
266     fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
267    
268     # return values
269     timedOut = False
270     outc = []
271    
272     while 1:
273     (r, w, e) = select.select([fd], [], [], timeout)
274    
275     if fd not in r :
276     timedOut = True
277     break
278 slacapra 1.11
279 spiga 1.100 read = p.stdout.read()
280     if read != '' :
281     outc.append( read )
282     else :
283 slacapra 1.16 break
284 spiga 1.100
285     if timedOut :
286     stop = time.time()
287     try:
288     os.killpg( os.getpgid(p.pid), signal.SIGTERM)
289     os.kill( p.pid, signal.SIGKILL)
290     p.wait()
291     p.stdout.close()
292     except OSError, err :
293 spiga 1.101 common.logger.info(
294 spiga 1.100 'Warning: an error occurred killing subprocess [%s]' \
295     % str(err) )
296    
297 spiga 1.113 raise CrabException( command, ''.join(outc), timeout, start, stop )
298 spiga 1.100
299     try:
300     p.wait()
301     p.stdout.close()
302     except OSError, err:
303 spiga 1.101 common.logger.info( 'Warning: an error occurred closing subprocess [%s] %s %s' \
304 spiga 1.100 % (str(err), ''.join(outc), p.returncode ))
305    
306     returncode = p.returncode
307     if returncode != 0 :
308     msg = 'Command: %s \n failed with exit code %s \n'%(command,returncode)
309 edelmann 1.105 msg += str(''.join(outc))
310 spiga 1.109 if not errorCode:
311     common.logger.info( msg )
312     return None
313     if errorCode:
314     if returncode is None :returncode=-66666
315     return returncode,''.join(outc)
316 spiga 1.101
317 spiga 1.100 return ''.join(outc)
318    
319 nsmirnov 1.4
320 slacapra 1.11 ####################################
321 gutsche 1.20 def makeCksum(filename) :
322     """
323 ewv 1.44 make check sum using filename and content of file
324 gutsche 1.20 """
325    
326 ewv 1.44 from zlib import crc32
327     hashString = filename
328 gutsche 1.20
329 ewv 1.44 inFile = open(filename, 'r')
330     hashString += inFile.read()
331     inFile.close()
332 gutsche 1.20
333 ewv 1.44 cksum = str(crc32(hashString))
334 gutsche 1.20 return cksum
335    
336 ewv 1.52
337 gutsche 1.32 def spanRanges(jobArray):
338     """
339     take array of job numbers and concatenate 1,2,3 to 1-3
340     return string
341     """
342    
343     output = ""
344 mcinquil 1.35 jobArray.sort()
345 ewv 1.44
346 gutsche 1.32 previous = jobArray[0]-1
347     for job in jobArray:
348     if previous+1 == job:
349     previous = job
350     if len(output) > 0 :
351     if output[-1] != "-":
352     output += "-"
353     else :
354     output += str(previous)
355     else:
356     output += str(previous) + "," + str(job)
357 mcinquil 1.35 #output += "," + str(job)
358 gutsche 1.32 previous = job
359     if len(jobArray) > 1 :
360     output += str(previous)
361    
362     return output
363    
364 spiga 1.40 def displayReport(self, header, lines, xml=''):
365 ewv 1.44
366 spiga 1.49 counter = 0
367     printline = ''
368     printline+= header
369 spiga 1.87 msg = '\n%s'%printline
370 spiga 1.49
371     for i in range(len(lines)):
372     if counter != 0 and counter%10 == 0 :
373 slacapra 1.84 msg += '-------------------------------------------------------------------------------------------------------\n'
374 spiga 1.82 msg+= '%s\n'%lines[i]
375 spiga 1.49 counter += 1
376     if xml != '' :
377 spiga 1.40 fileName = common.work_space.shareDir() + xml
378     task = common._db.getTask()
379     taskXML = common._db.serializeTask(task)
380 spiga 1.87 common.logger.log(10-1, taskXML)
381 spiga 1.40 f = open(fileName, 'w')
382     f.write(taskXML)
383     f.close()
384     pass
385 spiga 1.82 common.logger.info(msg)
386 spiga 1.39
387 spiga 1.42 def CliServerParams(self):
388 slacapra 1.45 """
389     Init client-server interactions
390     """
391     self.srvCfg = {}
392 slacapra 1.63 ## First I have to check if the decision has been already taken...
393     task = common._db.getTask()
394 slacapra 1.81 if task['serverName']!=None and task['serverName']!="":
395 slacapra 1.63 self.cfg_params['CRAB.server_name']=task['serverName']
396 slacapra 1.81
397     if self.cfg_params.has_key('CRAB.server_name'):
398     self.srvCfg = ServerConfig(self.cfg_params['CRAB.server_name']).config()
399     elif self.cfg_params.has_key('CRAB.use_server'):
400 slacapra 1.77 serverName=self.cfg_params.get('CRAB.server_name','default')
401 slacapra 1.62 if self.cfg_params.has_key('CRAB.server_name'):
402     serverName=self.cfg_params['CRAB.server_name']
403     else:
404     serverName='default'
405     self.srvCfg = ServerConfig(serverName).config()
406 slacapra 1.61 else:
407     msg = 'No server selected or port specified.\n'
408     msg += 'Please specify a server in the crab cfg file'
409     raise CrabException(msg)
410     return
411 slacapra 1.81 # save the serverName for future use
412     opsToBeSaved={}
413     opsToBeSaved['serverName']=self.srvCfg['serverGenericName']
414     common._db.updateTask_(opsToBeSaved)
415 slacapra 1.45
416 slacapra 1.61 self.server_admin = str(self.srvCfg['serverAdmin'])
417     self.server_dn = str(self.srvCfg['serverDN'])
418 spiga 1.58
419 slacapra 1.61 self.server_name = str(self.srvCfg['serverName'])
420     self.server_port = int(self.srvCfg['serverPort'])
421 slacapra 1.45
422 slacapra 1.61 self.storage_name = str(self.srvCfg['storageName'])
423     self.storage_path = str(self.srvCfg['storagePath'])
424 mcinquil 1.97
425 riahi 1.114 if self.srvCfg.has_key('proxyPath'):
426     self.proxy_path = str(self.srvCfg['proxyPath'])
427     else:
428     self.proxy_path = os.path.dirname(str(self.srvCfg['storagePath'])) + '/proxyCache'
429    
430 slacapra 1.61 self.storage_proto = str(self.srvCfg['storageProtocol'])
431 mcinquil 1.97 if self.cfg_params.has_key('USER.client'):
432     self.storage_proto = self.cfg_params['USER.client'].lower()
433    
434 slacapra 1.61 self.storage_port = str(self.srvCfg['storagePort'])
435 spiga 1.39
436 ewv 1.44 def bulkControl(self,list):
437 slacapra 1.45 """
438     Check the BULK size and reduce collection ...if needed
439     """
440     max_size = 400
441     sub_bulk = []
442     if len(list) > int(max_size):
443     n_sub_bulk = int( int(len(list) ) / int(max_size) )
444 mcinquil 1.53 for n in xrange(n_sub_bulk):
445 slacapra 1.45 first =n*int(max_size)
446     last = (n+1)*int(max_size)
447     sub_bulk.append(list[first:last])
448     if len(list[last:-1]) < 50:
449     for pp in list[last:-1]:
450     sub_bulk[n_sub_bulk-1].append(pp)
451 spiga 1.43 else:
452 mcinquil 1.53 sub_bulk.append(list[last:])
453 slacapra 1.45 else:
454     sub_bulk.append(list)
455    
456     return sub_bulk
457 ewv 1.89
458 slacapra 1.45
459 spiga 1.69 def getUserName():
460 spiga 1.66 """
461     extract user name from either SiteDB or Unix
462     """
463 mcinquil 1.96 if common.scheduler.name().upper() in ['LSF', 'CAF', 'SGE', 'PBS']:
464 ewv 1.89 common.logger.log(10-1, "Using as username the Unix user name")
465     userName = unixUserName()
466 spiga 1.66 else :
467 ewv 1.89 userName = gethnUserNameFromSiteDB()
468    
469     return userName
470 spiga 1.66
471 spiga 1.58
472 ewv 1.89 def unixUserName():
473 spiga 1.58 """
474     extract username from whoami
475     """
476     try:
477 ewv 1.89 userName = runCommand("whoami")
478     userName = string.strip(userName)
479 spiga 1.58 except:
480     msg = "Error. Problem with whoami command"
481     raise CrabException(msg)
482 ewv 1.89 return userName
483    
484 spiga 1.66
485 spiga 1.69 def getDN():
486 spiga 1.66 """
487     extract DN from user proxy's identity
488     """
489     try:
490     userdn = runCommand("voms-proxy-info -identity")
491     userdn = string.strip(userdn)
492 farinafa 1.112 #remove /CN=proxy that could cause problems with siteDB check at server-side
493     userdn = userdn.replace('/CN=proxy','')
494 spiga 1.66 #search for a / to avoid picking up warning messages
495     userdn = userdn[userdn.find('/'):]
496     except:
497     msg = "Error. Problem with voms-proxy-info -identity command"
498     raise CrabException(msg)
499     return userdn.split('\n')[0]
500    
501 ewv 1.89
502 spiga 1.69 def gethnUserNameFromSiteDB():
503 spiga 1.66 """
504     extract user name from SiteDB
505     """
506     from WMCore.Services.SiteDB.SiteDB import SiteDBJSON
507     hnUserName = None
508 spiga 1.69 userdn = getDN()
509 ewv 1.89 params = { 'cacheduration' : 24,
510     'logger' : common.logger() }
511     mySiteDB = SiteDBJSON(params)
512 ewv 1.90 msg_ = "there is no user name associated to DN %s in SiteDB.\n" % userdn
513     msg_ += "You need to register in SiteDB with the instructions at https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB"
514 spiga 1.66 try:
515     hnUserName = mySiteDB.dnUserName(dn=userdn)
516 ewv 1.89 except Exception, text:
517     msg = "Error extracting user name from SiteDB: %s\n" % text
518     msg += " Check that you are registered in SiteDB, see https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB\n"
519     msg += ' or %s' % msg_
520 spiga 1.66 raise CrabException(msg)
521     if not hnUserName:
522 ewv 1.89 msg = "Error. %s" % msg_
523 spiga 1.66 raise CrabException(msg)
524     return hnUserName
525    
526    
527 slacapra 1.45 def numberFile(file, txt):
528     """
529     append _'txt' before last extension of a file
530     """
531     txt=str(txt)
532     p = string.split(file,".")
533     # take away last extension
534     name = p[0]
535     for x in p[1:-1]:
536     name=name+"."+x
537     # add "_txt"
538     if len(p)>1:
539     ext = p[len(p)-1]
540     result = name + '_' + txt + "." + ext
541     else:
542     result = name + '_' + txt
543 spiga 1.43
544 slacapra 1.45 return result
545 spiga 1.46
546     def readTXTfile(self,inFileName):
547     """
548     read file and return a list with the content
549     """
550     out_list=[]
551     if os.path.exists(inFileName):
552     f = open(inFileName, 'r')
553     for line in f.readlines():
554 ewv 1.52 out_list.append(string.strip(line))
555 spiga 1.46 f.close()
556     else:
557     msg = ' file '+str(inFileName)+' not found.'
558 ewv 1.52 raise CrabException(msg)
559 spiga 1.46 return out_list
560    
561     def writeTXTfile(self, outFileName, args):
562     """
563     write a file with the given content ( args )
564     """
565     outFile = open(outFileName,"a")
566     outFile.write(str(args))
567     outFile.close()
568     return
569    
570 spiga 1.54 def readableList(self,rawList):
571 ewv 1.64 """
572     Turn a list of numbers into a string like 1-5,7,9,12-20
573     """
574     if not rawList:
575     return ''
576    
577 slacapra 1.56 listString = str(rawList[0])
578     endRange = ''
579     for i in range(1,len(rawList)):
580     if rawList[i] == rawList[i-1]+1:
581     endRange = str(rawList[i])
582     else:
583     if endRange:
584     listString += '-' + endRange + ',' + str(rawList[i])
585     endRange = ''
586     else:
587     listString += ',' + str(rawList[i])
588     if endRange:
589     listString += '-' + endRange
590     endRange = ''
591 ewv 1.64
592 slacapra 1.56 return listString
593 spiga 1.54
594 spiga 1.51 def getLocalDomain(self):
595 ewv 1.52 """
596 slacapra 1.56 Get local domain name
597 ewv 1.52 """
598 spiga 1.51 import socket
599 slacapra 1.88 tmp=socket.getfqdn()
600 spiga 1.51 dot=string.find(tmp,'.')
601     if (dot==-1):
602     msg='Unkown domain name. Cannot use local scheduler'
603     raise CrabException(msg)
604     localDomainName = string.split(tmp,'.',1)[-1]
605 ewv 1.52 return localDomainName
606 spiga 1.51
607 slacapra 1.56 #######################################################
608     # Brian Bockelman bbockelm@cse.unl.edu
609     # Module to check the avaialble disk space on a specified directory.
610     #
611    
612     def has_freespace(dir_name, needed_space_kilobytes):
613     enough_unix_quota = False
614     enough_quota = False
615     enough_partition = False
616     enough_mount = False
617     try:
618 spiga 1.109 enough_mount = check_mount(dir_name, needed_space_kilobytes)
619     except Exception,e :
620     common.logger.log(10-1,e)
621 slacapra 1.56 enough_mount = True
622     try:
623     enough_quota = check_quota(dir_name, needed_space_kilobytes)
624 spiga 1.109 except Exception, e:
625     common.logger.log(10-1,e)
626 slacapra 1.56 enough_quota = True
627     try:
628     enough_partition = check_partition(dir_name,
629     needed_space_kilobytes)
630 spiga 1.109 except Exception, e:
631     common.logger.log(10-1,e)
632 slacapra 1.56 enough_partition = True
633     try:
634     enough_unix_quota = check_unix_quota(dir_name,
635     needed_space_kilobytes)
636 spiga 1.109 except Exception, e:
637     common.logger.log(10-1,e)
638 slacapra 1.56 enough_unix_quota = True
639     return enough_mount and enough_quota and enough_partition \
640     and enough_unix_quota
641    
642     def check_mount(dir_name, needed_space_kilobytes):
643     try:
644     vfs = os.statvfs(dir_name)
645     except:
646     raise Exception("Unable to query VFS for %s." % dir_name)
647     dev_free = vfs[statvfs.F_FRSIZE] * vfs[statvfs.F_BAVAIL]
648     return dev_free/1024 > needed_space_kilobytes
649    
650     def check_quota(dir_name, needed_space_kilobytes):
651 spiga 1.109 err,results = runCommand("/usr/bin/fs lq %s" % dir_name,errorCode=True)
652     if results and err == 0 :
653     try:
654     results = results.split('\n')[1].split()
655     quota, used = results[1:3]
656     avail = int(quota) - int(used)
657     return avail > needed_space_kilobytes
658     except:
659     raise Exception("Unable to parse AFS output.")
660     elif results and err !=0:
661     raise Exception(results)
662 slacapra 1.56
663     def check_partition(dir_name, needed_space_kilobytes):
664 spiga 1.109 err,results = runCommand("/usr/bin/fs diskfree %s" % dir_name,errorCode=True)
665     if results and err==0:
666     try:
667     results = results.split('\n')[1].split()
668     avail = results[3]
669     return int(avail) > needed_space_kilobytes
670     except:
671     raise Exception("Unable to parse AFS output.")
672     elif results and err !=0:
673     raise Exception(results)
674 slacapra 1.56
675     def check_unix_quota(dir_name, needed_space_kilobytes):
676 spiga 1.109 err0, results0 = runCommand("df %s" % dir_name,errorCode=True)
677     if results0 and err0==0:
678     fs = results0.split('\n')[1].split()[0]
679     err,results = runCommand("quota -Q -u -g",errorCode=True)
680     if err != 0:
681     raise Exception(results)
682     has_info = False
683     for line in results.splitlines():
684     info = line.split()
685     if info[0] in ['Filesystem', 'Disk']:
686     continue
687     if len(info) == 1:
688     filesystem = info[0]
689     has_info = False
690     if len(info) == 6:
691     used, limit = info[0], max(info[1], info[2])
692     has_info = True
693     if len(info) == 7:
694     filesystem, used, limit = info[0], info[1], max(info[2], info[3])
695     has_info = True
696     if has_info:
697     if filesystem != fs:
698     continue
699     avail = int(limit) - int(used)
700     if avail < needed_space_kilobytes:
701     return False
702     elif results0 and err0 !=0:
703     raise Exception(results0)
704 slacapra 1.56 return True
705 spiga 1.54
706 slacapra 1.57 def getGZSize(gzipfile):
707     # return the uncompressed size of a gzipped file
708     import struct
709     f = open(gzipfile, "rb")
710     if f.read(2) != "\x1f\x8b":
711     raise IOError("not a gzip file")
712     f.seek(-4, 2)
713 ewv 1.64 return struct.unpack("<i", f.read())[0]
714 slacapra 1.57
715 spiga 1.60 def showWebMon(server_name):
716 spiga 1.72 taskName = common._db.queryTask('name')
717 spiga 1.60 msg = ''
718 spiga 1.71 msg +='You can also follow the status of this task on :\n'
719 spiga 1.72 msg +='\tCMS Dashboard: http://dashb-cms-job-task.cern.ch/taskmon.html#task=%s\n'%(taskName)
720 ewv 1.64 if server_name != '' :
721 spiga 1.71 msg += '\tServer page: http://%s:8888/logginfo\n'%server_name
722 spiga 1.72 msg += '\tYour task name is: %s \n'%taskName
723 spiga 1.60 return msg
724    
725 slacapra 1.86 def SE2CMS(dests):
726 slacapra 1.85 """
727     Trasnsform a list of SE grid name into a list SE according to CMS naming convention
728     input: array of SE grid names
729     output: array of SE CMS names
730     """
731     from ProdCommon.SiteDB.CmsSiteMapper import SECmsMap
732     se_cms = SECmsMap()
733     SEDestination = [se_cms[d] for d in dests]
734     return SEDestination
735 spiga 1.60
736 slacapra 1.86 def CE2CMS(dests):
737     """
738     Trasnsform a list of CE grid name into a list SE according to CMS naming convention
739     input: array of CE grid names
740     output: array of CE CMS names
741     """
742     from ProdCommon.SiteDB.CmsSiteMapper import CECmsMap
743     ce_cms = CECmsMap()
744     CEDestination = [ce_cms[d] for d in dests]
745     return CEDestination
746    
747 spiga 1.95 def checkLcgUtils( ):
748 mcinquil 1.94 """
749     _checkLcgUtils_
750     check the lcg-utils version and report
751     """
752     import commands
753     cmd = "lcg-cp --version | grep lcg_util"
754     status, output = commands.getstatusoutput( cmd )
755     num_ver = -1
756     if output.find("not found") == -1 or status == 0:
757     temp = output.split("-")
758     version = ""
759     if len(temp) >= 2:
760     version = output.split("-")[1]
761     temp = version.split(".")
762     if len(temp) >= 1:
763     num_ver = int(temp[0])*10
764     num_ver += int(temp[1])
765     return num_ver
766    
767 spiga 1.95 def setLcgTimeout( ):
768     """
769     """
770     opt = ' -t 600 '
771     if checkLcgUtils() >= 17: opt=' --connect-timeout 600 '
772     return opt
773    
774 spiga 1.110 def schedulerGlite():
775    
776     scheduler = None
777     err, out = runCommand('glite-version',errorCode=True)
778     if err==0:
779     if out.strip().startswith('3.1'):
780     scheduler = 'SchedulerGLiteAPI'
781     else:
782     scheduler = 'SchedulerGLite'
783     else:
784     common.logger.info("error detecting glite version ")
785    
786     return scheduler
787 spiga 1.101
788 gutsche 1.20 ####################################
789 nsmirnov 1.4 if __name__ == '__main__':
790     print 'sys.argv[1] =',sys.argv[1]
791     list = parseRange2(sys.argv[1])
792     print list
793 slacapra 1.29 cksum = makeCksum("crab_util.py")
794     print cksum
795 ewv 1.44