srmvometrics.py 63.8 KB
Newer Older
Andrea Sciaba's avatar
Andrea Sciaba committed
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
#!/usr/bin/env python

##############################################################################
#
# NAME:        srmvometrics.py
#
# FACILITY:    SAM (Service Availability Monitoring)
#
# COPYRIGHT:
#         Copyright (c) 2009, Members of the EGEE Collaboration.
#         http://www.eu-egee.org/partners/
#         Licensed under the Apache License, Version 2.0.
#         http://www.apache.org/licenses/LICENSE-2.0
#         This software is provided "as is", without warranties
#         or conditions of any kind, either express or implied.
#
# DESCRIPTION:
#
#         VO-specific Nagios SRM metrics.
#
# AUTHORS:     Nicolo Magini, CERN
# AUTHORS:     Alessandro Di Girolamo, CERN
# AUTHORS:     Konstantin Skaburskas, CERN
#
# CREATED:     23-Jul-2010
#
# VERSION:     1.7.7
# MODIFIED:    12-Nov-2014
# NOTES:       Using new PhEDEX senames API to get list of SEs to test in CMS GetPFNFromTFC probe
#
#
##############################################################################

"""
Nagios SRM metrics.

Nagios SRM metrics.

Nicolo Magini <nicolo.magini@cern.ch>, 
Alessandro Di Girolamo <Alessandro.Di.Girolamo@cern.ch>
CERN IT Experiment Support
SAM (Service Availability Monitoring)
"""

import os
import sys
import getopt
48
import time
Andrea Sciaba's avatar
Andrea Sciaba committed
49
50
51
52
53
54
55
56
57
58
import commands
import errno
import re
import urllib2
import platform
import simplejson
import pickle
import datetime
import urlparse
import filecmp
59
import requests
Andrea Sciaba's avatar
Andrea Sciaba committed
60
61
62
63
64
65
66

try:
    from gridmon import probe
    from gridmon import utils as samutils
    from gridmon import gridutils
    from gridmon.process import signaling
    import gfal2
67
except ImportError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
68
69
70
71
72
73
74
75
76
77
78
79
80
    summary = "UNKNOWN: Error loading modules : %s" % (e)
    sys.stdout.write(summary+'\n')
    sys.stdout.write(summary+'\nsys.path: %s\n'% str(sys.path))
    sys.exit(3)

# Reasonable defaults for timeouts
LCG_GFAL_BDII_TIMEOUT = 10

LCG_UTIL_TIMEOUT_BDII = LCG_GFAL_BDII_TIMEOUT
LCG_UTIL_TIMEOUT_CONNECT = 10
LCG_UTIL_TIMEOUT_SENDRECEIVE = 120
LCG_UTIL_TIMEOUT_SRM = 180

81
82
gfal2.set_verbose(gfal2.verbose_level.debug)

83

