ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/crab_util.py
Revision: 1.107
Committed: Sun Jan 17 19:05:52 2010 UTC (15 years, 3 months ago) by spiga
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_7_1_pre3
Changes since 1.106: +1 -1 lines
Log Message:
use default cache definition

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     def runCommand(command, printout=0, timeout=None):
217     """
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.101 common.logger.info( msg )
276 spigafi 1.102 return None
277 spiga 1.101
278 spiga 1.100 return ''.join(outc)
279    
280 nsmirnov 1.4
281 slacapra 1.11 ####################################
282 gutsche 1.20 def makeCksum(filename) :
283     """
284 ewv 1.44 make check sum using filename and content of file
285 gutsche 1.20 """
286    
287 ewv 1.44 from zlib import crc32
288     hashString = filename
289 gutsche 1.20
290 ewv 1.44 inFile = open(filename, 'r')
291     hashString += inFile.read()
292     inFile.close()
293 gutsche 1.20
294 ewv 1.44 cksum = str(crc32(hashString))
295 gutsche 1.20 return cksum
296    
297 ewv 1.52
298 gutsche 1.32 def spanRanges(jobArray):
299     """
300     take array of job numbers and concatenate 1,2,3 to 1-3
301     return string
302     """
303    
304     output = ""
305 mcinquil 1.35 jobArray.sort()
306 ewv 1.44
307 gutsche 1.32 previous = jobArray[0]-1
308     for job in jobArray:
309     if previous+1 == job:
310     previous = job
311     if len(output) > 0 :
312     if output[-1] != "-":
313     output += "-"
314     else :
315     output += str(previous)
316     else:
317     output += str(previous) + "," + str(job)
318 mcinquil 1.35 #output += "," + str(job)
319 gutsche 1.32 previous = job
320     if len(jobArray) > 1 :
321     output += str(previous)
322    
323     return output
324    
325 spiga 1.40 def displayReport(self, header, lines, xml=''):
326 ewv 1.44
327 spiga 1.49 counter = 0
328     printline = ''
329     printline+= header
330 spiga 1.87 msg = '\n%s'%printline
331 spiga 1.49
332     for i in range(len(lines)):
333     if counter != 0 and counter%10 == 0 :
334 slacapra 1.84 msg += '-------------------------------------------------------------------------------------------------------\n'
335 spiga 1.82 msg+= '%s\n'%lines[i]
336 spiga 1.49 counter += 1
337     if xml != '' :
338 spiga 1.40 fileName = common.work_space.shareDir() + xml
339     task = common._db.getTask()
340     taskXML = common._db.serializeTask(task)
341 spiga 1.87 common.logger.log(10-1, taskXML)
342 spiga 1.40 f = open(fileName, 'w')
343     f.write(taskXML)
344     f.close()
345     pass
346 spiga 1.82 common.logger.info(msg)
347 spiga 1.39
348 spiga 1.42 def CliServerParams(self):
349 slacapra 1.45 """
350     Init client-server interactions
351     """
352     self.srvCfg = {}
353 slacapra 1.63 ## First I have to check if the decision has been already taken...
354     task = common._db.getTask()
355 slacapra 1.81 if task['serverName']!=None and task['serverName']!="":
356 slacapra 1.63 self.cfg_params['CRAB.server_name']=task['serverName']
357 slacapra 1.81
358     if self.cfg_params.has_key('CRAB.server_name'):
359     self.srvCfg = ServerConfig(self.cfg_params['CRAB.server_name']).config()
360     elif self.cfg_params.has_key('CRAB.use_server'):
361 slacapra 1.77 serverName=self.cfg_params.get('CRAB.server_name','default')
362 slacapra 1.62 if self.cfg_params.has_key('CRAB.server_name'):
363     serverName=self.cfg_params['CRAB.server_name']
364     else:
365     serverName='default'
366     self.srvCfg = ServerConfig(serverName).config()
367 slacapra 1.61 else:
368     msg = 'No server selected or port specified.\n'
369     msg += 'Please specify a server in the crab cfg file'
370     raise CrabException(msg)
371     return
372 slacapra 1.81 # save the serverName for future use
373     opsToBeSaved={}
374     opsToBeSaved['serverName']=self.srvCfg['serverGenericName']
375     common._db.updateTask_(opsToBeSaved)
376 slacapra 1.45
377 slacapra 1.61 self.server_admin = str(self.srvCfg['serverAdmin'])
378     self.server_dn = str(self.srvCfg['serverDN'])
379 spiga 1.58
380 slacapra 1.61 self.server_name = str(self.srvCfg['serverName'])
381     self.server_port = int(self.srvCfg['serverPort'])
382 slacapra 1.45
383 slacapra 1.61 self.storage_name = str(self.srvCfg['storageName'])
384     self.storage_path = str(self.srvCfg['storagePath'])
385 mcinquil 1.97
386 slacapra 1.61 self.storage_proto = str(self.srvCfg['storageProtocol'])
387 mcinquil 1.97 if self.cfg_params.has_key('USER.client'):
388     self.storage_proto = self.cfg_params['USER.client'].lower()
389    
390 slacapra 1.61 self.storage_port = str(self.srvCfg['storagePort'])
391 spiga 1.39
392 ewv 1.44 def bulkControl(self,list):
393 slacapra 1.45 """
394     Check the BULK size and reduce collection ...if needed
395     """
396     max_size = 400
397     sub_bulk = []
398     if len(list) > int(max_size):
399     n_sub_bulk = int( int(len(list) ) / int(max_size) )
400 mcinquil 1.53 for n in xrange(n_sub_bulk):
401 slacapra 1.45 first =n*int(max_size)
402     last = (n+1)*int(max_size)
403     sub_bulk.append(list[first:last])
404     if len(list[last:-1]) < 50:
405     for pp in list[last:-1]:
406     sub_bulk[n_sub_bulk-1].append(pp)
407 spiga 1.43 else:
408 mcinquil 1.53 sub_bulk.append(list[last:])
409 slacapra 1.45 else:
410     sub_bulk.append(list)
411    
412     return sub_bulk
413 ewv 1.89
414 slacapra 1.45
415 spiga 1.69 def getUserName():
416 spiga 1.66 """
417     extract user name from either SiteDB or Unix
418     """
419 mcinquil 1.96 if common.scheduler.name().upper() in ['LSF', 'CAF', 'SGE', 'PBS']:
420 ewv 1.89 common.logger.log(10-1, "Using as username the Unix user name")
421     userName = unixUserName()
422 spiga 1.66 else :
423 ewv 1.89 userName = gethnUserNameFromSiteDB()
424    
425     return userName
426 spiga 1.66
427 spiga 1.58
428 ewv 1.89 def unixUserName():
429 spiga 1.58 """
430     extract username from whoami
431     """
432     try:
433 ewv 1.89 userName = runCommand("whoami")
434     userName = string.strip(userName)
435 spiga 1.58 except:
436     msg = "Error. Problem with whoami command"
437     raise CrabException(msg)
438 ewv 1.89 return userName
439    
440 spiga 1.66
441 spiga 1.69 def getDN():
442 spiga 1.66 """
443     extract DN from user proxy's identity
444     """
445     try:
446     userdn = runCommand("voms-proxy-info -identity")
447     userdn = string.strip(userdn)
448     #search for a / to avoid picking up warning messages
449     userdn = userdn[userdn.find('/'):]
450     except:
451     msg = "Error. Problem with voms-proxy-info -identity command"
452     raise CrabException(msg)
453     return userdn.split('\n')[0]
454    
455 ewv 1.89
456 spiga 1.69 def gethnUserNameFromSiteDB():
457 spiga 1.66 """
458     extract user name from SiteDB
459     """
460     from WMCore.Services.SiteDB.SiteDB import SiteDBJSON
461     hnUserName = None
462 spiga 1.69 userdn = getDN()
463 ewv 1.89 params = { 'cacheduration' : 24,
464     'logger' : common.logger() }
465     mySiteDB = SiteDBJSON(params)
466 ewv 1.90 msg_ = "there is no user name associated to DN %s in SiteDB.\n" % userdn
467     msg_ += "You need to register in SiteDB with the instructions at https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB"
468 spiga 1.66 try:
469     hnUserName = mySiteDB.dnUserName(dn=userdn)
470 ewv 1.89 except Exception, text:
471     msg = "Error extracting user name from SiteDB: %s\n" % text
472     msg += " Check that you are registered in SiteDB, see https://twiki.cern.ch/twiki/bin/view/CMS/SiteDBForCRAB\n"
473     msg += ' or %s' % msg_
474 spiga 1.66 raise CrabException(msg)
475     if not hnUserName:
476 ewv 1.89 msg = "Error. %s" % msg_
477 spiga 1.66 raise CrabException(msg)
478     return hnUserName
479    
480    
481 slacapra 1.45 def numberFile(file, txt):
482     """
483     append _'txt' before last extension of a file
484     """
485     txt=str(txt)
486     p = string.split(file,".")
487     # take away last extension
488     name = p[0]
489     for x in p[1:-1]:
490     name=name+"."+x
491     # add "_txt"
492     if len(p)>1:
493     ext = p[len(p)-1]
494     result = name + '_' + txt + "." + ext
495     else:
496     result = name + '_' + txt
497 spiga 1.43
498 slacapra 1.45 return result
499 spiga 1.46
500     def readTXTfile(self,inFileName):
501     """
502     read file and return a list with the content
503     """
504     out_list=[]
505     if os.path.exists(inFileName):
506     f = open(inFileName, 'r')
507     for line in f.readlines():
508 ewv 1.52 out_list.append(string.strip(line))
509 spiga 1.46 f.close()
510     else:
511     msg = ' file '+str(inFileName)+' not found.'
512 ewv 1.52 raise CrabException(msg)
513 spiga 1.46 return out_list
514    
515     def writeTXTfile(self, outFileName, args):
516     """
517     write a file with the given content ( args )
518     """
519     outFile = open(outFileName,"a")
520     outFile.write(str(args))
521     outFile.close()
522     return
523    
524 spiga 1.54 def readableList(self,rawList):
525 ewv 1.64 """
526     Turn a list of numbers into a string like 1-5,7,9,12-20
527     """
528     if not rawList:
529     return ''
530    
531 slacapra 1.56 listString = str(rawList[0])
532     endRange = ''
533     for i in range(1,len(rawList)):
534     if rawList[i] == rawList[i-1]+1:
535     endRange = str(rawList[i])
536     else:
537     if endRange:
538     listString += '-' + endRange + ',' + str(rawList[i])
539     endRange = ''
540     else:
541     listString += ',' + str(rawList[i])
542     if endRange:
543     listString += '-' + endRange
544     endRange = ''
545 ewv 1.64
546 slacapra 1.56 return listString
547 spiga 1.54
548 spiga 1.51 def getLocalDomain(self):
549 ewv 1.52 """
550 slacapra 1.56 Get local domain name
551 ewv 1.52 """
552 spiga 1.51 import socket
553 slacapra 1.88 tmp=socket.getfqdn()
554 spiga 1.51 dot=string.find(tmp,'.')
555     if (dot==-1):
556     msg='Unkown domain name. Cannot use local scheduler'
557     raise CrabException(msg)
558     localDomainName = string.split(tmp,'.',1)[-1]
559 ewv 1.52 return localDomainName
560 spiga 1.51
561 slacapra 1.56 #######################################################
562     # Brian Bockelman bbockelm@cse.unl.edu
563     # Module to check the avaialble disk space on a specified directory.
564     #
565    
566     def has_freespace(dir_name, needed_space_kilobytes):
567     enough_unix_quota = False
568     enough_quota = False
569     enough_partition = False
570     enough_mount = False
571     try:
572     enough_mount = check_mount(dir_name, need_space_kilobytes)
573     except:
574     enough_mount = True
575     try:
576     enough_quota = check_quota(dir_name, needed_space_kilobytes)
577     except:
578     raise
579     enough_quota = True
580     try:
581     enough_partition = check_partition(dir_name,
582     needed_space_kilobytes)
583     except:
584     enough_partition = True
585     try:
586     enough_unix_quota = check_unix_quota(dir_name,
587     needed_space_kilobytes)
588     except:
589     enough_unix_quota = True
590     return enough_mount and enough_quota and enough_partition \
591     and enough_unix_quota
592    
593     def check_mount(dir_name, needed_space_kilobytes):
594     try:
595     vfs = os.statvfs(dir_name)
596     except:
597     raise Exception("Unable to query VFS for %s." % dir_name)
598     dev_free = vfs[statvfs.F_FRSIZE] * vfs[statvfs.F_BAVAIL]
599     return dev_free/1024 > needed_space_kilobytes
600    
601     def check_quota(dir_name, needed_space_kilobytes):
602 spiga 1.100 results = runCommand("/usr/bin/fs lq %s" % dir_name)
603 spigafi 1.102 if not results :
604 slacapra 1.56 raise Exception("Unable to query the file system quota!")
605     try:
606     results = results.split('\n')[1].split()
607     quota, used = results[1:3]
608     avail = int(quota) - int(used)
609     return avail > needed_space_kilobytes
610     except:
611     return Exception("Unable to parse AFS output.")
612    
613     def check_partition(dir_name, needed_space_kilobytes):
614 spiga 1.100 results = runCommand("/usr/bin/fs diskfree %s" % dir_name)
615 spigafi 1.102 if not results :
616 slacapra 1.56 raise Exception("Unable to query the file system quota!")
617     try:
618     results = results.split('\n')[1].split()
619     avail = results[3]
620     return int(avail) > needed_space_kilobytes
621     except:
622     raise Exception("Unable to parse AFS output.")
623    
624     def check_unix_quota(dir_name, needed_space_kilobytes):
625 spiga 1.100 results = runCommand("df %s" % dir_name)
626 spigafi 1.102 if not results :
627 slacapra 1.56 raise Exception("Unable to query the filesystem with df.")
628     fs = results.split('\n')[1].split()[0]
629 spiga 1.100 results = runCommand("quota -Q -u -g")
630 slacapra 1.56 if fd.close():
631     raise Exception("Unable to query the quotas.")
632     has_info = False
633     for line in results.splitlines():
634     info = line.split()
635     if info[0] in ['Filesystem', 'Disk']:
636     continue
637     if len(info) == 1:
638     filesystem = info[0]
639     has_info = False
640     if len(info) == 6:
641 ewv 1.93 used, limit = info[0], max(info[1], info[2])
642 slacapra 1.56 has_info = True
643     if len(info) == 7:
644 ewv 1.93 filesystem, used, limit = info[0], info[1], max(info[2], info[3])
645 slacapra 1.56 has_info = True
646     if has_info:
647     if filesystem != fs:
648     continue
649     avail = int(limit) - int(used)
650     if avail < needed_space_kilobytes:
651     return False
652     return True
653 spiga 1.54
654 slacapra 1.57 def getGZSize(gzipfile):
655     # return the uncompressed size of a gzipped file
656     import struct
657     f = open(gzipfile, "rb")
658     if f.read(2) != "\x1f\x8b":
659     raise IOError("not a gzip file")
660     f.seek(-4, 2)
661 ewv 1.64 return struct.unpack("<i", f.read())[0]
662 slacapra 1.57
663 spiga 1.60 def showWebMon(server_name):
664 spiga 1.72 taskName = common._db.queryTask('name')
665 spiga 1.60 msg = ''
666 spiga 1.71 msg +='You can also follow the status of this task on :\n'
667 spiga 1.72 msg +='\tCMS Dashboard: http://dashb-cms-job-task.cern.ch/taskmon.html#task=%s\n'%(taskName)
668 ewv 1.64 if server_name != '' :
669 spiga 1.71 msg += '\tServer page: http://%s:8888/logginfo\n'%server_name
670 spiga 1.72 msg += '\tYour task name is: %s \n'%taskName
671 spiga 1.60 return msg
672    
673 slacapra 1.86 def SE2CMS(dests):
674 slacapra 1.85 """
675     Trasnsform a list of SE grid name into a list SE according to CMS naming convention
676     input: array of SE grid names
677     output: array of SE CMS names
678     """
679     from ProdCommon.SiteDB.CmsSiteMapper import SECmsMap
680     se_cms = SECmsMap()
681     SEDestination = [se_cms[d] for d in dests]
682     return SEDestination
683 spiga 1.60
684 slacapra 1.86 def CE2CMS(dests):
685     """
686     Trasnsform a list of CE grid name into a list SE according to CMS naming convention
687     input: array of CE grid names
688     output: array of CE CMS names
689     """
690     from ProdCommon.SiteDB.CmsSiteMapper import CECmsMap
691     ce_cms = CECmsMap()
692     CEDestination = [ce_cms[d] for d in dests]
693     return CEDestination
694    
695 spiga 1.95 def checkLcgUtils( ):
696 mcinquil 1.94 """
697     _checkLcgUtils_
698     check the lcg-utils version and report
699     """
700     import commands
701     cmd = "lcg-cp --version | grep lcg_util"
702     status, output = commands.getstatusoutput( cmd )
703     num_ver = -1
704     if output.find("not found") == -1 or status == 0:
705     temp = output.split("-")
706     version = ""
707     if len(temp) >= 2:
708     version = output.split("-")[1]
709     temp = version.split(".")
710     if len(temp) >= 1:
711     num_ver = int(temp[0])*10
712     num_ver += int(temp[1])
713     return num_ver
714    
715 spiga 1.95 def setLcgTimeout( ):
716     """
717     """
718     opt = ' -t 600 '
719     if checkLcgUtils() >= 17: opt=' --connect-timeout 600 '
720     return opt
721    
722 spiga 1.101
723 gutsche 1.20 ####################################
724 nsmirnov 1.4 if __name__ == '__main__':
725     print 'sys.argv[1] =',sys.argv[1]
726     list = parseRange2(sys.argv[1])
727     print list
728 slacapra 1.29 cksum = makeCksum("crab_util.py")
729     print cksum
730 ewv 1.44