Andrea Sciaba's avatar
Andrea Sciaba committed
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
class SRMVOMetrics(probe.MetricGatherer) :
    """A Metric Gatherer specific for SRM."""

    # Service version(s)
    svcVers = ['1', '2'] # NOT USED YET
    svcVer  = '2'

    # The probe's author name space -- CHANGE it to your ns
    ns = 'org.cms'

    # Timeouts
    _timeouts = {
                 'srm_connect'      : LCG_UTIL_TIMEOUT_SENDRECEIVE,
                 'ldap_timelimit'   : LCG_GFAL_BDII_TIMEOUT,
                 'LCG_GFAL_BDII_TIMEOUT' : LCG_GFAL_BDII_TIMEOUT,
                 'lcg_util' : {
                               'CLI': {
                                       'connect-timeout'    : LCG_UTIL_TIMEOUT_CONNECT,
                                       'sendreceive-timeout': LCG_UTIL_TIMEOUT_SENDRECEIVE,
                                       'bdii-timeout'       : LCG_UTIL_TIMEOUT_BDII,
                                       'srm-timeout'        : LCG_UTIL_TIMEOUT_SRM },
                               'API': {
                                       'connect-timeout'    : LCG_UTIL_TIMEOUT_CONNECT}
                               }
                  }

    _ldap_url  = "ldap://lcg-bdii.cern.ch:2170"
    
    probeinfo = { 'probeName'      : ns+'.SRM-Probe',
                  'probeVersion'   : '1.0',
                  'serviceVersion' : '1.*, 2.*'}
    # Metrics' info
    _metrics = { 
               'GetPFNFromTFC' : {'metricDescription': "Get full SRM endpoints and space tokens from PhEDEx DataService TFC module.",
                             'cmdLineOptions'   : ['lfn='],
                             'cmdLineOptionsReq' : [],
                             'metricChildren'   : ['VOLsDir','VOPut','VOLs','VOGetTURLs','VOGet','VODel'],
                             'critical'         :'N'
                             },
               'VOLsDir'    : {'metricDescription': "List content of VO's top level space area(s) in SRM.",
                             'cmdLineOptions'   : ['se-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : [],
                             'critical'         : 'N',
                             'statusMsgs'       : {'OK'      :'OK: Storage Path directory was listed successfully.',
                                                   'WARNING' :'WARNING: Problems listing Storage Path directory.'  ,
                                                   'CRITICAL':'CRITICAL: Problems listing Storage Path directory.' ,
                                                   'UNKNOWN' :'UNKNOWN: Problems listing Storage Path directory.'}
                             },
               'VOPut'      : {'metricDescription': "Copy a local file to the SRM into default space area(s).",
                             'cmdLineOptions'   : ['se-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : ['VOLs','VOGetTURLs','VOGet','VODel'],
                             'critical'         :'N'
                             },
               'VOLs'       : {'metricDescription': "List (previously copied) file(s) on the SRM.",
                             'cmdLineOptions'   : ['se-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : [],
                             'critical'         : 'N',
                             'statusMsgs'       : {'OK'      :'OK: File(s) was listed successfully.',
                                                   'WARNING' :'WARNING: Problems listing file(s).'  ,
                                                   'CRITICAL':'CRITICAL: Problems listing file(s).' ,
                                                   'UNKNOWN' :'UNKNOWN: Problems listing file(s).'}                                 
                             },
               'VOGetTURLs' : {'metricDescription': "Get Transport URLs for the file copied to storage.",
                             'cmdLineOptions'   : ['se-timeout=',
                                                   'ldap-uri=',
                                                   'ldap-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : [],
                             'critical'         : 'N'
                             },
               'VOGet'      : {'metricDescription': "Copy given remote file(s) from SRM to a local file.",
                             'cmdLineOptions'   : ['se-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : [],
                             'critical'         : 'N'
                             },
               'VODel'      : {'metricDescription': "Delete given file(s) from SRM.",
                             'cmdLineOptions'   : ['se-timeout='],
                             'cmdLineOptionsReq' : [],                             
                             'metricChildren'   : [],
                             'critical'         : 'N'
                             },
               'AllCMS'      : {'metricDescription': "Run all CMS metrics.",
                             'cmdLineOptions'   : [],
                             'cmdLineOptionsReq' : [],
                             'metricsOrder'     : ['GetPFNFromTFC','VOLsDir','VOPut','VOLs','VOGetTURLs','VOGet','VODel']
                             },
               }        

    def __init__(self, tuples):
        probe.MetricGatherer.__init__(self, tuples, 'SRM')
       
        self.usage="""    Metrics specific options:

--srmv <1|2>           (Default: %s)

%s
--ldap-uri <URI>       Format [ldap://]hostname[:port[/]] 
                       (Default: %s)
--ldap-timeout <sec>   (Default: %i)   
    
%s
--se-timeout <sec>     (Default: %i)

!!! NOT IMPLEMENTED YET !!!
--sapath <SAPath,...>  Storage Area Path to be tested on SRM. Comma separated 
                       list of Storage Paths to be tested.

"""%(self.svcVer,
     self.ns+'.SRM-{GetSURLs,GetTURLs}',
     self._ldap_url,
     self._timeouts['ldap_timelimit'],
     self.ns+'.SRM-{LsDir,Put,Ls,GetTURLs,Get,Del}',
     self._timeouts['srm_connect'])
     
        # TODO: move to super class
        # Need to be parametrized from CLI at runtime
        self.childTimeout = 120 # timeout

        # initiate metrics description
        self.set_metrics(self._metrics)

        # parse command line parameters
        self.parse_cmd_args(tuples)

        # working directory for metrics
        self.make_workdir()

        # LDAP
        self._ldap_fileEndptSAPath = self.workdir_metric+"/EndpointAndPath"

        # files and patterns
        self._fileTest       = self.workdir_metric+'/testFile.txt'
        self._fileTestIn     = self.workdir_metric+'/testFileIn.txt'
        self._fileSRMPattern = 'testfile-put-%s-%s-%s.txt' # spacetoken, time, uuid

        # Dictionary of extra SRM info for VOs, and file to save current version and history of dictionary
        curhour=datetime.datetime.now().hour
        self._fileHistoryVoInfoDictionary = self.workdir_metric+"/VOInfoDictionary_%s"%curhour
        self._fileVoInfoDictionary = self.workdir_metric+"/VOInfoDictionary"
227
        # Read dictionary from current cache
Andrea Sciaba's avatar
Andrea Sciaba committed
228
        try:
229
            # Clean up stale current cache entries (older than 3 days)
Andrea Sciaba's avatar
Andrea Sciaba committed
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
            try:
                modtime=os.path.getmtime(self._fileVoInfoDictionary)
                if (time.time()-modtime>3*86400):
                    self.printd('Stale VO Info cache file, deleting')
                    os.remove(self._fileVoInfoDictionary)
            except OSError:
                self.printd('VO Info cache file not found')
            self._voInfoDictionary = self.readVoInfoDictionary(self._fileVoInfoDictionary)
            self.printd('Loading VO Info dictionary from cache')
        except IOError:
            self._voInfoDictionary = {}
            self.printd('No cached VO Info dictionary; creating empty dictionary')
        except KeyError:
            self._voInfoDictionary = {}
            os.remove(self._fileVoInfoDictionary)
            self.printd('Cannot read cached VO Info dictionary; cleaning cache file and creating empty dictionary')
            
        # GFAL version
        self.gfal2_ver = "gfal2 " + gfal2.get_version()

        # lock file
        self._fileLock = self.workdir_metric+'/lock'
        self._fileLock_timelimit = 5*60
        'timelimit on working directory lock'

    def parse_args(self, opts):

        for o,v in opts:
            if o in ('--srmv'):
                if v in self.svcVers:
                    self.svcVer = str(v)
                else:
                    errstr = '--srmv must be one of '+\
                        ', '.join([x for x in self.svcVers])+'. '+v+' given.'
                    raise getopt.GetoptError(errstr)
            elif o in ('--ldap-uri'):
                [host, port] = samutils.parse_uri(v) 
                if port == None or port == '':
                    port = '2170'
                self._ldap_url = 'ldap://'+host+':'+port
                os.environ['LCG_GFAL_INFOSYS'] = host+':'+port
            elif o in ('--ldap-timeout'):
                self._timeouts['ldap_timelimit'] = int(v)
            elif o in ('--se-timeout'):
                self._timeouts['srm_connect'] = int(v)

    def __workdir_islocked(self):
        """Check if working directory is locked within allowed timelimit.
        """
        if not os.path.exists(self._fileLock):
            return False
        else:
            delta = time.time() - os.stat(self._fileLock).st_ctime
            if delta >= self._fileLock_timelimit:
                os.unlink(self._fileLock)
                return False
            else:
                return True

    def __workdir_lock(self):
        """Lock working directory.
        """
        if self.__workdir_islocked():
            raise IOError('Working directory is locked: %s' %
                          self.workdir_metric)
        file(self._fileLock, 'w')

    def __workdir_unlock(self):
        """Unlock working directory.
        """
        try: os.unlink(self._fileLock)
        except OSError: pass
    
    def saveVoInfoDictionary(self,filename):
        fp = open(filename, "w")
        pickle.dump(self._voInfoDictionary,fp)
        fp.close()
                
    def readVoInfoDictionary(self,filename):
        fp = open(filename, "r")
        voInfoDict=pickle.load(fp)
        fp.close()
        return voInfoDict

    def weightEndpointCriticality(self,VOtest):
315
316
        DetailedMsg = ''
        CriticalResult = []
Andrea Sciaba's avatar
Andrea Sciaba committed
317
318
        for srmendpt in self._voInfoDictionary.keys():
            try:
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
                try:
                    criticality = self._voInfoDictionary[srmendpt]['criticality']
                except KeyError:
                    criticality = 1
                if criticality == 1:
                    CriticalResult.append(self._voInfoDictionary[srmendpt][VOtest][0])
                # DetailedMsg = DetailedMsg + str(self._voInfoDictionary[srmendpt])
                DetailedMsg = DetailedMsg + \
                              str(self._voInfoDictionary[srmendpt]['space_token']) + \
                              " critical= " + str(criticality) + \
                              " " + str(self._voInfoDictionary[srmendpt][VOtest][1]) + \
                              " file= " + str(self._voInfoDictionary[srmendpt]['fn']) + \
                              "\n"
                # self.printd('VO specific Detailed Output: %s' % str(DetailedMsg))
            except IndexError:
                return 'UNKNOWN', 'No SRM endpoints found in internal dictionary'
Andrea Sciaba's avatar
Andrea Sciaba committed
335
            except KeyError:
336
337
                return 'UNKNOWN', 'No test results found in internal dictionary for SRM endpoint'
        # print " GLOBAL result     \n \n \n \n \n "
Andrea Sciaba's avatar
Andrea Sciaba committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
        ## oredering criticality
        self.printd('VO specific Detailed Output: %s' % str(DetailedMsg))
        if 'CRITICAL' in CriticalResult:                # it's enough one CRIT  
          #return ('CRITICAL' ,str(DetailedMsg))
          return ('CRITICAL') 
        if 'WARNING' in CriticalResult:         #
          #return ('WARNING' ,str(DetailedMsg))
          return ('WARNING')
        if 'UNKNOWN' in CriticalResult:                 #
          #return ('UNKNOWN' ,str(DetailedMsg))
          return ('UNKNOWN')
        #return ('OK' ,str(DetailedMsg)) # all OK
        return ('OK')

    def metricAllCMS(self):
        return self.metricAll('AllCMS')

    def metricAllATLAS(self):
        return self.metricAll('AllATLAS')

    def metricAllLHCb(self):
        return self.metricAll('AllLHCb')

361
    def oldmetricGetPFNFromTFC(self, testLFN="/store/unmerged/SAM/testSRM"):
Andrea Sciaba's avatar
Andrea Sciaba committed
362
363
364
365
366
        """Get full SRM endpoint(s) and storage areas from PhEDEx DataService.
        """

        try:
            self.__workdir_lock()
367
        except IOError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
368
369
370
            self.printd('Failed to lock. %s' % str(e))
            return 'UNKNOWN', 'UNKNOWN: Failed to lock working directory.'

371
        # URLs for PhEDEx DataService for lfn2pfn
Andrea Sciaba's avatar
Andrea Sciaba committed
372
373
374
375
376
377
378
379
380
381
382
383
384
        tfcURL="https://cmsweb.cern.ch/phedex/datasvc/json/prod/lfn2pfn?node="
        pfnMatchURL="&lfn="
        pfnProtocolOption = "&protocol=srmv2"
        destinationOption = "&destination="
        custodialOption = "&custodial="

        #URLs for PhEDEx DataService for senames API
        seNamesURL="https://cmsweb.cern.ch/phedex/datasvc/json/prod/senames?protocol=srmv2&sename=%s"
        nodeName = self.hostName

        opener=urllib2.build_opener()
        header='grid-monitoring-probes-org.cms.SRM-GetPFNFromTFC/1.0 (CMS) %s/%s %s/%s (%s)' % (urllib2.__name__,urllib2.__version__,platform.system(),platform.release(),platform.processor())
        opener.addheaders = [('User-agent', header)]
385
        headers = {'user-agent': header}
Andrea Sciaba's avatar
Andrea Sciaba committed
386
387
388
389
390
391
392

        # LFN path for file to test transfers
        self.printd('The LFN used for testing will be in: '+testLFN)

        try:
            self.printd("Contacting PhEDEx dataservice to perform SEName-to-PhEDExNodeName at URL:")
            self.printd(seNamesURL % nodeName)
393
394
395
396
            req = requests.get(seNamesURL % nodeName, headers=headers, verify=False, timeout=120)
            req.raise_for_status()
            seNames = req.content
            seNamesJSON = simplejson.loads(seNames)
Andrea Sciaba's avatar
Andrea Sciaba committed
397
            phedexNodeNames = seNamesJSON[u'phedex'][u'senames']
398
        except (requests.HTTPError, KeyError):
Andrea Sciaba's avatar
Andrea Sciaba committed
399
400
401
            self.printd('WARNING: Unable to open PhEDEx DataService senames API to perform SEName-to-PhEDExNodeName matching for SEName %s' % nodeName)
            if len(self._voInfoDictionary):
                self.printd("WARNING: using cached PFN")
402
                # Update timestamp/uuid in cached PFN
Andrea Sciaba's avatar
Andrea Sciaba committed
403
404
405
406
407
408
409
                for pfn in self._voInfoDictionary:
                    try:
                        self._voInfoDictionary[pfn]['fn'] = self._voInfoDictionary[pfn]['fntemp'] % (str(int(time.time())), samutils.uuidstr())
                        self.printd("The PFN path used for testing will be:")
                        self.printd(pfn+" : "+str(self._voInfoDictionary[pfn]))
                    except KeyError:
                        self.printd("WARNING: no cached PFN found")
410
411
                        return 'WARNING', "WARNING: Unable to open PhEDEx DataService senames API, no cached PFN found"
                return 'OK', "WARNING: Unable to open PhEDEx DataService senames API, using cached PFN"
Andrea Sciaba's avatar
Andrea Sciaba committed
412
413
            else:
                self.printd("WARNING: no cached PFN found")
414
                return 'WARNING', "WARNING: Unable to open PhEDEx DataService senames API, no cached PFN found"
Andrea Sciaba's avatar
Andrea Sciaba committed
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

        outputList={}
        
        for pNNLine in phedexNodeNames:
            endpointName=pNNLine[u'sename']
            try:
                siteName=pNNLine[u'node']
            except KeyError:
                continue
        
            if endpointName == nodeName:
                
                self.printd(nodeName+" is listed as SRM for Site "+siteName)
                
                # Contact web service to get PFN and spacetoken for non-custodial transfers
                endpointLFN = "/SAM-%s/lcg-util" % endpointName

                # Testing only non-custodial area - don't want to clutter custodial area with small files at T1s
                custodiality = "n"
                    
                pfnUrl = tfcURL+siteName+pfnMatchURL+testLFN+endpointLFN+pfnProtocolOption+destinationOption+siteName+custodialOption+custodiality
                self.printd("Setting custodiality flag="+custodiality)
                self.printd("Contacting webservice to perform LFN-to-PFN matching at URL:")
                self.printd(pfnUrl)

                try:
441
442
443
444
                    req = requests.get(pfnUrl, headers=headers, verify=False, timeout=120)
                    req.raise_for_status()
                    pfnFile = req.content
                    pfnJSON = simplejson.loads(pfnFile)
Andrea Sciaba's avatar
Andrea Sciaba committed
445
446
                    pfn = (((pfnJSON[u'phedex'])[u'mapping'])[0])[u'pfn']
                    spacetoken = (((pfnJSON[u'phedex'])[u'mapping'])[0])[u'space_token']
447
                except (requests.HTTPError, KeyError):
Andrea Sciaba's avatar
Andrea Sciaba committed
448
449
450
                    self.printd('WARNING: Unable to open PhEDEx DataService lfn2pfn URL to perform LFN-to-PFN matching for Site %s' % siteName)
                    continue

451
                if not pfn:
Andrea Sciaba's avatar
Andrea Sciaba committed
452
453
454
455
456
457
458
459
460
461
462
463
464
                    self.printd("ERROR: LFN did not match to any PFN - probably the TFC does not contain any rule for the srmv2 protocol.")
                    continue
                
                self.printd("LFN was matched to PFN "+pfn)
                if spacetoken:
                    spacetokendesc=spacetoken
                    self.printd("In space token "+spacetoken+" for custodiality="+custodiality)
                else:
                    spacetokendesc="nospacetoken"
                    self.printd("No space token defined for custodiality="+custodiality)

                if re.compile("^srm://.+srm/managerv2\?SFN=.+$").match(pfn) or re.compile("^srm://.+srm/v2/server\?SFN=.+$").match(pfn):
                    pfntonode=re.sub(":.+$","",re.sub("^srm://","",pfn))
465
                    if pfntonode != nodeName :
Andrea Sciaba's avatar
Andrea Sciaba committed
466
467
468
                        self.printd("WARNING: the resulting PFN matches to SRM "+pfntonode+" instead of SRM "+nodeName)
                        continue
                    else:
469
                        fntemp = self._fileSRMPattern % (spacetokendesc, '%s', '%s')
Andrea Sciaba's avatar
Andrea Sciaba committed
470
                        fn = fntemp % (str(int(time.time())), samutils.uuidstr())
471
                        outputList[pfn] = {'fntemp': fntemp, 'fn': fn, 'space_token': spacetoken, 'space_token_get': spacetoken, 'userspace' : testLFN}
Andrea Sciaba's avatar
Andrea Sciaba committed
472
                elif pfn.startswith("gsiftp://"):
473
                    pfntonode = urlparse.urlparse(pfn).hostname
Andrea Sciaba's avatar
Andrea Sciaba committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
                    fntemp = self._fileSRMPattern % (spacetokendesc,'%s','%s')
                    fn = fntemp % (str(int(time.time())), samutils.uuidstr())
                    outputList[pfn]={'fntemp' : fntemp, 'fn': fn, 'space_token': spacetoken, 'space_token_get': spacetoken, 'userspace' : testLFN}
                else:
                    self.printd("WARNING: Invalid matching to srmv2 protocol")
                    self.printd("Note: this test currently supports only PFNs in the known srmv2 full endpoint formats:")
                    self.printd("srm://hostname:port/srm/managerv2?SFN=sitefilename")
                    self.printd("or")
                    self.printd("srm://hostname:port/srm/v2/server?SFN=sitefilename")
                    self.printd("or")
                    self.printd("gsiftp://hostname:port/sitefilename")

        # Extract a random PFN from the dictionary of PFN matches. It will be used for testing, other PFN matches will be ignored
        # Print warning if not all PFN matches are the same.
488
489
490
491
492
493
        if len(outputList) == 0:
            self.printd("WARNING: " + nodeName + " not found in SRM list")
            self.printd(
                "WARNING: This error usually means that the site is not running PhEDEx agents in the Prod instance,")
            self.printd(
                "WARNING: or that the TrivialFileCatalog published by the site's PhEDEx agents doesn't have a valid srmv2 protocol rule for " + nodeName)
Andrea Sciaba's avatar
Andrea Sciaba committed
494
495
496
497
498
499
500
            if len(self._voInfoDictionary):
                self.printd("WARNING: using cached PFN")
                # Update timestamp/uuid in cached PFN
                for pfn in self._voInfoDictionary:
                    try:
                        self._voInfoDictionary[pfn]['fn'] = self._voInfoDictionary[pfn]['fntemp'] % (str(int(time.time())), samutils.uuidstr())
                        self.printd("The PFN path used for testing will be:")
501
                        self.printd(pfn + " : " + str(self._voInfoDictionary[pfn]))
Andrea Sciaba's avatar
Andrea Sciaba committed
502
503
                    except KeyError:
                        self.printd("WARNING: no cached PFN found")
504
505
                        return ('WARNING', "WARNING: " + nodeName + " not found in SRM list, no cached PFN found")
                return ('OK', "WARNING: " + nodeName + " not found in SRM list, using cached PFN")
Andrea Sciaba's avatar
Andrea Sciaba committed
506
507
            else:
                self.printd("WARNING: no cached PFN found")
508
                return ('WARNING', "WARNING: " + nodeName + " not found in SRM list, no cached PFN found")
Andrea Sciaba's avatar
Andrea Sciaba committed
509

510
511
        else:
            self._voInfoDictionary = outputList
Andrea Sciaba's avatar
Andrea Sciaba committed
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530

        for outputPfns in outputList:
            self.printd("The PFN path used for testing will be:")
            self.printd(outputPfns+" : "+str(outputList[outputPfns]))
            
        self.printd('Saving endpoints to %s' % self._fileVoInfoDictionary, v=2)
        self.printd('Test results will be saved to %s' % self._fileHistoryVoInfoDictionary, v=2)

        try:
            self.saveVoInfoDictionary(self._fileVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileVoInfoDictionary)
        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary history to file %s' % self._fileHistoryVoInfoDictionary)

        return ('OK', "Got PFN and Space Token from PhEDEx DataService")

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
    def metricGetPFNFromTFC(self, testLFN="/store/unmerged/SAM/testSRM"):
        """Get full SRM endpoint(s) and storage areas from PhEDEx DataService.
        """

        try:
            self.__workdir_lock()
        except IOError as e:
            self.printd('Failed to lock. %s' % str(e))
            return 'UNKNOWN', 'UNKNOWN: Failed to lock working directory.'

        PFNTable = { 'srm-cms.cern.ch': "srm://srm-cms.cern.ch:8443/srm/managerv2?SFN=/castor/cern.ch/cms/store/unmerged/SAM/testSRM/SAM-srm-cms.cern.ch/lcg-util",
                     'eoscmsftp.cern.ch': "gsiftp://eoscmsftp.cern.ch//eos/cms/store/unmerged/SAM/testSRM/SAM-eoscmsftp.cern.ch/lcg-util",
                     'cmssrm-kit.gridka.de': "srm://cmssrm-kit.gridka.de:8443/srm/managerv2?SFN=/pnfs/gridka.de/cms/disk-only/store/unmerged/SAM/testSRM/SAM-cmssrm-kit.gridka.de/lcg-util",
                     'srmcms.pic.es': "srm://srmcms.pic.es:8443/srm/managerv2?SFN=/pnfs/pic.es/data/cms/disk/store/unmerged/SAM/testSRM/SAM-srmcms.pic.es/lcg-util",
                     'ccsrm.in2p3.fr': "srm://ccsrm.in2p3.fr:8443/srm/managerv2?SFN=/pnfs/in2p3.fr/data/cms/prod/store/unmerged/SAM/testSRM/SAM-ccsrm.in2p3.fr/lcg-util",
                     'storm-fe-cms.cr.cnaf.infn.it': "srm://storm-fe-cms.cr.cnaf.infn.it:8444/srm/managerv2?SFN=/cmstape/store/unmerged/SAM/testSRM/SAM-storm-fe-cms.cr.cnaf.infn.it/lcg-util",
                     'srm-cms.jinr-t1.ru': "srm://srm-cms.jinr-t1.ru:8443/srm/managerv2?SFN=/pnfs/jinr-t1.ru/data/cms/store/unmerged/SAM/testSRM/SAM-srm-cms.jinr-t1.ru/lcg-util",
                     'srm-cms-mss.jinr-t1.ru': "srm://srm-cms-mss.jinr-t1.ru:8443/srm/managerv2?SFN=/pnfs/jinr-t1.ru/data/cms/store/unmerged/SAM/testSRM/SAM-srm-cms-mss.jinr-t1.ru/lcg-util",
                     'gridftp.echo.stfc.ac.uk': "gsiftp://gridftp.echo.stfc.ac.uk/cms:/store/unmerged/SAM/testSRM/SAM-gridftp.echo.stfc.ac.uk/lcg-util",
                     'srm-cms.gridpp.rl.ac.uk': "srm://srm-cms.gridpp.rl.ac.uk:8443/srm/managerv2?SFN=/castor/ads.rl.ac.uk/prod/cms/store/unmerged/SAM/testSRM/SAM-srm-cms.gridpp.rl.ac.uk/lcg-util",
                     'cmsdcatape.fnal.gov': "srm://cmsdcatape.fnal.gov:8443/srm/managerv2?SFN=/11/store/unmerged/SAM/testSRM/SAM-cmsdcatape.fnal.gov/lcg-util",
                     'cmsdcadisk.fnal.gov': "srm://cmsdcadisk.fnal.gov:8443/srm/managerv2?SFN=/dcache/uscmsdisk/store/unmerged/SAM/testSRM/SAM-cmsdcadisk.fnal.gov/lcg-util",
                     'se.grid.vbc.ac.at': "gsiftp://se.grid.vbc.ac.at:2811//eos/vbc/experiments/cms/store/unmerged/SAM/testSRM/SAM-se.grid.vbc.ac.at/lcg-util",
                     'maite.iihe.ac.be': "srm://maite.iihe.ac.be:8443/srm/managerv2?SFN=/pnfs/iihe/cms/ph/sc4/store/unmerged/SAM/testSRM/SAM-maite.iihe.ac.be/lcg-util",
                     'ingrid-se02.cism.ucl.ac.be': "srm://ingrid-se02.cism.ucl.ac.be:8444/srm/managerv2?SFN=/storage/data/cms/store/unmerged/SAM/testSRM/SAM-ingrid-se02.cism.ucl.ac.be/lcg-util",
                     'osg-se.sprace.org.br': "srm://osg-se.sprace.org.br:8443/srm/managerv2?SFN=/pnfs/sprace.org.br/data/cms/store/unmerged/SAM/testSRM/SAM-osg-se.sprace.org.br/lcg-util",
                     'gridftp.hepgrid.uerj.br': "gsiftp://gridftp.hepgrid.uerj.br//mnt/hadoop/cms//store/unmerged/SAM/testSRM/SAM-gridftp.hepgrid.uerj.br/lcg-util",
                     'eoscmsftp.cern.ch': "gsiftp://eoscmsftp.cern.ch//eos/cms/store/unmerged/SAM/testSRM/SAM-eoscmsftp.cern.ch/lcg-util",
                     'storage01.lcg.cscs.ch': "srm://storage01.lcg.cscs.ch:8443/srm/managerv2?SFN=/pnfs/lcg.cscs.ch/cms/trivcat/store/unmerged/SAM/testSRM/SAM-storage01.lcg.cscs.ch/lcg-util",
Andrea Sciaba's avatar
Andrea Sciaba committed
560
                     'ccsrm.ihep.ac.cn': "gsiftp://ccsrm.ihep.ac.cn:2811/dpm/ihep.ac.cn/home/cms/store/unmerged/SAM/testSRM/SAM-srm.ihep.ac.cn/lcg-util",
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
                     'srm.ihep.ac.cn': "srm://srm.ihep.ac.cn:8443/srm/managerv2?SFN=/pnfs/ihep.ac.cn/data/cms/store/unmerged/SAM/testSRM/SAM-srm.ihep.ac.cn/lcg-util",
                     'dcache-se-cms.desy.de': "srm://dcache-se-cms.desy.de:8443/srm/managerv2?SFN=/pnfs/desy.de/cms/tier2/unmerged/SAM/testSRM/SAM-dcache-se-cms.desy.de/lcg-util",
                     'grid-srm.physik.rwth-aachen.de': "srm://grid-srm.physik.rwth-aachen.de:8443/srm/managerv2?SFN=/pnfs/physik.rwth-aachen.de/cms/store/unmerged/SAM/testSRM/SAM-grid-srm.physik.rwth-aachen.de/lcg-util",
                     'ganymede.hep.kbfi.ee': "gsiftp://ganymede.hep.kbfi.ee:2811//cms/store/unmerged/SAM/testSRM/SAM-ganymede.hep.kbfi.ee/lcg-util",
                     'srm.ciemat.es': "srm://srm.ciemat.es:8443/srm/managerv2?SFN=/pnfs/ciemat.es/data/cms/prod/store/unmerged/SAM/testSRM/SAM-srm.ciemat.es/lcg-util",
                     'storm.ifca.es': "srm://storm.ifca.es:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-storm.ifca.es/lcg-util",
                     'madhatter.csc.fi': "srm://madhatter.csc.fi:8443/srm/managerv2?SFN=/pnfs/csc.fi/data/cms/store/unmerged/SAM/testSRM/SAM-madhatter.csc.fi/lcg-util",
                     'ccsrmt2.in2p3.fr': "srm://ccsrmt2.in2p3.fr:8443/srm/managerv2?SFN=/pnfs/in2p3.fr/data/cms/t2data/store/unmerged/SAM/testSRM/SAM-ccsrmt2.in2p3.fr/lcg-util",
                     'node12.datagrid.cea.fr': "gsiftp://node12.datagrid.cea.fr/dpm/datagrid.cea.fr/home/cms/trivcat/store/unmerged/SAM/testSRM/SAM-node12.datagrid.cea.fr/lcg-util",
                     'polgrid4.in2p3.fr': "gsiftp://polgrid4.in2p3.fr/dpm/in2p3.fr/home/cms/trivcat/store/unmerged/SAM/testSRM/SAM-polgrid4.in2p3.fr/lcg-util",
                     'sbgse1.in2p3.fr': "srm://sbgse1.in2p3.fr:8446/srm/managerv2?SFN=/dpm/in2p3.fr/home/cms/phedex/store/unmerged/SAM/testSRM/SAM-sbgse1.in2p3.fr/lcg-util",
                     'grid02.physics.uoi.gr': "srm://grid02.physics.uoi.gr:8446/srm/managerv2?SFN=/dpm/physics.uoi.gr/home/cms/store/unmerged/SAM/testSRM/SAM-grid02.physics.uoi.gr/lcg-util",
                     'grid143.kfki.hu': "srm://grid143.kfki.hu:8446/srm/managerv2?SFN=/dpm/kfki.hu/home/cms/phedex/store/unmerged/SAM/testSRM/SAM-grid143.kfki.hu/lcg-util",
                     'se01.indiacms.res.in': "srm://se01.indiacms.res.in:8446/srm/managerv2?SFN=/dpm/indiacms.res.in/home/cms/store/unmerged/SAM/testSRM/SAM-se01.indiacms.res.in/lcg-util",
                     'storm-se-01.ba.infn.it': "srm://storm-se-01.ba.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-storm-se-01.ba.infn.it/lcg-util",
                     't2-srm-02.lnl.infn.it': "srm://t2-srm-02.lnl.infn.it:8443/srm/managerv2?SFN=/pnfs/lnl.infn.it/data/cms/store/unmerged/SAM/testSRM/SAM-t2-srm-02.lnl.infn.it/lcg-util",
                     'stormfe1.pi.infn.it': "srm://stormfe1.pi.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-stormfe1.pi.infn.it/lcg-util",
                     'cmsrm-se01.roma1.infn.it': "srm://cmsrm-se01.roma1.infn.it:8443/srm/managerv2?SFN=/pnfs/roma1.infn.it/data/cms/store/unmerged/SAM/testSRM/SAM-cmsrm-se01.roma1.infn.it/lcg-util",
                     'cms-t2-se01.sdfarm.kr': "srm://cms-t2-se01.sdfarm.kr:8443/srm/managerv2?SFN=/pnfs/sdfarm.kr/data/cms/store/unmerged/SAM/testSRM/SAM-cms-t2-se01.sdfarm.kr/lcg-util",
                     'pcncp22.ncp.edu.pk': "srm://pcncp22.ncp.edu.pk:8446/srm/managerv2?SFN=/dpm/ncp.edu.pk/home/cms/store/unmerged/SAM/testSRM/SAM-pcncp22.ncp.edu.pk/lcg-util",
                     'se.cis.gov.pl': "gsiftp://se.cis.gov.pl:2811//dpm/cis.gov.pl/home/cms/store/unmerged/SAM/testSRM/SAM-se.cis.gov.pl/lcg-util",
                     'se.grid.icm.edu.pl': "gsiftp://se.grid.icm.edu.pl/dpm/grid.icm.edu.pl/home/cms/phedex/store/store/unmerged/SAM/testSRM/SAM-se.grid.icm.edu.pl/lcg-util",
                     'srm01.ncg.ingrid.pt': "srm://srm01.ncg.ingrid.pt:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-srm01.ncg.ingrid.pt/lcg-util",
                     'dp0015.m45.ihep.su': "srm://dp0015.m45.ihep.su:8443/srm/managerv2?SFN=/pnfs/m45.ihep.su/data/cms/store/unmerged/SAM/testSRM/SAM-dp0015.m45.ihep.su/lcg-util",
                     'grse001.inr.troitsk.ru': "srm://grse001.inr.troitsk.ru:8446/srm/managerv2?SFN=/dpm/inr.troitsk.ru/home/cms/store/unmerged/SAM/testSRM/SAM-grse001.inr.troitsk.ru/lcg-util",
                     'se3.itep.ru': "srm://se3.itep.ru:8443/srm/managerv2?SFN=/pnfs/itep.ru/data/cms/store/unmerged/SAM/testSRM/SAM-se3.itep.ru/lcg-util",
                     'lcgsedc01.jinr.ru': "srm://lcgsedc01.jinr.ru:8443/srm/managerv2?SFN=/pnfs/jinr.ru/data/cms/store/unmerged/SAM/testSRM/SAM-lcgsedc01.jinr.ru/lcg-util",
                     'eymir.grid.metu.edu.tr': "srm://eymir.grid.metu.edu.tr:8446/srm/managerv2?SFN=/dpm/grid.metu.edu.tr/home/cms/store/unmerged/SAM/testSRM/SAM-eymir.grid.metu.edu.tr/lcg-util",
                     'se01.grid.nchc.org.tw': "srm://se01.grid.nchc.org.tw:8446/srm/managerv2?SFN=/dpm/grid.nchc.org.tw/home/cms/store/unmerged/SAM/testSRM/SAM-se01.grid.nchc.org.tw/lcg-util",
                     'cms-se0.kipt.kharkov.ua': "srm://cms-se0.kipt.kharkov.ua:8446/srm/managerv2?SFN=/dpm/kipt.kharkov.ua/home/cms/store/unmerged/SAM/testSRM/SAM-cms-se0.kipt.kharkov.ua/lcg-util",
                     'dc2-grid-64.brunel.ac.uk': "gsiftp://dc2-grid-64.brunel.ac.uk/dpm/brunel.ac.uk/home/cms/store/unmerged/SAM/testSRM/SAM-dc2-grid-64.brunel.ac.uk/lcg-util",
                     'gfe02.grid.hep.ph.ic.ac.uk': "srm://gfe02.grid.hep.ph.ic.ac.uk:8443/srm/managerv2?SFN=/pnfs/hep.ph.ic.ac.uk/data/cms/store/unmerged/SAM/testSRM/SAM-gfe02.grid.hep.ph.ic.ac.uk/lcg-util",
                     'lcgse01.phy.bris.ac.uk': "gsiftp://lcgse01.phy.bris.ac.uk/dpm/phy.bris.ac.uk/home/cms/store/unmerged/SAM/testSRM/SAM-lcgse01.phy.bris.ac.uk/lcg-util",
                     'heplnx204.pp.rl.ac.uk': "srm://heplnx204.pp.rl.ac.uk:8443/srm/managerv2?SFN=/pnfs/pp.rl.ac.uk/data/cms/store/unmerged/SAM/testSRM/SAM-heplnx204.pp.rl.ac.uk/lcg-util",
                     'transfer.ultralight.org': "gsiftp://transfer.ultralight.org:2811//mnt/hadoop//store/unmerged/SAM/testSRM/SAM-transfer.ultralight.org/lcg-util",
                     'cmsio.rc.ufl.edu': "gsiftp://cmsio.rc.ufl.edu//cmsuf/data/store/unmerged/SAM/testSRM/SAM-cmsio.rc.ufl.edu/lcg-util",
                     'se01.cmsaf.mit.edu': "gsiftp://se01.cmsaf.mit.edu:2811/cms/store/unmerged/SAM/testSRM/SAM-se01.cmsaf.mit.edu/lcg-util",
                     'red-gridftp.unl.edu': "gsiftp://red-gridftp.unl.edu//mnt/hadoop/user/uscms01/pnfs/unl.edu/data4/cms/store/unmerged/SAM/testSRM/SAM-red-gridftp.unl.edu/lcg-util",
                     'cms-gridftp.rcac.purdue.edu': "gsiftp://cms-gridftp.rcac.purdue.edu//store/unmerged/SAM/testSRM/SAM-cms-gridftp.rcac.purdue.edu/lcg-util",
                     'gftp.t2.ucsd.edu': "gsiftp://gftp.t2.ucsd.edu/hadoop/cms/phedex/store/unmerged/SAM/testSRM/SAM-gftp.t2.ucsd.edu/lcg-util",
                     'gridftp.accre.vanderbilt.edu': "gsiftp://gridftp.accre.vanderbilt.edu/lio/lfs/cms/store/unmerged/SAM/testSRM/SAM-gridftp.accre.vanderbilt.edu/lcg-util",
                     'cms-lvs-gridftp.hep.wisc.edu': "gsiftp://cms-lvs-gridftp.hep.wisc.edu//hdfs/store/unmerged/SAM/testSRM/SAM-cms-lvs-gridftp.hep.wisc.edu/lcg-util",
                     'dcache.grid.uni-sofia.bg': "srm://dcache.grid.uni-sofia.bg:8443/srm/managerv2?SFN=/data/uni-sofia.bg/cms/store/unmerged/SAM/testSRM/SAM-dcache.grid.uni-sofia.bg/lcg-util",
                     'grid02.hep.by': "srm://grid02.hep.by:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-grid02.hep.by/lcg-util",
                     'eospublicftp.cern.ch': "gsiftp://eospublicftp.cern.ch//eos/opendata/cms/upload/unmerged/SAM/testSRM/SAM-eospublicftp.cern.ch/lcg-util",
                     'data-bridge.cern.ch': "https://data-bridge.cern.ch/myfed/cms-output/unmerged/SAM/testSRM/SAM-data-bridge.cern.ch/lcg-util",
                     't3se01.psi.ch': "srm://t3se01.psi.ch:8443/srm/managerv2?SFN=/pnfs/psi.ch/cms/trivcat/store/unmerged/SAM/testSRM/SAM-t3se01.psi.ch/lcg-util",
                     'grid09.phy.pku.edu.cn': "srm://grid09.phy.pku.edu.cn:8446/srm/managerv2?SFN=/dpm//phy.pku.edu.cn/home/cms/store/unmerged/SAM/testSRM/SAM-grid09.phy.pku.edu.cn/lcg-util",
                     'lyogrid06.in2p3.fr': "srm://lyogrid06.in2p3.fr:8446/srm/managerv2?SFN=/dpm/in2p3.fr/home/cms/data/store/unmerged/SAM/testSRM/SAM-lyogrid06.in2p3.fr/lcg-util",
                     'lorienmaster.irb.hr': "srm://lorienmaster.irb.hr:8444/srm/managerv2?SFN=/STORE/se/cms/store/unmerged/SAM/testSRM/SAM-lorienmaster.irb.hr/lcg-util",
                     'dpm.grid.atomki.hu': "srm://dpm.grid.atomki.hu:8446/srm/managerv2?SFN=/dpm/grid.atomki.hu/home/cms/phedex/store/unmerged/SAM/testSRM/SAM-dpm.grid.atomki.hu/lcg-util",
                     'storage.vb-ehep.in': "srm://storage.vb-ehep.in:8446/srm/managerv2?SFN=/dpm/vb-ehep.in/home/cms/store/unmerged/SAM/testSRM/SAM-storage.vb-ehep.in/lcg-util",
                     'se1.particles.ipm.ac.ir': "srm://se1.particles.ipm.ac.ir:8446/srm/managerv2?SFN=/dpm/particles.ipm.ac.ir/home/cms/store/unmerged/SAM/testSRM/SAM-se1.particles.ipm.ac.ir/lcg-util",
                     'sebo-t3-01.cr.cnaf.infn.it': "srm://sebo-t3-01.cr.cnaf.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-sebo-t3-01.cr.cnaf.infn.it/lcg-util",
                     'storm.mib.infn.it': "srm://storm.mib.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-storm.mib.infn.it/lcg-util",
                     'gridse2.pg.infn.it': "srm://gridse2.pg.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-gridse2.pg.infn.it/lcg-util",
                     'gridsrm.ts.infn.it': "srm://gridsrm.ts.infn.it:8444/srm/managerv2?SFN=/cms/store/unmerged/SAM/testSRM/SAM-gridsrm.ts.infn.it/lcg-util",
                     'srm-eosinfnts.ts.infn.it': "gsiftp://srm-eosinfnts.ts.infn.it:2811//eos/infnts/cms/store/unmerged/SAM/testSRM/SAM-srm-eosinfnts.ts.infn.it/lcg-util",
                     'cms-se.sdfarm.kr': "gsiftp://cms-se.sdfarm.kr//xrootd/store/unmerged/SAM/testSRM/SAM-cms-se.sdfarm.kr/lcg-util",
                     'cluster142.knu.ac.kr': "srm://cluster142.knu.ac.kr:8443/srm/managerv2?SFN=/pnfs/knu.ac.kr/data/cms/store/unmerged/SAM/testSRM/SAM-cluster142.knu.ac.kr/lcg-util",
                     'phedex.sscc.uos.ac.kr': "gsiftp://phedex.sscc.uos.ac.kr:2811//hdfs/store/unmerged/SAM/testSRM/SAM-phedex.sscc.uos.ac.kr/lcg-util",
                     'proton.fis.cinvestav.mx': "gsiftp://proton.fis.cinvestav.mx//meson/data/store/unmerged/SAM/testSRM/SAM-proton.fis.cinvestav.mx/lcg-util",
                     'se2.grid.lebedev.ru': "srm://se2.grid.lebedev.ru:8446/srm/managerv2?SFN=/dpm/grid.lebedev.ru/home/cms/store/unmerged/SAM/testSRM/SAM-se2.grid.lebedev.ru/lcg-util",
                     'cms-phedex.lxfarm.mephi.ru': "srm://cms-phedex.lxfarm.mephi.ru:8443/data/phedex/unmerged/SAM/testSRM/SAM-cms-phedex.lxfarm.mephi.ru/lcg-util",
                     'cms-se.sc.chula.ac.th': "srm://cms-se.sc.chula.ac.th:8446/srm/managerv2?SFN=/dpm/sc.chula.ac.th/home/cms/store/unmerged/SAM/testSRM/SAM-cms-se.sc.chula.ac.th/lcg-util",
                     'grid71.phy.ncu.edu.tw': "srm://grid71.phy.ncu.edu.tw:8446/srm/managerv2?SFN=/dpm/phy.ncu.edu.tw/home/cms/store/unmerged/SAM/testSRM/SAM-grid71.phy.ncu.edu.tw/lcg-util",
                     'ntugrid6.phys.ntu.edu.tw': "srm://ntugrid6.phys.ntu.edu.tw:8446/srm/managerv2?SFN=/dpm/phys.ntu.edu.tw/home/cms/store/unmerged/SAM/testSRM/SAM-ntugrid6.phys.ntu.edu.tw/lcg-util",
                     'kodiak-se.baylor.edu': "gsiftp://kodiak-se.baylor.edu//cms/data/store/unmerged/SAM/testSRM/SAM-kodiak-se.baylor.edu/lcg-util",
                     'brux11.hep.brown.edu': "gsiftp://brux11.hep.brown.edu/mnt/hadoop/store/unmerged/SAM/testSRM/SAM-brux11.hep.brown.edu/lcg-util",
                     'cmsdata.phys.cmu.edu': "gsiftp://cmsdata.phys.cmu.edu//export/data/store/unmerged/SAM/testSRM/SAM-cmsdata.phys.cmu.edu/lcg-util",
                     'gridftp-hadoop.colorado.edu': "gsiftp://gridftp-hadoop.colorado.edu/mnt/hadoop/store/unmerged/SAM/testSRM/SAM-gridftp-hadoop.colorado.edu/lcg-util",
                     'uscms1-se.fltech-grid3.fit.edu': "srm://uscms1-se.fltech-grid3.fit.edu:8443/srm/v2/server?SFN=/mnt/nas1/store/unmerged/SAM/testSRM/SAM-uscms1-se.fltech-grid3.fit.edu/lcg-util",
                     'cmseos-gridftp.fnal.gov': "gsiftp://cmseos-gridftp.fnal.gov//eos/uscms/store/unmerged/SAM/testSRM/SAM-cmseos-gridftp.fnal.gov/lcg-util",
                     'hepcloud-poc.storage.googleapis.com': "s3://hepcloud-poc.storage.googleapis.com/store/unmerged/SAM/testSRM/SAM-hepcloud-poc.storage.googleapis.com/lcg-util",
                     't3serv010.mit.edu': "gsiftp://t3serv010.mit.edu:2811//cms/store/unmerged/SAM/testSRM/SAM-t3serv010.mit.edu/lcg-util",
                     'gc1-se.spa.umn.edu': "srm://gc1-se.spa.umn.edu:8443/srm/v2/server?SFN=/hdfs/cms/phedex/store/unmerged/SAM/testSRM/SAM-gc1-se.spa.umn.edu/lcg-util",
                     'deepthought.crc.nd.edu': "gsiftp://deepthought.crc.nd.edu/store/unmerged/SAM/testSRM/SAM-deepthought.crc.nd.edu/lcg-util",
                     'cms-0.mps.ohio-state.edu': "srm://cms-0.mps.ohio-state.edu:8443/srm/v2/server?SFN=/mnt/hadoop/se/store/unmerged/SAM/testSRM/SAM-cms-0.mps.ohio-state.edu/lcg-util",
                     'cms-se.hep.uprm.edu': "gsiftp://cms-se.hep.uprm.edu//data/store/unmerged/SAM/testSRM/SAM-cms-se.hep.uprm.edu/lcg-util",
                     'bonner07.rice.edu': "gsiftp://bonner07.rice.edu/cms/osg/stage_out/store/unmerged/SAM/testSRM/SAM-bonner07.rice.edu/lcg-util",
                     'ruhex-osgce.rutgers.edu': "gsiftp://ruhex-osgce.rutgers.edu/cms/se/phedex/store/unmerged/SAM/testSRM/SAM-ruhex-osgce.rutgers.edu/lcg-util",
                     'gw01.brazos.tamu.edu': "gsiftp://gw01.brazos.tamu.edu/cms/store/unmerged/SAM/testSRM/SAM-gw01.brazos.tamu.edu/lcg-util",
                     'sigmorgh.hpcc.ttu.edu': "srm://sigmorgh.hpcc.ttu.edu:49443/srm/v2/server?SFN=/lustre/hep/cms/buffer/store/unmerged/SAM/testSRM/SAM-sigmorgh.hpcc.ttu.edu/lcg-util",
                     'charm.ucr.edu': "srm://charm.ucr.edu:10443/srm/v2/server?SFN=/mnt/hadoop/cms/store/unmerged/SAM/testSRM/SAM-charm.ucr.edu/lcg-util",
                     'hepcms-gridftp.umd.edu': "gsiftp://hepcms-gridftp.umd.edu//mnt/hadoop/cms/store/unmerged/SAM/testSRM/SAM-hepcms-gridftp.umd.edu/lcg-util",
                     'umiss005.hep.olemiss.edu': "gsiftp://umiss005.hep.olemiss.edu/osgremote/osg_data/cms/store/unmerged/SAM/testSRM/SAM-umiss005.hep.olemiss.edu/lcg-util",
                     'osg-hep.phys.virginia.edu': "srm://osg-hep.phys.virginia.edu:18443/srm/v2/server?SFN=//raids/phedex3/unmerged/SAM/testSRM/SAM-osg-hep.phys.virginia.edu/lcg-util",
                     'se11.accre.vanderbilt.edu': "gsiftp://se11.accre.vanderbilt.edu:2812/store/unmerged/SAM/testSRM/SAM-se11.accre.vanderbilt.edu/lcg-util" }

        outputList = {}
        # LFN path for file to test transfers
        self.printd('The LFN used for testing will be in: '+testLFN)
        if ( testLFN != "/store/unmerged/SAM/testSRM" ):
            self.printd("ERROR: LFN did not match pre-configured LFN")

        nodeName = self.hostName
        try:
            pfn = PFNTable[nodeName]
        except KeyError:
            self.printd("WARNING: \"" + nodeName + "\" not in PFN table")
            return ('UNKNOWN', "WARNING: \"" + nodeName + "\" not in PFN table")
        self.printd("LFN was matched to PFN "+pfn)
        #
        spacetoken = None
        spacetokendesc="nospacetoken"
        self.printd("No space token defined")

        if re.compile("^srm://.+srm/managerv2\?SFN=.+$").match(pfn) or re.compile("^srm://.+srm/v2/server\?SFN=.+$").match(pfn):
            pfntonode=re.sub(":.+$","",re.sub("^srm://","",pfn))
            if pfntonode != nodeName :
                self.printd("WARNING: the resulting PFN matches to SRM "+pfntonode+" instead of SRM "+nodeName)
            else:
                fntemp = self._fileSRMPattern % (spacetokendesc, '%s', '%s')
                fn = fntemp % (str(int(time.time())), samutils.uuidstr())
                outputList[pfn] = {'fntemp': fntemp, 'fn': fn, 'space_token': spacetoken, 'space_token_get': spacetoken, 'userspace' : testLFN}
        elif pfn.startswith("gsiftp://"):
            pfntonode = urlparse.urlparse(pfn).hostname
            fntemp = self._fileSRMPattern % (spacetokendesc,'%s','%s')
            fn = fntemp % (str(int(time.time())), samutils.uuidstr())
            outputList[pfn]={'fntemp' : fntemp, 'fn': fn, 'space_token': spacetoken, 'space_token_get': spacetoken, 'userspace' : testLFN}
        else:
            self.printd("WARNING: Invalid matching to srmv2 protocol")
            self.printd("Note: this test currently supports only PFNs in the known srmv2 full endpoint formats:")
            self.printd("srm://hostname:port/srm/managerv2?SFN=sitefilename")
            self.printd("or")
            self.printd("srm://hostname:port/srm/v2/server?SFN=sitefilename")
            self.printd("or")
            self.printd("gsiftp://hostname:port/sitefilename")
            return ('OK', "WARNING: Invalid matching to srmv2 protocol")

        self._voInfoDictionary = outputList

        for outputPfns in outputList:
            self.printd("The PFN path used for testing will be:")
            self.printd(outputPfns+" : "+str(outputList[outputPfns]))
            
        self.printd('Saving endpoints to %s' % self._fileVoInfoDictionary, v=2)
        self.printd('Test results will be saved to %s' % self._fileHistoryVoInfoDictionary, v=2)

        try:
            self.saveVoInfoDictionary(self._fileVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileVoInfoDictionary)
        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary history to file %s' % self._fileHistoryVoInfoDictionary)

        return ('OK', "Got PFN and Space Token from PFN-Table Service")

Andrea Sciaba's avatar
Andrea Sciaba committed
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
    def metricGetATLASInfo(self):
        """Get full SRM endpoint(s) and storage areas from ToACache.
        """
        agis_file="/afs/cern.ch/user/d/digirola/public/nagios_atlas/project/src/SRM/org.atlas/src/ToA_srm2_list"
        agis=open(agis_file, 'r')
        agis_endpoint_info=[]
        for entry in agis:
          if entry.find(self.hostName) != -1:
            #print entry
            agis_endpoint_info.append(entry[:-1])
            spacetokendesc=entry.split()[1]
            fn = self._fileSRMPattern % (spacetokendesc,str(int(time.time())),
                                                     samutils.uuidstr())
            if spacetokendesc in ('ATLASDATADISK','ATLASMCDISK','ATLASGROUPDISK'):
              criticality=1
            else: 
              criticality=0
            #endpoint (spacetoken) criticality
            agis_endpoint_details = {
              'fn': fn, 
              'space_token': spacetokendesc,
              'criticality': criticality,
            }
            self._voInfoDictionary[entry.split()[0]+'SAM']=agis_endpoint_details

        #print agis_endpoint_info
        self.printd(str(agis_endpoint_info))
        self.printd(str(self._voInfoDictionary))
        try:
740
741
742
743
744
745
746
747
748
749
750
            fp = open(self._ldap_fileEndptSAPath, "w")
            for info in agis_endpoint_info:
                ep = info.split()[0] + '\n'
                fp.write(ep)
            fp.close()
        except IOError as e:
            try:
                os.unlink(self._ldap_fileEndptSAPath)
            except OSError:
                pass
            return ('UNKNOWN', 'IOError: %s' % str(e))
Andrea Sciaba's avatar
Andrea Sciaba committed
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

 
        #print self._ldap_fileEndptSAPath
        return ('OK',"Endpoint informations found in ToA cached file ")

    def metricGetLHCbInfo(self):
        """Get full SRM endpoint(s) and storage areas from ToACache.
        """
        dirac_file="/afs/cern.ch/user/s/santinel/public/www/ATP/ToA_srm2_list"
        dirac=open(dirac_file, 'r')
        dirac_endpoint_info=[]
        for entry in dirac:
          if entry.find(self.hostName) != -1:
            #print entry
            dirac_endpoint_info.append(entry[:-1])
            spacetokendesc=entry.split()[1]
            fn = self._fileSRMPattern % (spacetokendesc,str(int(time.time())),
                                                     samutils.uuidstr())
            if spacetokendesc in ('LHCb_USER','LHCb_M-DST','LHCb_RAW'):
              criticality=1
            else:
              criticality=0
            #endpoint (spacetoken) criticality
            dirac_endpoint_details = {
              'fn': fn,
              'space_token': spacetokendesc,
              'criticality': criticality,
            }
            self._voInfoDictionary[entry.split()[0]+'/SAM']=dirac_endpoint_details

        #print dirac_endpoint_info
        self.printd(str(dirac_endpoint_info))
        self.printd(str(self._voInfoDictionary))
        try:
          fp = open(self._ldap_fileEndptSAPath, "w")
          for info in dirac_endpoint_info:
            ep=info.split()[0]+'\n'
            fp.write(ep)
          fp.close()
790
        except IOError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
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
          try:
            os.unlink(self._ldap_fileEndptSAPath)
          except OSError: pass
          return ('UNKNOWN', 'IOError: %s' % str(e))

        #print self._ldap_fileEndptSAPath
        return ('OK',"Endpoint informations found in ToA cached file ")

    def metricVOLsDir(self):
        "List content of VO's top level space area(s) in SRM using gfal2.listdir()."

        status = 'OK'
        summary = ''
        self.printd(self.gfal2_ver)
        
        srms = self._voInfoDictionary.keys()

        req = {'surls'          : srms,
               'timeout'        : self._timeouts['srm_connect'],
               }
        self.printd('Using gfal2 listdir().')
        self.printd('Parameters:\n%s' % '\n'.join(
                        ['  %s: %s' % (x,str(y)) for x,y in req.items()]))

	# Instantiate gfal2
816
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
817
818
819
820
821
822
823
824
825
826
827
828
829

        self.print_time()
        self.printd('Listing storage url(s).')

        for surl in req['surls']:
            summary += 'Storage Path[%s]' % surl
            self.printd('Storage Path[%s]' % surl, cr=False)
            try:
                self.print_time()
                # FIXME: Set timeout?
                ctx.listdir(surl)
                summary += '-ok;'
                self.printd('-ok;')
830
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
831
832
833
834
835
836
837
838
839
840
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    if status != 'CRITICAL':
                        status = er[0][2]
                    summary += '-%s [ErrDB:%s];' % (status.lower(), str(er))
                else:
                    status = 'CRITICAL'
                    summary += '-%s;' % status.lower()
                self.printd('-%s;\nERROR: %s\n' % (status.lower(), e.message))
841
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
842
843
844
845
846
847
                return ('UNKNOWN', 'problem invoking gfal2 listdir(): %s:%s' % (str(e), sys.exc_info()[0]))

        return (status, summary)

    def metricVOPut(self):
        "Copy a local file to the SRM into space area(s) defined by VO."
848
849
850

        def event_callback(event):
            self.printd("[%s] %s %s %s" % (event.timestamp, event.domain, event.stage, event.description))
Andrea Sciaba's avatar
Andrea Sciaba committed
851
        
852

Andrea Sciaba's avatar
Andrea Sciaba committed
853
854
855
856
857
858
859
860
861
        self.printd(self.gfal2_ver)
        
        # generate source file
        try:
            src_filename = self._fileTest
            fp = open(src_filename, "w")
            for s in "1234567890": fp.write(s+'\n')
            fp.close()
            src_file = 'file://' + src_filename
862
        except IOError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
863
864
865
866
            self.printd('ERROR: %s' % str(e))
            return ('UNKNOWN', 'Error opening local file.')

	# Instantiate gfal2
867
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
868
869
870
871

        for srmendpt in self._voInfoDictionary.keys():
            # Set transfer parameters
            params = ctx.transfer_parameters()
872
            params.create_parent = True
Andrea Sciaba's avatar
Andrea Sciaba committed
873
            params.timeout = self._timeouts['srm_connect']
874
            params.event_callback = event_callback
Andrea Sciaba's avatar
Andrea Sciaba committed
875
876

            if self._voInfoDictionary[srmendpt].get('space_token', None):
877
                params.dst_spacetoken = self._voInfoDictionary[srmendpt]['space_token']
Andrea Sciaba's avatar
Andrea Sciaba committed
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

            dest_filename=(self._voInfoDictionary[srmendpt])['fn']
            dest_file=srmendpt+'/'+dest_filename

            self.printd('VOPut: Copy file using gfal.filecopy().')

            self.printd('''Parameters:
 source: %s
 dest: %s
 src_spacetoken: %s
 dst_spacetoken: %s
 timeout: %s''' % (src_file, dest_file, params.src_spacetoken,
                   params.dst_spacetoken, params.timeout))

            start_transfer = datetime.datetime.now()
            self.printd('StartTime of the transfer: %s' % str(start_transfer)) 

            stMsg = 'File was%s copied to SRM.'

            try:
                ctx.filecopy(params, src_file, dest_file)
                status = 'OK'
                total_transfer = datetime.datetime.now()-start_transfer
                self.printd('Transfer Duration: %s' % str(total_transfer))
                summary = stMsg % ''+ " Transfer time: "+str(total_transfer)
903
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
904
905
906
907
908
909
910
911
912
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    status = er[0][2]
                    summary = stMsg % (' NOT')+' [ErrDB:%s]' % str(er)
                else:
                    status = 'CRITICAL'
                    summary = stMsg % ' NOT'
                self.printd('ERROR: %s' % str(e))
913
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
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
                status = 'UNKNOWN'
                summary = stMsg % ' NOT'
                self.printd('ERROR: %s:%s' % (str(e), sys.exc_info()[0]))

            (self._voInfoDictionary[srmendpt])['putResult']=(status,summary)

        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileHistoryVoInfoDictionary)

        # weightedResult will return a tuple with nagiosexitcode and detailed output
        weightedResult=self.weightEndpointCriticality('putResult')
        return weightedResult
         ## what if no srmendpt?
        
    def metricVOLs(self):
        "Stat (previously copied) file(s) on the SRM."
        
        self.printd(self.gfal2_ver)
        
        status = 'OK'
        
        srms = []

        for srmendpt in self._voInfoDictionary.keys():
            dest_filename=(self._voInfoDictionary[srmendpt])['fn']
            dest_file=srmendpt+'/'+dest_filename
            srms.append(dest_file)

        self.print_time()
            
        req = {'surls'          : srms,
               'timeout'        : self._timeouts['srm_connect'],
               }
        self.printd('Using gfal2.stat().')
        self.printd('Parameters:\n%s' % '\n'.join(
                        ['  %s: %s' % (x,str(y)) for x,y in req.items()]))
        self.print_time()
        self.printd('Stating file(s).')
        errmsg = ''

	# Instantiate gfal2
957
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
958
959
960

        summary = ''
        for surl in req['surls']:
Andrea Sciaba's avatar
Andrea Sciaba committed
961
#            summary += 'listing [%s]' % surl
Andrea Sciaba's avatar
Andrea Sciaba committed
962
963
964
965
966
967
968
            self.printd('listing [%s]' % surl)
            try:
                # FIXME: Set timeout?
                statp = ctx.stat(surl)
                self.printd("stat: " + str(statp).replace('\n', ', '))
                summary += '-ok;'
                self.printd('-ok;')
969
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
970
971
972
973
974
975
976
977
978
979
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    if status != 'CRITICAL':
                        status = er[0][2]
                    summary += '-%s [ErrDB:%s];' % (status.lower(), str(er))
                else:
                    status = 'CRITICAL'
                    summary += '-%s;' % status.lower()
                self.printd('-%s;\nERROR: %s\n' % (status.lower(), e.message))
980
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
981
982
983
984
985
986
987
988
989
990
                return ('UNKNOWN', 'problem invoking gfal2 stat(): %s:%s' % (str(e), sys.exc_info()[0]))

        return (status, summary)

    def metricVOGetTURLs(self):
        "Get Transport URLs for the file copied to storage."

        self.printd(self.gfal2_ver)

	# Instantiate gfal2
991
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013

        for srmendpt in self._voInfoDictionary.keys():
                        
            self.print_time()
            src_filename=(self._voInfoDictionary[srmendpt])['fn']
            src_file=srmendpt+'/'+src_filename

            status = 'OK'
            summary = ''
            self.printd('=====\nSURL: %s\n-----' % src_file)
            self.print_time()
            protocol = 'gsiftp'
            try:
                if urlparse.urlparse(src_file).scheme == 'gsiftp':
                    # If protocol is gsiftp, it's already a transport URL
                    replicas = src_file
                else:
                    # FIXME: Set timeout?
                    replicas = ctx.getxattr(src_file, 'user.replicas')
                self.printd('proto: %s - OK' % protocol)
                self.printd('replicas: %s' % replicas)
                summary = 'protocol OK-[%s]' % protocol
1014
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
                self.printd('proto: %s - FAILED' % protocol)
                self.printd('error: %s' % e.message)
                summary = 'protocol FAILED-[%s]' % protocol
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    status = er[0][2]
                else:
                    status = 'CRITICAL'
1024
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
                status = 'UNKNOWN'
                self.printd('ERROR: %s\n%s' % (str(e), sys.exc_info()[0]))

            self.print_time()
            self.printd('=====')

            (self._voInfoDictionary[srmendpt])['getTURLResult']=(status,summary)

        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileHistoryVoInfoDictionary)

        #EXTRACT ARIBITRARY ITEM FROM THE DICTIONARY TO RETURN RESULTS
        #REPLACE WITH WEIGHTED CALCULATION BASED ON CRITICALITY OF PATHS/ENDPOINTS!!!

        try:
            return (self._voInfoDictionary.values()[0])['getTURLResult']
        except IndexError:
            return ('UNKNOWN', 'No SRM endpoints found in internal dictionary')
        except KeyError:
            return ('UNKNOWN', 'No test results found in internal dictionary for SRM endpoint')
        
    def metricVOGet(self):
        "Copy given remote file(s) from SRM to a local file."

1051
1052
1053
        def event_callback(event):
            self.printd("[%s] %s %s %s" % (event.timestamp, event.domain, event.stage, event.description))

Andrea Sciaba's avatar
Andrea Sciaba committed
1054
1055
1056
        self.printd(self.gfal2_ver)

	# Instantiate gfal2
1057
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072

        for srmendpt in self._voInfoDictionary.keys():

            self.print_time()
            src_filename=(self._voInfoDictionary[srmendpt])['fn']
            src_file=srmendpt+'/'+src_filename

            dest_file = 'file://'+self._fileTestIn

            self.printd('Source: %s' % src_file)
            self.printd('Destination: %s' % dest_file)

            # Set transfer parameters
            params = ctx.transfer_parameters()
            params.timeout = self._timeouts['srm_connect']
1073
            params.event_callback = event_callback
Andrea Sciaba's avatar
Andrea Sciaba committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
            if self._voInfoDictionary[srmendpt].get('space_token_get', None):
                params.src_spacetoken = self._voInfoDictionary[srmendpt]['space_token_get']
            params.overwrite = True

            self.printd('Get file using gfal.filecopy().')

            self.printd('''Parameters:
 source: %s
 dest: %s
 src_spacetoken: %s
 dst_spacetoken: %s
 timeout: %s''' % (src_file, dest_file, params.src_spacetoken,
                   params.dst_spacetoken, params.timeout))

            stMsg = 'File was%s copied from SRM.'
            errmsg = ''
            start_transfer = datetime.datetime.now()
            self.printd('StartTime of the transfer: %s' % str(start_transfer))

            try:
                ctx.filecopy(params, src_file, dest_file)
                if filecmp.cmp(self._fileTest, self._fileTestIn):
                    # Files match
                    status = 'OK'
                    total_transfer = datetime.datetime.now()-start_transfer
                    self.printd('Transfer Duration: %s' % str(total_transfer))
                    summary = stMsg % ('')+' Diff successful.' + " Transfer time: "+str(total_transfer)
                else:
                    # Files do not match
                    status = 'CRITICAL'
                    summary = stMsg % ('')+' Files differ!'
                    self.printd('Files differ!')
1106
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    status = er[0][2]
                    summary = stMsg % (' NOT')+' [ErrDB:%s]' % str(er)
                else:
                    status = 'CRITICAL'
                    summary = stMsg % ' NOT'
                self.printd('ERROR: %s' % str(e))
1116
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
                status = 'UNKNOWN'
                summary = stMsg % ' NOT'
                self.printd('ERROR: %s:%s' % (str(e), sys.exc_info()[0]))

            self.print_time()
            (self._voInfoDictionary[srmendpt])['getResult']=(status,summary)

        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileHistoryVoInfoDictionary)

        # GET WEIGHTED CALCULATION BASED ON CRITICALITY OF PATHS/ENDPOINTS

        weightedResult=self.weightEndpointCriticality('getResult')
        return weightedResult

    def metricVODel(self):
        "Delete given file(s) from SRM."
        
        self.printd(self.gfal2_ver)
        
        # TODO: - cleanup of the metric's working directory 
        #   (this may go to metricAll() in the superclass)

	# Instantiate gfal2
1143
        ctx = gfal2.creat_context()
Andrea Sciaba's avatar
Andrea Sciaba committed
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162

        for srmendpt in self._voInfoDictionary.keys():

            self.print_time()
            src_filename=(self._voInfoDictionary[srmendpt])['fn']
            src_file=srmendpt+'/'+src_filename

            self.printd('Source: %s' % src_file)
            self.printd('Using gfal2.unlink().')
        
            stMsg = 'File was%s deleted from SRM.'
            errmsg = ''
            self.print_time()
            self.printd('Deleting: %s' % src_file)
            try:
                # FIXME: Set timeout?
                ctx.unlink(src_file)
                status = 'OK'
                summary = stMsg % ''
1163
            except gfal2.GError as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1164
1165
1166
1167
1168
1169
1170
1171
                summary = stMsg % ' NOT'
                em = probe.ErrorsMatching(self.errorDBFile, self.errorTopics)
                er = em.match(e.message)
                if er:
                    status = er[0][2]
                else:
                    status = 'CRITICAL'
                self.printd('ERROR: %s:%s' % (str(e),sys.exc_info()[0]))
1172
            except Exception as e:
Andrea Sciaba's avatar
Andrea Sciaba committed
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
                status = 'UNKNOWN'
                summary = stMsg % ' NOT'
                self.printd('ERROR: %s:%s' % (str(e),sys.exc_info()[0]))

            self.print_time()
            (self._voInfoDictionary[srmendpt])['delResult']=(status,summary)

        try:
            self.saveVoInfoDictionary(self._fileHistoryVoInfoDictionary)
        except IOError:
            self.printd('Error saving VO Info Dictionary to file %s' % self._fileHistoryVoInfoDictionary)

        #Remove lock on workdir
        self.__workdir_unlock()

        #EXTRACT ARIBITRARY ITEM FROM THE DICTIONARY TO RETURN RESULTS
        #REPLACE WITH WEIGHTED CALCULATION BASED ON CRITICALITY OF PATHS/ENDPOINTS!!!

        try:
            return (self._voInfoDictionary.values()[0])['delResult']
        except IndexError:
            return ('UNKNOWN', 'No SRM endpoints found in internal dictionary')
        except KeyError:
            return ('UNKNOWN', 'No test results found in internal dictionary for SRM endpoint')
            
runner = probe.Runner(SRMVOMetrics, probe.ProbeFormatRenderer())
sys.exit(runner.run(sys.argv))