From f5c9c73e85412dd7afb2f5c094949d768b5eb159 Mon Sep 17 00:00:00 2001 From: Christophe Haen Date: Thu, 11 Jun 2020 18:11:45 +0200 Subject: [PATCH 01/24] M2: close the socket after dereferencing the Connection instance --- .../private/Transports/M2SSLTransport.py | 84 +++++++++++++++++-- 1 file changed, 75 insertions(+), 9 deletions(-) diff --git a/Core/DISET/private/Transports/M2SSLTransport.py b/Core/DISET/private/Transports/M2SSLTransport.py index 9def1d7fd63..fde34b9fbb3 100755 --- a/Core/DISET/private/Transports/M2SSLTransport.py +++ b/Core/DISET/private/Transports/M2SSLTransport.py @@ -45,6 +45,9 @@ def __init__(self, *args, **kwargs): as for other transports. If ctx is specified (as an instance of SSL.Context) then use that rather than creating a new context. """ + # The thread init of M2Crypto is not really thread safe. + # So we put it a second time + M2Threading.init() self.remoteAddress = None self.peerCredentials = {} self.__timeout = 1 @@ -98,9 +101,7 @@ def initAsClient(self): error = "%s:%s" % (e, repr(e)) if self.oSocket is not None: - self.oSocket.close() - self.oSocket.socket.close() - self.oSocket = None + self.close() return S_ERROR(error) @@ -125,20 +126,85 @@ def initAsServer(self): return S_OK() def close(self): + # pylint: disable=line-too-long """ Close this socket. """ + if self.oSocket: + # TL;DR: + # Do NOT touch that method + # # Surprisingly (to me at least), M2Crypto does not close - # the socket when calling SSL.Connection.close - # It only does it when the garbage collector kicks in - # We have to manually close it here, otherwise the connections - # will hang forever + # the underlying socket when calling SSL.Connection.close + # It only does it when the garbage collector kicks in (see ~M2Crypto.SSL.Connection.Connection.__del__) + # If the socket is not closed, the connection may hang forever. + # + # Thus, we are setting self.oSocket to None to allow the GC to do the work, but since we are not sure + # that it will run, we anyway force the connection to be closed + # + # However, we should close the underlying socket only after SSL was shutdown properly. + # This is because OpenSSL `ssl3_shutdown` (see callstack below) may still read some data + # (see https://github.com/openssl/openssl/blob/master/ssl/s3_lib.c#L4509):: + # + # + # 1 0x00007fffe9d48fc0 in sock_read () from /lib/libcrypto.so.1.0.0 + # 2 0x00007fffe9d46e83 in BIO_read () from /lib/libcrypto.so.1.0.0 + # 3 0x00007fffe9eab9dd in ssl3_read_n () from /lib/libssl.so.1.0.0 + # 4 0x00007fffe9ead216 in ssl3_read_bytes () from /lib/libssl.so.1.0.0 + # 5 0x00007fffe9ea999c in ssl3_shutdown () from /lib/libssl.so.1.0.0 + # 6 0x00007fffe9ed4f93 in ssl_free () from /lib/libssl.so.1.0.0 + # 7 0x00007fffe9d46d5b in BIO_free () from /lib/libcrypto.so.1.0.0 + # 8 0x00007fffe9f30a96 in bio_free (bio=0x5555556f3200) at SWIG/_m2crypto_wrap.c:5008 + # 9 0x00007fffe9f30b1e in _wrap_bio_free (self=, args=) at SWIG/_m2crypto_wrap.c + # + # We unfortunately have no way to force that order, and there is a risk of deadlock + # when running in a multi threaded environment like the agents:: + # + # Thread A opens socket, gets FD = 111 + # Thread A works on it + # Thread A closes FD 111 (underlying socket.close()) + # Thread B opens socket, gets FD = 111 + # Thread A calls read on FD=111 from ssl3_shutdown + # + # This is illustrated on the strace below:: + # + # 26461 14:25:15.266692 write(111]:42688->[]:9140]>, + # "blabla", 37 + # 26464 14:25:15.266857 <... connect resumed>) = 0 <0.000195> + # 26464 14:25:15.267023 getsockname(120:44252->188.185.84.86:9140]>, + # 26461 14:25:15.267176 <... write resumed>) = 37 <0.000453> + # 26464 14:25:15.267425 <... getsockname resumed>{sa_family=AF_INET, sin_port=htons(44252), + # sin_addr=inet_addr("")}, [28->16]) = 0 <0.000292> + # 26461 14:25:15.267466 close(111]:42688->[]:9140]> + # 26464 14:25:15.267637 close(120:44252->188.185.84.86:9140]> + # 26464 14:25:15.267738 <... close resumed>) = 0 <0.000086> + # 26461 14:25:15.267768 <... close resumed>) = 0 <0.000285> + # 26464 14:25:15.267827 socket(AF_INET6, SOCK_DGRAM|SOCK_CLOEXEC, IPPROTO_IP + # 26461 14:25:15.267888 futex(0x21f8620, FUTEX_WAKE_PRIVATE, 1 + # 26464 14:25:15.267976 <... socket resumed>) = 111 <0.000138> + # 26461 14:25:15.268092 <... futex resumed>) = 1 <0.000196> + # 26464 14:25:15.268195 connect(111, + # {sa_family=AF_INET6, sin6_port=htons(9140), + # inet_pton(AF_INET6, "", &sin6_addr), + # sin6_flowinfo=htonl(0), sin6_scope_id=0 + # }, 28 + # 26461 14:25:15.268294 read(111]:42480->[]:9140]>, + # 26464 14:25:15.268503 <... connect resumed>) = 0 <0.000217> + # 26464 14:25:15.268673 getsockname(111]:42480->[]:9140]>, + # 26464 14:25:15.268862 <... getsockname resumed>{sa_family=AF_INET6, sin6_port=htons(42480), + # inet_pton(AF_INET6, "", &sin6_addr), sin6_flowinfo=htonl(0), sin6_scope_id= + # 0}, [28]) = 0 <0.000168> + # 26464 14:25:15.269048 + # close(111]:42480->[]:9140]> + # + self.oSocket.close() - self.oSocket.socket.close() - # del self.oSocket + underlyingSocket = self.oSocket.socket self.oSocket = None + underlyingSocket.close() return S_OK() def renewServerContext(self): + # pylint: disable=line-too-long """ Renews the server context. This reloads the certificates and re-initialises the SSL context. From d72ae88a5b3911833d492870e9f3227e3559fb61 Mon Sep 17 00:00:00 2001 From: Christophe Haen Date: Fri, 12 Jun 2020 10:59:46 +0200 Subject: [PATCH 02/24] CI: disable coverage in pytest (because Test_PoolCE is too sensitive to timing issues) --- pytest.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pytest.ini b/pytest.ini index 74fb4a3f68c..81dd39cb17f 100644 --- a/pytest.ini +++ b/pytest.ini @@ -5,4 +5,4 @@ python_files=Test_*.py assert*.py # The reason here is that we do nasty things with the pythonpath # in order to make sure that M2Crypto and pyGSI do not step # on each other's feet -addopts = -rx -v --color=yes --showlocals --tb=long --ignore=tests --ignore=Core/Security/test --cov=. --cov-report term-missing +addopts = -rx -v --color=yes --showlocals --tb=long --ignore=tests --ignore=Core/Security/test From e32252be82cbe84b1ab813909a31f9d9f44f05d3 Mon Sep 17 00:00:00 2001 From: Christophe Haen Date: Mon, 15 Jun 2020 10:32:42 +0200 Subject: [PATCH 03/24] RMS/DMS: cancel FTS operations if the matching RMS request does not exist anymore --- DataManagementSystem/Agent/FTS3Agent.py | 38 +- RequestManagementSystem/DB/RequestDB.py | 735 +++++++++++------------- 2 files changed, 375 insertions(+), 398 deletions(-) diff --git a/DataManagementSystem/Agent/FTS3Agent.py b/DataManagementSystem/Agent/FTS3Agent.py index 47fef84be99..1adeaca1eb6 100644 --- a/DataManagementSystem/Agent/FTS3Agent.py +++ b/DataManagementSystem/Agent/FTS3Agent.py @@ -354,24 +354,36 @@ def _treatOperation(self, operation): continueOperationProcessing = True # Check the status of the associated RMS Request. - # If it is canceled then we will not create new FTS3Jobs, and mark + # If it is canceled or does not exist anymore then we will not create new FTS3Jobs, and mark # this as FTS3Operation canceled. if operation.rmsReqID: res = ReqClient().getRequestStatus(operation.rmsReqID) if not res['OK']: - log.error("Could not get request status", res) - return operation, res - rmsReqStatus = res['Value'] - - if rmsReqStatus == 'Canceled': - log.info( - "The RMS Request is canceled, canceling the FTS3Operation", - "rmsReqID: %s, FTS3OperationID: %s" % - (operation.rmsReqID, - operation.operationID)) - operation.status = 'Canceled' - continueOperationProcessing = False + # If the Request does not exist anymore + if cmpError(res, errno.ENOENT): + log.info( + "The RMS Request does not exist anymore, canceling the FTS3Operation", + "rmsReqID: %s, FTS3OperationID: %s" % + (operation.rmsReqID, + operation.operationID)) + operation.status = 'Canceled' + continueOperationProcessing = False + else: + log.error("Could not get request status", res) + return operation, res + + else: + rmsReqStatus = res['Value'] + + if rmsReqStatus == 'Canceled': + log.info( + "The RMS Request is canceled, canceling the FTS3Operation", + "rmsReqID: %s, FTS3OperationID: %s" % + (operation.rmsReqID, + operation.operationID)) + operation.status = 'Canceled' + continueOperationProcessing = False if continueOperationProcessing: res = operation.prepareNewJobs( diff --git a/RequestManagementSystem/DB/RequestDB.py b/RequestManagementSystem/DB/RequestDB.py index e84a1a8360c..4f9a9e1b813 100644 --- a/RequestManagementSystem/DB/RequestDB.py +++ b/RequestManagementSystem/DB/RequestDB.py @@ -16,6 +16,7 @@ db holding Request, Operation and File """ +import errno import random import datetime @@ -24,7 +25,7 @@ from sqlalchemy.orm import relationship, backref, sessionmaker, joinedload_all, mapper from sqlalchemy.sql import update from sqlalchemy import create_engine, func, Table, Column, MetaData, ForeignKey, \ - Integer, String, DateTime, Enum, BLOB, BigInteger, distinct + Integer, String, DateTime, Enum, BLOB, BigInteger, distinct # # from DIRAC from DIRAC import S_OK, S_ERROR, gLogger @@ -34,7 +35,6 @@ from DIRAC.ConfigurationSystem.Client.Utilities import getDBParameters - __RCSID__ = "$Id $" @@ -44,234 +44,225 @@ # Description of the file table -fileTable = Table( 'File', metadata, - Column( 'FileID', Integer, primary_key = True ), - Column( 'OperationID', Integer, - ForeignKey( 'Operation.OperationID', ondelete = 'CASCADE' ), - nullable = False ), - Column( 'Status', Enum( 'Waiting', 'Done', 'Failed', 'Scheduled' ), server_default = 'Waiting' ), - Column( 'LFN', String( 255 ), index = True ), - Column( 'PFN', String( 255 ) ), - Column( 'ChecksumType', Enum( 'ADLER32', 'MD5', 'SHA1', '' ), server_default = '' ), - Column( 'Checksum', String( 255 ) ), - Column( 'GUID', String( 36 ) ), - Column( 'Size', BigInteger ), - Column( 'Attempt', Integer ), - Column( 'Error', String( 255 ) ), - mysql_engine = 'InnoDB' ) +fileTable = Table('File', metadata, + Column('FileID', Integer, primary_key=True), + Column('OperationID', Integer, + ForeignKey('Operation.OperationID', ondelete='CASCADE'), + nullable=False), + Column('Status', Enum('Waiting', 'Done', 'Failed', 'Scheduled'), server_default='Waiting'), + Column('LFN', String(255), index=True), + Column('PFN', String(255)), + Column('ChecksumType', Enum('ADLER32', 'MD5', 'SHA1', ''), server_default=''), + Column('Checksum', String(255)), + Column('GUID', String(36)), + Column('Size', BigInteger), + Column('Attempt', Integer), + Column('Error', String(255)), + mysql_engine='InnoDB') # Map the File object to the fileTable, with a few special attributes -mapper( File, fileTable, properties = {'_Status': fileTable.c.Status, - '_LFN': fileTable.c.LFN, - '_ChecksumType' : fileTable.c.ChecksumType, - '_GUID' : fileTable.c.GUID} ) +mapper(File, fileTable, properties={'_Status': fileTable.c.Status, + '_LFN': fileTable.c.LFN, + '_ChecksumType': fileTable.c.ChecksumType, + '_GUID': fileTable.c.GUID}) # Description of the Operation table -operationTable = Table( 'Operation', metadata, - Column( 'TargetSE', String( 255 ) ), - Column( 'CreationTime', DateTime ), - Column( 'SourceSE', String( 255 ) ), - Column( 'Arguments', BLOB ), - Column( 'Error', String( 255 ) ), - Column( 'Type', String( 64 ), nullable = False ), - Column( 'Order', Integer, nullable = False ), - Column( 'Status', - Enum( 'Waiting', 'Assigned', 'Queued', 'Done', 'Failed', 'Canceled', 'Scheduled' ), - server_default = 'Queued' ), - Column( 'LastUpdate', DateTime ), - Column( 'SubmitTime', DateTime ), - Column( 'Catalog', String( 255 ) ), - Column( 'OperationID', Integer, primary_key = True ), - Column( 'RequestID', Integer, - ForeignKey( 'Request.RequestID', ondelete = 'CASCADE' ), - nullable = False ), - mysql_engine = 'InnoDB' ) +operationTable = Table('Operation', metadata, + Column('TargetSE', String(255)), + Column('CreationTime', DateTime), + Column('SourceSE', String(255)), + Column('Arguments', BLOB), + Column('Error', String(255)), + Column('Type', String(64), nullable=False), + Column('Order', Integer, nullable=False), + Column('Status', + Enum('Waiting', 'Assigned', 'Queued', 'Done', 'Failed', 'Canceled', 'Scheduled'), + server_default='Queued'), + Column('LastUpdate', DateTime), + Column('SubmitTime', DateTime), + Column('Catalog', String(255)), + Column('OperationID', Integer, primary_key=True), + Column('RequestID', Integer, + ForeignKey('Request.RequestID', ondelete='CASCADE'), + nullable=False), + mysql_engine='InnoDB') # Map the Operation object to the operationTable, with a few special attributes -mapper( Operation, operationTable, properties = {'_CreationTime': operationTable.c.CreationTime, - '_Order': operationTable.c.Order, - '_Status': operationTable.c.Status, - '_LastUpdate': operationTable.c.LastUpdate, - '_SubmitTime': operationTable.c.SubmitTime, - '_Catalog': operationTable.c.Catalog, - '__files__':relationship( File, - backref = backref( '_parent', lazy = 'immediate' ), - lazy = 'immediate', - passive_deletes = True, - cascade = "all, delete-orphan" )} ) +mapper(Operation, operationTable, properties={'_CreationTime': operationTable.c.CreationTime, + '_Order': operationTable.c.Order, + '_Status': operationTable.c.Status, + '_LastUpdate': operationTable.c.LastUpdate, + '_SubmitTime': operationTable.c.SubmitTime, + '_Catalog': operationTable.c.Catalog, + '__files__': relationship(File, + backref=backref('_parent', lazy='immediate'), + lazy='immediate', + passive_deletes=True, + cascade="all, delete-orphan")}) # Description of the Request Table -requestTable = Table( 'Request', metadata, - Column( 'DIRACSetup', String( 32 ) ), - Column( 'CreationTime', DateTime ), - Column( 'JobID', Integer, server_default = '0' ), - Column( 'OwnerDN', String( 255 ) ), - Column( 'RequestName', String( 255 ), nullable = False ), - Column( 'Error', String( 255 ) ), - Column( 'Status', - Enum( 'Waiting', 'Assigned', 'Done', 'Failed', 'Canceled', 'Scheduled' ), - server_default = 'Waiting' ), - Column( 'LastUpdate', DateTime ), - Column( 'OwnerGroup', String( 32 ) ), - Column( 'SubmitTime', DateTime ), - Column( 'RequestID', Integer, primary_key = True ), - Column( 'SourceComponent', BLOB ), - Column( 'NotBefore', DateTime ), - mysql_engine = 'InnoDB' ) +requestTable = Table('Request', metadata, + Column('DIRACSetup', String(32)), + Column('CreationTime', DateTime), + Column('JobID', Integer, server_default='0'), + Column('OwnerDN', String(255)), + Column('RequestName', String(255), nullable=False), + Column('Error', String(255)), + Column('Status', + Enum('Waiting', 'Assigned', 'Done', 'Failed', 'Canceled', 'Scheduled'), + server_default='Waiting'), + Column('LastUpdate', DateTime), + Column('OwnerGroup', String(32)), + Column('SubmitTime', DateTime), + Column('RequestID', Integer, primary_key=True), + Column('SourceComponent', BLOB), + Column('NotBefore', DateTime), + mysql_engine='InnoDB') # Map the Request object to the requestTable, with a few special attributes -mapper( Request, requestTable, properties = {'_CreationTime': requestTable.c.CreationTime, - '_Status': requestTable.c.Status, - '_LastUpdate': requestTable.c.LastUpdate, - '_SubmitTime': requestTable.c.SubmitTime, - '_NotBefore': requestTable.c.NotBefore, - '__operations__' : relationship( Operation, - backref = backref( '_parent', - lazy = 'immediate' ), - order_by = operationTable.c.Order, - lazy = 'immediate', - passive_deletes = True, - cascade = "all, delete-orphan" )} ) - +mapper(Request, requestTable, properties={'_CreationTime': requestTable.c.CreationTime, + '_Status': requestTable.c.Status, + '_LastUpdate': requestTable.c.LastUpdate, + '_SubmitTime': requestTable.c.SubmitTime, + '_NotBefore': requestTable.c.NotBefore, + '__operations__': relationship(Operation, + backref=backref('_parent', + lazy='immediate'), + order_by=operationTable.c.Order, + lazy='immediate', + passive_deletes=True, + cascade="all, delete-orphan")}) ######################################################################## -class RequestDB( object ): +class RequestDB(object): """ .. class:: RequestDB db holding requests """ - - def __getDBConnectionInfo( self, fullname ): + def __getDBConnectionInfo(self, fullname): """ Collect from the CS all the info needed to connect to the DB. This should be in a base class eventually """ - result = getDBParameters( fullname ) - if not result[ 'OK' ]: - raise Exception( 'Cannot get database parameters: %s' % result[ 'Message' ] ) + result = getDBParameters(fullname) + if not result['OK']: + raise Exception('Cannot get database parameters: %s' % result['Message']) - dbParameters = result[ 'Value' ] - self.dbHost = dbParameters[ 'Host' ] - self.dbPort = dbParameters[ 'Port' ] - self.dbUser = dbParameters[ 'User' ] - self.dbPass = dbParameters[ 'Password' ] - self.dbName = dbParameters[ 'DBName' ] + dbParameters = result['Value'] + self.dbHost = dbParameters['Host'] + self.dbPort = dbParameters['Port'] + self.dbUser = dbParameters['User'] + self.dbPass = dbParameters['Password'] + self.dbName = dbParameters['DBName'] - - def __init__( self ): + def __init__(self): """c'tor :param self: self reference """ - self.log = gLogger.getSubLogger( 'RequestDB' ) + self.log = gLogger.getSubLogger('RequestDB') # Initialize the connection info - self.__getDBConnectionInfo( 'RequestManagement/ReqDB' ) - - + self.__getDBConnectionInfo('RequestManagement/ReqDB') - runDebug = ( gLogger.getLevel() == 'DEBUG' ) + runDebug = (gLogger.getLevel() == 'DEBUG') self.engine = create_engine('mysql://%s:%s@%s:%s/%s' % (self.dbUser, self.dbPass, self.dbHost, self.dbPort, self.dbName), echo=runDebug, pool_recycle=3600) metadata.bind = self.engine - self.DBSession = sessionmaker( bind = self.engine ) + self.DBSession = sessionmaker(bind=self.engine) - - def createTables( self ): + def createTables(self): """ create tables """ try: - metadata.create_all( self.engine ) + metadata.create_all(self.engine) except Exception as e: - return S_ERROR( e ) + return S_ERROR(e) return S_OK() - - def cancelRequest( self, requestID ): + def cancelRequest(self, requestID): session = self.DBSession() try: - updateRet = session.execute( update( Request )\ - .where( Request.RequestID == requestID )\ - .values( {Request._Status : 'Canceled', - Request._LastUpdate : datetime.datetime.utcnow()\ - .strftime( Request._datetimeFormat )} ) ) + updateRet = session.execute(update(Request) + .where(Request.RequestID == requestID) + .values({Request._Status: 'Canceled', + Request._LastUpdate: datetime.datetime.utcnow() + .strftime(Request._datetimeFormat)})) session.commit() # No row was changed if not updateRet.rowcount: - return S_ERROR( "No such request %s" % requestID ) + return S_ERROR("No such request %s" % requestID) return S_OK() except Exception as e: session.rollback() - self.log.exception( "cancelRequest: unexpected exception", lException = e ) - return S_ERROR( "cancelRequest: unexpected exception %s" % e ) + self.log.exception("cancelRequest: unexpected exception", lException=e) + return S_ERROR("cancelRequest: unexpected exception %s" % e) finally: session.close() - - def putRequest( self, request ): + def putRequest(self, request): """ update or insert request into db :param ~Request.Request request: Request instance """ - session = self.DBSession( expire_on_commit = False ) + session = self.DBSession(expire_on_commit=False) try: try: - if hasattr( request, 'RequestID' ): + if hasattr(request, 'RequestID'): - status = session.query( Request._Status )\ - .filter( Request.RequestID == request.RequestID )\ + status = session.query(Request._Status)\ + .filter(Request.RequestID == request.RequestID)\ .one() if status[0] == 'Canceled': - self.log.info( "Request %s(%s) was canceled, don't put it back" % ( request.RequestID, request.RequestName ) ) - return S_OK( request.RequestID ) + self.log.info("Request %s(%s) was canceled, don't put it back" % (request.RequestID, request.RequestName)) + return S_OK(request.RequestID) - except NoResultFound, e: + except NoResultFound as e: pass # Since the object request is not attached to the session, we merge it to have an update # instead of an insert with duplicate primary key - request = session.merge( request ) - session.add( request ) + request = session.merge(request) + session.add(request) session.commit() session.expunge_all() - return S_OK( request.RequestID ) + return S_OK(request.RequestID) except Exception as e: session.rollback() - self.log.exception( "putRequest: unexpected exception", lException = e ) - return S_ERROR( "putRequest: unexpected exception %s" % e ) + self.log.exception("putRequest: unexpected exception", lException=e) + return S_ERROR("putRequest: unexpected exception %s" % e) finally: session.close() - - def getScheduledRequest( self, operationID ): + def getScheduledRequest(self, operationID): session = self.DBSession() try: - requestID = session.query( Request.RequestID )\ - .join( Request.__operations__ )\ - .filter( Operation.OperationID == operationID )\ - .one() - return self.getRequest( requestID[0] ) + requestID = session.query(Request.RequestID)\ + .join(Request.__operations__)\ + .filter(Operation.OperationID == operationID)\ + .one() + return self.getRequest(requestID[0]) except NoResultFound: return S_OK() finally: @@ -291,9 +282,7 @@ def getScheduledRequest( self, operationID ): # return S_ERROR( "getRequestName: no request found for RequestID=%s" % requestID ) # finally: # session.close() - - - def getRequest( self, reqID = 0, assigned = True ): + def getRequest(self, reqID=0, assigned=True): """ read request for execution :param reqID: request's ID (default 0) If 0, take a pseudo random one @@ -301,8 +290,8 @@ def getRequest( self, reqID = 0, assigned = True ): """ # expire_on_commit is set to False so that we can still use the object after we close the session - session = self.DBSession( expire_on_commit = False ) - log = self.log.getSubLogger( 'getRequest' if assigned else 'peekRequest' ) + session = self.DBSession(expire_on_commit=False) + log = self.log.getSubLogger('getRequest' if assigned else 'peekRequest') requestID = None @@ -311,83 +300,84 @@ def getRequest( self, reqID = 0, assigned = True ): if reqID: requestID = reqID - log.verbose( "selecting request '%s'%s" % ( reqID, ' (Assigned)' if assigned else '' ) ) + log.verbose("selecting request '%s'%s" % (reqID, ' (Assigned)' if assigned else '')) status = None try: - status = session.query( Request._Status )\ - .filter( Request.RequestID == reqID )\ + status = session.query(Request._Status)\ + .filter(Request.RequestID == reqID)\ .one() - except NoResultFound, e: - return S_ERROR( "getRequest: request '%s' not exists" % reqID ) + except NoResultFound as e: + return S_ERROR("getRequest: request '%s' not exists" % reqID) if status and status == "Assigned" and assigned: - return S_ERROR( "getRequest: status of request '%s' is 'Assigned', request cannot be selected" % reqID ) + return S_ERROR("getRequest: status of request '%s' is 'Assigned', request cannot be selected" % reqID) else: - now = datetime.datetime.utcnow().replace( microsecond = 0 ) + now = datetime.datetime.utcnow().replace(microsecond=0) reqIDs = set() try: - reqAscIDs = session.query( Request.RequestID )\ - .filter( Request._Status == 'Waiting' )\ - .filter( Request._NotBefore < now )\ - .order_by( Request._LastUpdate )\ - .limit( 100 )\ + reqAscIDs = session.query(Request.RequestID)\ + .filter(Request._Status == 'Waiting')\ + .filter(Request._NotBefore < now)\ + .order_by(Request._LastUpdate)\ + .limit(100)\ .all() - reqIDs = set( [reqID[0] for reqID in reqAscIDs] ) + reqIDs = set([reqID[0] for reqID in reqAscIDs]) - reqDescIDs = session.query( Request.RequestID )\ - .filter( Request._Status == 'Waiting' )\ - .filter( Request._NotBefore < now )\ - .order_by( Request._LastUpdate.desc() )\ - .limit( 50 )\ + reqDescIDs = session.query(Request.RequestID)\ + .filter(Request._Status == 'Waiting')\ + .filter(Request._NotBefore < now)\ + .order_by(Request._LastUpdate.desc())\ + .limit(50)\ .all() - reqIDs |= set( [reqID[0] for reqID in reqDescIDs] ) + reqIDs |= set([reqID[0] for reqID in reqDescIDs]) # No Waiting requests - except NoResultFound, e: + except NoResultFound as e: return S_OK() if not reqIDs: return S_OK() - reqIDs = list( reqIDs ) - random.shuffle( reqIDs ) + reqIDs = list(reqIDs) + random.shuffle(reqIDs) requestID = reqIDs[0] - # If we are here, the request MUST exist, so no try catch # the joinedload_all is to force the non-lazy loading of all the attributes, especially _parent - request = session.query( Request )\ - .options( joinedload_all( '__operations__.__files__' ) )\ - .filter( Request.RequestID == requestID )\ + request = session.query(Request)\ + .options(joinedload_all('__operations__.__files__'))\ + .filter(Request.RequestID == requestID)\ .one() if not reqID: - log.verbose( "selected request %s('%s')%s" % ( request.RequestID, request.RequestName, ' (Assigned)' if assigned else '' ) ) - + log.verbose( + "selected request %s('%s')%s" % + (request.RequestID, + request.RequestName, + ' (Assigned)' if assigned else '')) if assigned: - session.execute( update( Request )\ - .where( Request.RequestID == requestID )\ - .values( {Request._Status : 'Assigned', - Request._LastUpdate : datetime.datetime.utcnow()\ - .strftime( Request._datetimeFormat )} ) - ) + session.execute(update(Request) + .where(Request.RequestID == requestID) + .values({Request._Status: 'Assigned', + Request._LastUpdate: datetime.datetime.utcnow() + .strftime(Request._datetimeFormat)}) + ) session.commit() session.expunge_all() - return S_OK( request ) + return S_OK(request) except Exception as e: session.rollback() - log.exception( "getRequest: unexpected exception", lException = e ) - return S_ERROR( "getRequest: unexpected exception : %s" % e ) + log.exception("getRequest: unexpected exception", lException=e) + return S_ERROR("getRequest: unexpected exception : %s" % e) finally: session.close() - - def getBulkRequests( self, numberOfRequest = 10, assigned = True ): + def getBulkRequests(self, numberOfRequest=10, assigned=True): """ read as many requests as requested for execution :param int numberOfRequest: Number of Request we want (default 10) @@ -398,8 +388,8 @@ def getBulkRequests( self, numberOfRequest = 10, assigned = True ): """ # expire_on_commit is set to False so that we can still use the object after we close the session - session = self.DBSession( expire_on_commit = False ) - log = self.log.getSubLogger( 'getBulkRequest' if assigned else 'peekBulkRequest' ) + session = self.DBSession(expire_on_commit=False) + log = self.log.getSubLogger('getBulkRequest' if assigned else 'peekBulkRequest') requestDict = {} @@ -407,93 +397,87 @@ def getBulkRequests( self, numberOfRequest = 10, assigned = True ): # If we are here, the request MUST exist, so no try catch # the joinedload_all is to force the non-lazy loading of all the attributes, especially _parent try: - now = datetime.datetime.utcnow().replace( microsecond = 0 ) - requestIDs = session.query( Request.RequestID )\ - .with_for_update()\ - .filter( Request._Status == 'Waiting' )\ - .filter( Request._NotBefore < now )\ - .order_by( Request._LastUpdate )\ - .limit( numberOfRequest )\ - .all() + now = datetime.datetime.utcnow().replace(microsecond=0) + requestIDs = session.query(Request.RequestID)\ + .with_for_update()\ + .filter(Request._Status == 'Waiting')\ + .filter(Request._NotBefore < now)\ + .order_by(Request._LastUpdate)\ + .limit(numberOfRequest)\ + .all() requestIDs = [ridTuple[0] for ridTuple in requestIDs] - log.debug( "Got request ids %s" % requestIDs ) + log.debug("Got request ids %s" % requestIDs) - requests = session.query( Request )\ - .options( joinedload_all( '__operations__.__files__' ) )\ - .filter( Request.RequestID.in_( requestIDs ) )\ + requests = session.query(Request)\ + .options(joinedload_all('__operations__.__files__'))\ + .filter(Request.RequestID.in_(requestIDs))\ .all() - log.debug( "Got %s Request objects " % len( requests ) ) - requestDict = dict( ( req.RequestID, req ) for req in requests ) + log.debug("Got %s Request objects " % len(requests)) + requestDict = dict((req.RequestID, req) for req in requests) # No Waiting requests - except NoResultFound, e: + except NoResultFound as e: pass if assigned and requestDict: - session.execute( update( Request )\ - .where( Request.RequestID.in_( requestDict.keys() ) )\ - .values( {Request._Status : 'Assigned', - Request._LastUpdate : datetime.datetime.utcnow()\ - .strftime( Request._datetimeFormat )} ) - ) + session.execute(update(Request) + .where(Request.RequestID.in_(requestDict.keys())) + .values({Request._Status: 'Assigned', + Request._LastUpdate: datetime.datetime.utcnow() + .strftime(Request._datetimeFormat)}) + ) session.commit() session.expunge_all() except Exception as e: session.rollback() - log.exception( "unexpected exception", lException = e ) - return S_ERROR( "getBulkRequest: unexpected exception : %s" % e ) + log.exception("unexpected exception", lException=e) + return S_ERROR("getBulkRequest: unexpected exception : %s" % e) finally: session.close() - return S_OK( requestDict ) + return S_OK(requestDict) - - - def peekRequest( self, requestID ): + def peekRequest(self, requestID): """ get request (ro), no update on states :param requestID: Request.RequestID """ - return self.getRequest( requestID, False ) - + return self.getRequest(requestID, False) - - def getRequestIDsList( self, statusList = None, limit = None, since = None, until = None, getJobID = False ): + def getRequestIDsList(self, statusList=None, limit=None, since=None, until=None, getJobID=False): """ select requests with status in :statusList: """ - statusList = statusList if statusList else list( Request.FINAL_STATES ) + statusList = statusList if statusList else list(Request.FINAL_STATES) limit = limit if limit else 100 session = self.DBSession() requestIDs = [] try: if getJobID: - reqQuery = session.query( Request.RequestID, Request._Status, Request._LastUpdate, Request.JobID )\ - .filter( Request._Status.in_( statusList ) ) + reqQuery = session.query(Request.RequestID, Request._Status, Request._LastUpdate, Request.JobID)\ + .filter(Request._Status.in_(statusList)) else: - reqQuery = session.query( Request.RequestID, Request._Status, Request._LastUpdate )\ - .filter( Request._Status.in_( statusList ) ) + reqQuery = session.query(Request.RequestID, Request._Status, Request._LastUpdate)\ + .filter(Request._Status.in_(statusList)) if since: - reqQuery = reqQuery.filter( Request._LastUpdate > since ) + reqQuery = reqQuery.filter(Request._LastUpdate > since) if until: - reqQuery = reqQuery.filter( Request._LastUpdate < until ) + reqQuery = reqQuery.filter(Request._LastUpdate < until) - reqQuery = reqQuery.order_by( Request._LastUpdate )\ - .limit( limit ) - requestIDs = [ tuple( reqIDTuple ) for reqIDTuple in reqQuery.all() ] + reqQuery = reqQuery.order_by(Request._LastUpdate)\ + .limit(limit) + requestIDs = [tuple(reqIDTuple) for reqIDTuple in reqQuery.all()] except Exception as e: session.rollback() - self.log.exception( "getRequestIDsList: unexpected exception", lException = e ) - return S_ERROR( "getRequestIDsList: unexpected exception : %s" % e ) + self.log.exception("getRequestIDsList: unexpected exception", lException=e) + return S_ERROR("getRequestIDsList: unexpected exception : %s" % e) finally: session.close() - return S_OK( requestIDs ) - + return S_OK(requestIDs) - - def deleteRequest( self, requestID ): + def deleteRequest(self, requestID): """ delete request given its ID :param str requestID: request.RequestID @@ -503,58 +487,55 @@ def deleteRequest( self, requestID ): session = self.DBSession() try: - session.query( Request ).filter( Request.RequestID == requestID ).delete() + session.query(Request).filter(Request.RequestID == requestID).delete() session.commit() except Exception as e: session.rollback() - self.log.exception( "deleteRequest: unexpected exception", lException = e ) - return S_ERROR( "deleteRequest: unexpected exception : %s" % e ) + self.log.exception("deleteRequest: unexpected exception", lException=e) + return S_ERROR("deleteRequest: unexpected exception : %s" % e) finally: session.close() return S_OK() - - def getDBSummary( self ): + def getDBSummary(self): """ get db summary """ # # this will be returned - retDict = { "Request" : {}, "Operation" : {}, "File" : {} } + retDict = {"Request": {}, "Operation": {}, "File": {}} session = self.DBSession() try: - requestQuery = session.query( Request._Status, func.count( Request.RequestID ) )\ - .group_by( Request._Status )\ + requestQuery = session.query(Request._Status, func.count(Request.RequestID))\ + .group_by(Request._Status)\ .all() for status, count in requestQuery: retDict["Request"][status] = count - operationQuery = session.query( Operation.Type, Operation._Status, func.count( Operation.OperationID ) )\ - .group_by( Operation.Type, Operation._Status )\ + operationQuery = session.query(Operation.Type, Operation._Status, func.count(Operation.OperationID))\ + .group_by(Operation.Type, Operation._Status)\ .all() for oType, status, count in operationQuery: - retDict['Operation'].setdefault( oType, {} )[status] = count - + retDict['Operation'].setdefault(oType, {})[status] = count - fileQuery = session.query( File._Status, func.count( File.FileID ) )\ - .group_by( File._Status )\ + fileQuery = session.query(File._Status, func.count(File.FileID))\ + .group_by(File._Status)\ .all() for status, count in fileQuery: retDict["File"][status] = count except Exception as e: - self.log.exception( "getDBSummary: unexpected exception", lException = e ) - return S_ERROR( "getDBSummary: unexpected exception : %s" % e ) + self.log.exception("getDBSummary: unexpected exception", lException=e) + return S_ERROR("getDBSummary: unexpected exception : %s" % e) finally: session.close() - return S_OK( retDict ) + return S_OK(retDict) - - def getRequestSummaryWeb( self, selectDict, sortList, startItem, maxItems ): + def getRequestSummaryWeb(self, selectDict, sortList, startItem, maxItems): """ Returns a list of Request for the web portal :param dict selectDict: parameter on which to restrain the query {key : Value} @@ -565,30 +546,25 @@ def getRequestSummaryWeb( self, selectDict, sortList, startItem, maxItems ): :param int startItem: start item (for pagination) :param int maxItems: max items (for pagination) """ - - - parameterList = [ 'RequestID', 'RequestName', 'JobID', 'OwnerDN', 'OwnerGroup', - 'Status', "Error", "CreationTime", "LastUpdate"] - + parameterList = ['RequestID', 'RequestName', 'JobID', 'OwnerDN', 'OwnerGroup', + 'Status', "Error", "CreationTime", "LastUpdate"] resultDict = {} session = self.DBSession() try: - summaryQuery = session.query( Request.RequestID, Request.RequestName, - Request.JobID, Request.OwnerDN, Request.OwnerGroup, - Request._Status, Request.Error, - Request._CreationTime, Request._LastUpdate ) - - + summaryQuery = session.query(Request.RequestID, Request.RequestName, + Request.JobID, Request.OwnerDN, Request.OwnerGroup, + Request._Status, Request.Error, + Request._CreationTime, Request._LastUpdate) for key, value in selectDict.items(): if key == 'ToDate': - summaryQuery = summaryQuery.filter( Request._LastUpdate < value ) + summaryQuery = summaryQuery.filter(Request._LastUpdate < value) elif key == 'FromDate': - summaryQuery = summaryQuery.filter( Request._LastUpdate > value ) + summaryQuery = summaryQuery.filter(Request._LastUpdate > value) else: tableName = 'Request' @@ -600,56 +576,55 @@ def getRequestSummaryWeb( self, selectDict, sortList, startItem, maxItems ): elif key == 'Status': key = '_Status' - if isinstance( value, list ): - summaryQuery = summaryQuery.filter( eval( '%s.%s.in_(%s)' % ( tableName, key, value ) ) ) + if isinstance(value, list): + summaryQuery = summaryQuery.filter(eval('%s.%s.in_(%s)' % (tableName, key, value))) else: - summaryQuery = summaryQuery.filter( eval( '%s.%s' % ( tableName, key ) ) == value ) + summaryQuery = summaryQuery.filter(eval('%s.%s' % (tableName, key)) == value) if sortList: - summaryQuery = summaryQuery.order_by( eval( 'Request.%s.%s()' % ( sortList[0][0], sortList[0][1].lower() ) ) ) + summaryQuery = summaryQuery.order_by(eval('Request.%s.%s()' % (sortList[0][0], sortList[0][1].lower()))) try: requestLists = summaryQuery.all() - except NoResultFound, e: + except NoResultFound as e: resultDict['ParameterNames'] = parameterList resultDict['Records'] = [] - return S_OK( resultDict ) + return S_OK(resultDict) except Exception as e: - return S_ERROR( 'Error getting the webSummary %s' % e ) + return S_ERROR('Error getting the webSummary %s' % e) - nRequests = len( requestLists ) + nRequests = len(requestLists) - if startItem <= len( requestLists ): + if startItem <= len(requestLists): firstIndex = startItem else: - return S_ERROR( 'getRequestSummaryWeb: Requested index out of range' ) + return S_ERROR('getRequestSummaryWeb: Requested index out of range') - if ( startItem + maxItems ) <= len( requestLists ): + if (startItem + maxItems) <= len(requestLists): secondIndex = startItem + maxItems else: - secondIndex = len( requestLists ) + secondIndex = len(requestLists) records = [] - for i in range( firstIndex, secondIndex ): + for i in range(firstIndex, secondIndex): row = requestLists[i] - records.append( [ str( x ) for x in row] ) + records.append([str(x) for x in row]) resultDict['ParameterNames'] = parameterList resultDict['Records'] = records resultDict['TotalRecords'] = nRequests - return S_OK( resultDict ) + return S_OK(resultDict) # except Exception as e: - self.log.exception( "getRequestSummaryWeb: unexpected exception", lException = e ) - return S_ERROR( "getRequestSummaryWeb: unexpected exception : %s" % e ) + self.log.exception("getRequestSummaryWeb: unexpected exception", lException=e) + return S_ERROR("getRequestSummaryWeb: unexpected exception : %s" % e) finally: session.close() - - def getRequestCountersWeb( self, groupingAttribute, selectDict ): + def getRequestCountersWeb(self, groupingAttribute, selectDict): """ For the web portal. Returns a dictionary {value : counts} for a given key. The key can be any field from the RequestTable. or "Type", @@ -668,50 +643,47 @@ def getRequestCountersWeb( self, groupingAttribute, selectDict ): groupingAttribute = 'Request.%s' % groupingAttribute try: - summaryQuery = session.query( eval( groupingAttribute ), func.count( Request.RequestID ) ) + summaryQuery = session.query(eval(groupingAttribute), func.count(Request.RequestID)) for key, value in selectDict.items(): if key == 'ToDate': - summaryQuery = summaryQuery.filter( Request._LastUpdate < value ) + summaryQuery = summaryQuery.filter(Request._LastUpdate < value) elif key == 'FromDate': - summaryQuery = summaryQuery.filter( Request._LastUpdate > value ) + summaryQuery = summaryQuery.filter(Request._LastUpdate > value) else: objectType = 'Request' if key == 'Type': - summaryQuery = summaryQuery.join( Request.__operations__ ) + summaryQuery = summaryQuery.join(Request.__operations__) objectType = 'Operation' elif key == 'Status': key = '_Status' - if isinstance( value, list ): - summaryQuery = summaryQuery.filter( eval( '%s.%s.in_(%s)' % ( objectType, key, value ) ) ) + if isinstance(value, list): + summaryQuery = summaryQuery.filter(eval('%s.%s.in_(%s)' % (objectType, key, value))) else: - summaryQuery = summaryQuery.filter( eval( '%s.%s' % ( objectType, key ) ) == value ) + summaryQuery = summaryQuery.filter(eval('%s.%s' % (objectType, key)) == value) - summaryQuery = summaryQuery.group_by( groupingAttribute ) + summaryQuery = summaryQuery.group_by(groupingAttribute) try: requestLists = summaryQuery.all() - resultDict = dict( requestLists ) - except NoResultFound, e: + resultDict = dict(requestLists) + except NoResultFound as e: pass except Exception as e: - return S_ERROR( 'Error getting the webCounters %s' % e ) - + return S_ERROR('Error getting the webCounters %s' % e) - - return S_OK( resultDict ) + return S_OK(resultDict) except Exception as e: - self.log.exception( "getRequestSummaryWeb: unexpected exception", lException = e ) - return S_ERROR( "getRequestSummaryWeb: unexpected exception : %s" % e ) + self.log.exception("getRequestSummaryWeb: unexpected exception", lException=e) + return S_ERROR("getRequestSummaryWeb: unexpected exception : %s" % e) finally: session.close() - - def getDistinctValues( self, tableName, columnName ): + def getDistinctValues(self, tableName, columnName): """ For a given table and a given field, return the list of of distinct values in the DB""" session = self.DBSession() @@ -719,54 +691,52 @@ def getDistinctValues( self, tableName, columnName ): if columnName == 'Status': columnName = '_Status' try: - result = session.query( distinct( eval ( "%s.%s" % ( tableName, columnName ) ) ) ).all() + result = session.query(distinct(eval("%s.%s" % (tableName, columnName)))).all() distinctValues = [dist[0] for dist in result] - except NoResultFound, e: + except NoResultFound as e: pass except Exception as e: - self.log.exception( "getDistinctValues: unexpected exception", lException = e ) - return S_ERROR( "getDistinctValues: unexpected exception : %s" % e ) + self.log.exception("getDistinctValues: unexpected exception", lException=e) + return S_ERROR("getDistinctValues: unexpected exception : %s" % e) finally: session.close() - return S_OK( distinctValues ) - + return S_OK(distinctValues) - def getRequestIDsForJobs( self, jobIDs ): + def getRequestIDsForJobs(self, jobIDs): """ read request ids for jobs given jobIDs :param jobIDs: list of jobIDs :type jobIDs: python:list """ - self.log.debug( "getRequestIDsForJobs: got %s jobIDs to check" % str( jobIDs ) ) + self.log.debug("getRequestIDsForJobs: got %s jobIDs to check" % str(jobIDs)) if not jobIDs: - return S_ERROR( "Must provide jobID list as argument." ) - if isinstance( jobIDs, ( long, int ) ): - jobIDs = [ jobIDs ] - jobIDs = set( jobIDs ) + return S_ERROR("Must provide jobID list as argument.") + if isinstance(jobIDs, (long, int)): + jobIDs = [jobIDs] + jobIDs = set(jobIDs) - reqDict = { "Successful": {}, "Failed": {} } + reqDict = {"Successful": {}, "Failed": {}} session = self.DBSession() try: - ret = session.query( Request.JobID, Request.RequestID )\ - .filter( Request.JobID.in_( jobIDs ) )\ - .all() + ret = session.query(Request.JobID, Request.RequestID)\ + .filter(Request.JobID.in_(jobIDs))\ + .all() - reqDict['Successful'] = dict( ( jobId, reqID ) for jobId, reqID in ret ) - reqDict['Failed'] = dict( ( jobid, 'Request not found' ) for jobid in jobIDs - set( reqDict['Successful'] ) ) + reqDict['Successful'] = dict((jobId, reqID) for jobId, reqID in ret) + reqDict['Failed'] = dict((jobid, 'Request not found') for jobid in jobIDs - set(reqDict['Successful'])) except Exception as e: - self.log.exception( "getRequestIDsForJobs: unexpected exception", lException = e ) - return S_ERROR( "getRequestIDsForJobs: unexpected exception : %s" % e ) + self.log.exception("getRequestIDsForJobs: unexpected exception", lException=e) + return S_ERROR("getRequestIDsForJobs: unexpected exception : %s" % e) finally: session.close() - return S_OK( reqDict ) + return S_OK(reqDict) - - def readRequestsForJobs( self, jobIDs = None ): + def readRequestsForJobs(self, jobIDs=None): """ read request for jobs :param jobIDs: list of JobIDs @@ -774,50 +744,48 @@ def readRequestsForJobs( self, jobIDs = None ): :return: S_OK( "Successful" : { jobID1 : Request, jobID2: Request, ... } "Failed" : { jobID3: "error message", ... } ) """ - self.log.debug( "readRequestForJobs: got %s jobIDs to check" % str( jobIDs ) ) + self.log.debug("readRequestForJobs: got %s jobIDs to check" % str(jobIDs)) if not jobIDs: - return S_ERROR( "Must provide jobID list as argument." ) - if isinstance( jobIDs, ( long, int ) ): - jobIDs = [ jobIDs ] - jobIDs = set( jobIDs ) + return S_ERROR("Must provide jobID list as argument.") + if isinstance(jobIDs, (long, int)): + jobIDs = [jobIDs] + jobIDs = set(jobIDs) - reqDict = { "Successful": {}, "Failed": {} } + reqDict = {"Successful": {}, "Failed": {}} # expire_on_commit is set to False so that we can still use the object after we close the session - session = self.DBSession( expire_on_commit = False ) + session = self.DBSession(expire_on_commit=False) try: - ret = session.query( Request.JobID, Request )\ - .options( joinedload_all( '__operations__.__files__' ) )\ - .filter( Request.JobID.in_( jobIDs ) ).all() + ret = session.query(Request.JobID, Request)\ + .options(joinedload_all('__operations__.__files__'))\ + .filter(Request.JobID.in_(jobIDs)).all() - reqDict['Successful'] = dict( ( jobId, reqObj ) for jobId, reqObj in ret ) + reqDict['Successful'] = dict((jobId, reqObj) for jobId, reqObj in ret) - reqDict['Failed'] = dict( ( jobid, 'Request not found' ) for jobid in jobIDs - set( reqDict['Successful'] ) ) + reqDict['Failed'] = dict((jobid, 'Request not found') for jobid in jobIDs - set(reqDict['Successful'])) session.expunge_all() except Exception as e: - self.log.exception( "readRequestsForJobs: unexpected exception", lException = e ) - return S_ERROR( "readRequestsForJobs: unexpected exception : %s" % e ) + self.log.exception("readRequestsForJobs: unexpected exception", lException=e) + return S_ERROR("readRequestsForJobs: unexpected exception : %s" % e) finally: session.close() - return S_OK( reqDict ) - + return S_OK(reqDict) - def getRequestStatus( self, requestID ): + def getRequestStatus(self, requestID): """ get request status for a given request ID """ - self.log.debug( "getRequestStatus: checking status for '%s' request" % requestID ) + self.log.debug("getRequestStatus: checking status for '%s' request" % requestID) session = self.DBSession() try: - status = session.query( Request._Status ).filter( Request.RequestID == requestID ).one() - except NoResultFound: - return S_ERROR( "Request %s does not exist" % requestID ) + status = session.query(Request._Status).filter(Request.RequestID == requestID).one() + except NoResultFound: + return S_ERROR(errno.ENOENT, "Request %s does not exist" % requestID) finally: session.close() - return S_OK( status[0] ) - + return S_OK(status[0]) - def getRequestFileStatus( self, requestID, lfnList ): + def getRequestFileStatus(self, requestID, lfnList): """ get status for files in request given its id :param str requestID: Request.RequestID @@ -827,71 +795,68 @@ def getRequestFileStatus( self, requestID, lfnList ): session = self.DBSession() try: - res = dict.fromkeys( lfnList, "UNKNOWN" ) - requestRet = session.query( File._LFN, File._Status )\ - .join( Request.__operations__ )\ - .join( Operation.__files__ )\ - .filter( Request.RequestID == requestID )\ - .filter( File._LFN.in_( lfnList ) )\ - .all() + res = dict.fromkeys(lfnList, "UNKNOWN") + requestRet = session.query(File._LFN, File._Status)\ + .join(Request.__operations__)\ + .join(Operation.__files__)\ + .filter(Request.RequestID == requestID)\ + .filter(File._LFN.in_(lfnList))\ + .all() for lfn, status in requestRet: res[lfn] = status - return S_OK( res ) + return S_OK(res) except Exception as e: - self.log.exception( "getRequestFileStatus: unexpected exception", lException = e ) - return S_ERROR( "getRequestFileStatus: unexpected exception : %s" % e ) + self.log.exception("getRequestFileStatus: unexpected exception", lException=e) + return S_ERROR("getRequestFileStatus: unexpected exception : %s" % e) finally: session.close() - - def getRequestInfo( self, requestID ): + def getRequestInfo(self, requestID): """ get request info given Request.RequestID """ session = self.DBSession() try: - requestInfoQuery = session.query( Request.RequestID, Request._Status, Request.RequestName, - Request.JobID, Request.OwnerDN, Request.OwnerGroup, - Request.DIRACSetup, Request.SourceComponent, Request._CreationTime, - Request._SubmitTime, Request._LastUpdate )\ - .filter( Request.RequestID == requestID ) - + requestInfoQuery = session.query(Request.RequestID, Request._Status, Request.RequestName, + Request.JobID, Request.OwnerDN, Request.OwnerGroup, + Request.DIRACSetup, Request.SourceComponent, Request._CreationTime, + Request._SubmitTime, Request._LastUpdate)\ + .filter(Request.RequestID == requestID) try: requestInfo = requestInfoQuery.one() except NoResultFound: - return S_ERROR( 'No such request' ) + return S_ERROR('No such request') - return S_OK( tuple( requestInfo ) ) + return S_OK(tuple(requestInfo)) except Exception as e: - self.log.exception( "getRequestInfo: unexpected exception", lException = e ) - return S_ERROR( "getRequestInfo: unexpected exception : %s" % e ) + self.log.exception("getRequestInfo: unexpected exception", lException=e) + return S_ERROR("getRequestInfo: unexpected exception : %s" % e) finally: session.close() - def getDigest( self, requestID ): + def getDigest(self, requestID): """ get digest for request given its id :param str requestName: request id """ - self.log.debug( "getDigest: will create digest for request '%s'" % requestID ) - request = self.getRequest( requestID, False ) + self.log.debug("getDigest: will create digest for request '%s'" % requestID) + request = self.getRequest(requestID, False) if not request["OK"]: - self.log.error( "getDigest: %s" % request["Message"] ) + self.log.error("getDigest: %s" % request["Message"]) return request request = request["Value"] - if not isinstance( request, Request ): - self.log.info( "getDigest: request '%s' not found" ) + if not isinstance(request, Request): + self.log.info("getDigest: request '%s' not found") return S_OK() return request.getDigest() - - def getRequestIDForName( self, requestName ): + def getRequestIDForName(self, requestName): """ read request id for given name if the name is not unique, an error is returned @@ -901,22 +866,22 @@ def getRequestIDForName( self, requestName ): reqID = 0 try: - ret = session.query( Request.RequestID )\ - .filter( Request.RequestName == requestName )\ + ret = session.query(Request.RequestID)\ + .filter(Request.RequestName == requestName)\ .all() if not ret: - return S_ERROR( 'No such request %s' % requestName ) - elif len( ret ) > 1: - return S_ERROR( 'RequestName %s not unique (%s matches)' % ( requestName, len( ret ) ) ) + return S_ERROR('No such request %s' % requestName) + elif len(ret) > 1: + return S_ERROR('RequestName %s not unique (%s matches)' % (requestName, len(ret))) reqID = ret[0][0] - except NoResultFound, e: - return S_ERROR( 'No such request' ) + except NoResultFound as e: + return S_ERROR('No such request') except Exception as e: - self.log.exception( "getRequestIDsForName: unexpected exception", lException = e ) - return S_ERROR( "getRequestIDsForName: unexpected exception : %s" % e ) + self.log.exception("getRequestIDsForName: unexpected exception", lException=e) + return S_ERROR("getRequestIDsForName: unexpected exception : %s" % e) finally: session.close() - return S_OK( reqID ) + return S_OK(reqID) From 62d719595e3158eea8e22c2f1bae4dd1d3ea33fc Mon Sep 17 00:00:00 2001 From: Christophe Haen Date: Mon, 15 Jun 2020 10:32:54 +0200 Subject: [PATCH 04/24] gitignore: ignore env file for vscode --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0e1c97cd729..7bea1aaba40 100644 --- a/.gitignore +++ b/.gitignore @@ -72,6 +72,7 @@ tests/CI/SERVERCONFIG # VSCode .vscode +.env # docs # this is auto generated From 48144008702d1f0659123bab432f39fa10b8bf2f Mon Sep 17 00:00:00 2001 From: Simon Fayer Date: Tue, 16 Jun 2020 20:04:24 +0100 Subject: [PATCH 05/24] Print error if LFN list is missing --- DataManagementSystem/scripts/dirac-dms-add-file.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/DataManagementSystem/scripts/dirac-dms-add-file.py b/DataManagementSystem/scripts/dirac-dms-add-file.py index a2bcb95804b..2ecc74bcd6b 100755 --- a/DataManagementSystem/scripts/dirac-dms-add-file.py +++ b/DataManagementSystem/scripts/dirac-dms-add-file.py @@ -56,6 +56,11 @@ def getDict( item_list ): lfn_dict['guid'] = guid return lfn_dict +from DIRAC.DataManagementSystem.Client.DataManager import DataManager +from DIRAC import gLogger +import DIRAC +exitCode = 0 + lfns = [] if len( args ) == 1: inputFileName = args[0] @@ -67,14 +72,12 @@ def getDict( item_list ): items[0] = items[0].replace( 'LFN:', '' ).replace( 'lfn:', '' ) lfns.append( getDict( items ) ) inputFile.close() + else: + gLogger.error("Error: LFN list '%s' missing." % inputFileName) + exitCode = 4 else: lfns.append( getDict( args ) ) -from DIRAC.DataManagementSystem.Client.DataManager import DataManager -from DIRAC import gLogger -import DIRAC -exitCode = 0 - dm = DataManager() for lfn in lfns: if not os.path.exists( lfn['localfile'] ): From f0ab1d0eef4bcbc4a33883ef3f2b3aec68ac1ecb Mon Sep 17 00:00:00 2001 From: Philippe Charpentier Date: Wed, 17 Jun 2020 09:53:19 +0200 Subject: [PATCH 06/24] fix hospital handling --- TransformationSystem/Client/TaskManager.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TransformationSystem/Client/TaskManager.py b/TransformationSystem/Client/TaskManager.py index a711c0b9e63..1f6afddb677 100644 --- a/TransformationSystem/Client/TaskManager.py +++ b/TransformationSystem/Client/TaskManager.py @@ -827,8 +827,8 @@ def _checkSickTransformations(self, transID): """ Check if the transformation is in the transformations to be processed at Hospital or Clinic """ transID = int(transID) - clinicPath = "Hospital/Transformations" - if transID in set(int(x) for x in self.opsH.getValue(clinicPath, [])): + clinicPath = "Hospital" + if transID in set(int(x) for x in self.opsH.getValue(os.path.join(clinicPath, "Transformations"), [])): return clinicPath if "Clinics" in self.opsH.getSections("Hospital").get('Value', []): basePath = os.path.join("Hospital", "Clinics") From a7c1fdacd8d9556fd7d18109e9b6e124f689765f Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Mon, 8 Jun 2020 12:47:33 +0200 Subject: [PATCH 07/24] dirac-admin-add-host: adding host to ComponentMonitoring --- Interfaces/scripts/dirac-admin-add-host.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Interfaces/scripts/dirac-admin-add-host.py b/Interfaces/scripts/dirac-admin-add-host.py index 7d7ca02c25c..2ed1376f542 100755 --- a/Interfaces/scripts/dirac-admin-add-host.py +++ b/Interfaces/scripts/dirac-admin-add-host.py @@ -76,6 +76,19 @@ def addProperty( arg ): errorList.append( ( "commit", result[ 'Message' ] ) ) exitCode = 255 +if exitCode == 0: + from DIRAC.FrameworkSystem.Client.ComponentMonitoringClient import ComponentMonitoringClient + cmc = ComponentMonitoringClient() + ret = cmc.hostExists(dict(HostName=hostName)) + if not ret['OK']: + Script.gLogger.error('Cannot check if host is registered in ComponentMoniroting', ret['Message']) + elif ret['Value']: + Script.gLogger.info('Host already registered in ComponentMonitoring') + else: + ret = cmc.addHost(dict(HostName=hostName, CPU='TO_COME')) + if not ret['OK']: + Script.gLogger.error('Failed to add Host to ComponentMonitoring', ret['Message']) + for error in errorList: Script.gLogger.error( "%s: %s" % error ) From 52f597dd930cda913f1bd6b72beba6276d720562 Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Thu, 11 Jun 2020 09:53:10 +0200 Subject: [PATCH 08/24] CSAPI: fix and expand parameter docstrings indentation was off for some, causing failure to properly markup --- ConfigurationSystem/Client/CSAPI.py | 49 ++++++++++++++++------------- 1 file changed, 27 insertions(+), 22 deletions(-) diff --git a/ConfigurationSystem/Client/CSAPI.py b/ConfigurationSystem/Client/CSAPI.py index dd052219262..f547b2b36f3 100644 --- a/ConfigurationSystem/Client/CSAPI.py +++ b/ConfigurationSystem/Client/CSAPI.py @@ -121,7 +121,7 @@ def listHosts(self): def describeUsers(self, users=None): """ describe users by nickname - :param list users: list of users' nickanames + :param list users: list of users' nicknames :return: a S_OK(description) of the users in input """ if users is None: @@ -240,14 +240,14 @@ def addUser(self, username, properties): """ Add a user to the cs - :param str username: group name - :param dict properties: dictionary describing user properties: + :param str username: username + :param dict properties: dictionary describing user properties: - - DN - - groups - - + - DN + - groups + - - :return: True/False + :return: True/False """ if not self.__initialized['OK']: return self.__initialized @@ -279,14 +279,15 @@ def modifyUser(self, username, properties, createIfNonExistant=False): """ Modify a user - :param str username: group name - :param dict properties: dictionary describing user properties: + :param str username: group name + :param dict properties: dictionary describing user properties: - DN - Groups - - :return: S_OK, Value = True/False + :param bool createIfNonExistant: if true, registers the users if it did not exist + :return: S_OK, Value = True/False """ if not self.__initialized['OK']: return self.__initialized @@ -341,14 +342,14 @@ def addGroup(self, groupname, properties): """ Add a group to the cs - :param str groupname: group name - :param dict properties: dictionary describing group properties: + :param str groupname: group name + :param dict properties: dictionary describing group properties: - Users - Properties - - :return: True/False + :return: S_OK, Value = True/False """ if not self.__initialized['OK']: return self.__initialized @@ -366,14 +367,15 @@ def modifyGroup(self, groupname, properties, createIfNonExistant=False): """ Modify a group - :param str groupname: group name - :param dict properties: dictionary describing group properties: + :param str groupname: group name + :param dict properties: dictionary describing group properties: - Users - Properties - - :return: True/False + :param bool createIfNonExistant: if true, creates the group if it did not exist + :return: S_OK, Value = True/False """ if not self.__initialized['OK']: return self.__initialized @@ -401,14 +403,15 @@ def modifyGroup(self, groupname, properties, createIfNonExistant=False): def addHost(self, hostname, properties): """ Add a host to the cs - :param str hostname: hostname name - :param dict properties: dictionary describing host properties: + + :param str hostname: host name + :param dict properties: dictionary describing host properties: - DN - Properties - - :return: True/False + :return: S_OK, Value = True/False """ if not self.__initialized['OK']: return self.__initialized @@ -528,14 +531,16 @@ def getOpsSection(): def modifyHost(self, hostname, properties, createIfNonExistant=False): """ Modify a host - :param str hostname: hostname name - :param dict properties: dictionary describing host properties: + + :param str hostname: hostname name + :param dict properties: dictionary describing host properties: - DN - Properties - - :return: True/False + :param bool createIfNonExistant: if true, creates the host if it did not exist + :return: S_OK, Value = True/False """ if not self.__initialized['OK']: return self.__initialized From 6c669c1e47b267329e78a33cee6a4261ac5eb546 Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Thu, 11 Jun 2020 10:32:02 +0200 Subject: [PATCH 09/24] Config: add documentation for type of gConfig --- ConfigurationSystem/Client/Config.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ConfigurationSystem/Client/Config.py b/ConfigurationSystem/Client/Config.py index 11314f2a160..6363f77d4c5 100755 --- a/ConfigurationSystem/Client/Config.py +++ b/ConfigurationSystem/Client/Config.py @@ -6,8 +6,13 @@ from DIRAC.ConfigurationSystem.private.ConfigurationClient import ConfigurationClient +#: Global gConfig object of type :class:`~DIRAC.ConfigurationSystem.private.ConfigurationClient.ConfigurationClient` gConfig = ConfigurationClient() def getConfig(): + """ + :returns: gConfig + :rtype: ~DIRAC.ConfigurationSystem.private.ConfigurationClient.ConfigurationClient + """ return gConfig From 97dd214d0df23342f514035b1aeb248e6da88d43 Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Mon, 22 Jun 2020 11:38:19 +0200 Subject: [PATCH 10/24] dirac-admin-add-host: Fix typo in log message Co-authored-by: fstagni --- Interfaces/scripts/dirac-admin-add-host.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Interfaces/scripts/dirac-admin-add-host.py b/Interfaces/scripts/dirac-admin-add-host.py index 2ed1376f542..04dc291493d 100755 --- a/Interfaces/scripts/dirac-admin-add-host.py +++ b/Interfaces/scripts/dirac-admin-add-host.py @@ -81,7 +81,7 @@ def addProperty( arg ): cmc = ComponentMonitoringClient() ret = cmc.hostExists(dict(HostName=hostName)) if not ret['OK']: - Script.gLogger.error('Cannot check if host is registered in ComponentMoniroting', ret['Message']) + Script.gLogger.error('Cannot check if host is registered in ComponentMonitoring', ret['Message']) elif ret['Value']: Script.gLogger.info('Host already registered in ComponentMonitoring') else: From e4207d11a1f491082e7bdd18b100a63db74dd4a4 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Wed, 24 Jun 2020 16:39:16 +0200 Subject: [PATCH 11/24] pytest without coverage --- .github/workflows/basic.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml index 21febce9efd..348b18141f8 100644 --- a/.github/workflows/basic.yml +++ b/.github/workflows/basic.yml @@ -12,10 +12,10 @@ jobs: fail-fast: False matrix: command: - - pytest - - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest - - pytest Core/Security/test - - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest Core/Security/test + - pytest --no-cov + - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov + - pytest --no-cov Core/Security/test + - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov Core/Security/test - tests/checkDocs.sh # TODO This should cover more than just tests/CI # Excluded codes related to sourcing files From 6b995e99dab365ac3edd1d847fd533626e8d2968 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Wed, 24 Jun 2020 21:00:37 +0200 Subject: [PATCH 12/24] no --no-cov fir general pytest --- .github/workflows/basic.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml index 348b18141f8..9bcc0f00cf9 100644 --- a/.github/workflows/basic.yml +++ b/.github/workflows/basic.yml @@ -12,8 +12,8 @@ jobs: fail-fast: False matrix: command: - - pytest --no-cov - - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov + - pytest + - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest - pytest --no-cov Core/Security/test - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov Core/Security/test - tests/checkDocs.sh From c08871db85ecf7ece4069aad3100d76d5397c72f Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Thu, 25 Jun 2020 09:26:22 +0200 Subject: [PATCH 13/24] once again --- .github/workflows/basic.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml index 9bcc0f00cf9..7d70c7d623b 100644 --- a/.github/workflows/basic.yml +++ b/.github/workflows/basic.yml @@ -12,7 +12,7 @@ jobs: fail-fast: False matrix: command: - - pytest + - pytest --no-cov - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest - pytest --no-cov Core/Security/test - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov Core/Security/test From ebc8639fa65732f1dfb355227181190ccfca9ea6 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Thu, 25 Jun 2020 10:38:50 +0200 Subject: [PATCH 14/24] test adapted for --no-cov pytest running --- .../PilotAgent/test/Test_Pilot.py | 67 ++++++------------- 1 file changed, 22 insertions(+), 45 deletions(-) diff --git a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py index 8e986940958..dc8468c991c 100644 --- a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py +++ b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py @@ -2,54 +2,31 @@ """ # imports -import unittest import json import os +import sys + +if "--no-cov" in sys.argv: + del sys.argv[sys.argv.index( '--no-cov' )] from DIRAC.WorkloadManagementSystem.PilotAgent.pilotTools import PilotParams, CommandBase from DIRAC.WorkloadManagementSystem.PilotAgent.pilotCommands import GetPilotVersion -class PilotTestCase( unittest.TestCase ): - """ Base class for the Agents test cases - """ - def setUp( self ): - self.pp = PilotParams() - - def tearDown( self ): - try: - os.remove('pilot.out') - os.remove( 'pilot.json' ) - os.remove( 'pilot.json-local' ) - except OSError: - pass - - -class CommandsTestCase( PilotTestCase ): - - def test_commandBase(self): - cb = CommandBase(self.pp) - returnCode, _outputData = cb.executeAndGetOutput("ls") - self.assertEqual(returnCode, 0) - - def test_GetPilotVersion( self ): - - # Now defining a local file for test, and all the necessary parameters - fp = open( 'pilot.json', 'w' ) - json.dump( {'TestSetup':{'Version':['v1r1', 'v2r2']}}, fp ) - fp.close() - self.pp.setup = 'TestSetup' - self.pp.pilotCFGFileLocation = 'file://%s' % os.getcwd() - gpv = GetPilotVersion( self.pp ) - self.assertIsNone( gpv.execute() ) - self.assertEqual( gpv.pp.releaseVersion, 'v1r1' ) - -############################################################################# -# Test Suite run -############################################################################# - -if __name__ == '__main__': - suite = unittest.defaultTestLoader.loadTestsFromTestCase( PilotTestCase ) - suite.addTest( unittest.defaultTestLoader.loadTestsFromTestCase( CommandsTestCase ) ) - testResult = unittest.TextTestRunner( verbosity = 2 ).run( suite ) - -# EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF# +def test_GetPilotVersion(): + pp = PilotParams() + # Now defining a local file for test, and all the necessary parameters + fp = open( 'pilot.json', 'w' ) + json.dump( { 'TestSetup': { 'Version': ['v1r1', 'v2r2'] } }, fp ) + fp.close() + pp.setup = 'TestSetup' + pp.pilotCFGFileLocation = 'file://%s' % os.getcwd() + gpv = GetPilotVersion( pp ) + result = gpv.execute() + assert result is None + assert gpv.pp.releaseVersion == 'v1r1' + +def test_commandBase(): + pp = PilotParams() + cb = CommandBase( pp ) + returnCode, _outputData = cb.executeAndGetOutput( "ls" ) + assert returnCode== 0 From b996650e9fd4967250ed1072010dc8ced78a8dc6 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Thu, 25 Jun 2020 10:44:22 +0200 Subject: [PATCH 15/24] hopefully the final --no-cov --- .github/workflows/basic.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/basic.yml b/.github/workflows/basic.yml index 7d70c7d623b..348b18141f8 100644 --- a/.github/workflows/basic.yml +++ b/.github/workflows/basic.yml @@ -13,7 +13,7 @@ jobs: matrix: command: - pytest --no-cov - - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest + - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov - pytest --no-cov Core/Security/test - DIRAC_USE_M2CRYPTO=Yes DIRAC_M2CRYPTO_SPLIT_HANDSHAKE=Yes pytest --no-cov Core/Security/test - tests/checkDocs.sh From e8d903fe192130b808944c762f8c85f490b67529 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Thu, 25 Jun 2020 10:51:04 +0200 Subject: [PATCH 16/24] typo fixed --- WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py index dc8468c991c..aafbc2c273a 100644 --- a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py +++ b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py @@ -29,4 +29,4 @@ def test_commandBase(): pp = PilotParams() cb = CommandBase( pp ) returnCode, _outputData = cb.executeAndGetOutput( "ls" ) - assert returnCode== 0 + assert returnCode == 0 From dc3f58165e79bb844c7c83fe04f0d4d68a1fecfb Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Thu, 25 Jun 2020 11:14:17 +0200 Subject: [PATCH 17/24] autopep8 --- .../PilotAgent/test/Test_Pilot.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py index aafbc2c273a..a183bf9f959 100644 --- a/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py +++ b/WorkloadManagementSystem/PilotAgent/test/Test_Pilot.py @@ -7,26 +7,28 @@ import sys if "--no-cov" in sys.argv: - del sys.argv[sys.argv.index( '--no-cov' )] + del sys.argv[sys.argv.index('--no-cov')] from DIRAC.WorkloadManagementSystem.PilotAgent.pilotTools import PilotParams, CommandBase from DIRAC.WorkloadManagementSystem.PilotAgent.pilotCommands import GetPilotVersion + def test_GetPilotVersion(): pp = PilotParams() # Now defining a local file for test, and all the necessary parameters - fp = open( 'pilot.json', 'w' ) - json.dump( { 'TestSetup': { 'Version': ['v1r1', 'v2r2'] } }, fp ) + fp = open('pilot.json', 'w') + json.dump({'TestSetup': {'Version': ['v1r1', 'v2r2']}}, fp) fp.close() pp.setup = 'TestSetup' pp.pilotCFGFileLocation = 'file://%s' % os.getcwd() - gpv = GetPilotVersion( pp ) + gpv = GetPilotVersion(pp) result = gpv.execute() assert result is None assert gpv.pp.releaseVersion == 'v1r1' + def test_commandBase(): pp = PilotParams() - cb = CommandBase( pp ) - returnCode, _outputData = cb.executeAndGetOutput( "ls" ) + cb = CommandBase(pp) + returnCode, _outputData = cb.executeAndGetOutput("ls") assert returnCode == 0 From 105bcfbdb9edfd762887aafa0f9540c6e84d0231 Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Thu, 25 Jun 2020 10:41:27 +0200 Subject: [PATCH 18/24] ComponentInstaller: allow underscores in installed components The previous split would drop things after an underscore in the installed components name (e.g., Bdii2CSAgent_GLUE2) --- FrameworkSystem/Client/ComponentInstaller.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/FrameworkSystem/Client/ComponentInstaller.py b/FrameworkSystem/Client/ComponentInstaller.py index d71901639d4..63baf94e43c 100644 --- a/FrameworkSystem/Client/ComponentInstaller.py +++ b/FrameworkSystem/Client/ComponentInstaller.py @@ -1130,7 +1130,7 @@ def getSetupComponents(self): for cType in self.componentTypes: if body.find('dirac-%s' % (cType)) != -1: - system, compT = component.split('_')[0:2] + system, compT = component.split('_', 1) if system not in resultDict[resultIndexes[cType]]: resultDict[resultIndexes[cType]][system] = [] resultDict[resultIndexes[cType]][system].append(compT) From 2661d6b625ec0a8b0c41251f53c7d9014c2654ec Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Thu, 25 Jun 2020 12:54:59 +0200 Subject: [PATCH 19/24] dirac-transformation-clean: fix use of position arguments allows calling the script with e.g., -ddd --- TransformationSystem/scripts/dirac-transformation-clean.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/TransformationSystem/scripts/dirac-transformation-clean.py b/TransformationSystem/scripts/dirac-transformation-clean.py index ddc63836010..452afc62078 100755 --- a/TransformationSystem/scripts/dirac-transformation-clean.py +++ b/TransformationSystem/scripts/dirac-transformation-clean.py @@ -5,7 +5,7 @@ from __future__ import print_function import sys -from DIRAC.Core.Base.Script import parseCommandLine +from DIRAC.Core.Base.Script import parseCommandLine, getPositionalArgs parseCommandLine() from DIRAC.TransformationSystem.Agent.TransformationCleaningAgent import TransformationCleaningAgent @@ -15,8 +15,7 @@ print('Usage: dirac-transformation-clean transID [transID] [transID]') sys.exit() else: - transIDs = [int( arg ) for arg in sys.argv[1:]] - + transIDs = [int(arg) for arg in getPositionalArgs()] agent = TransformationCleaningAgent( 'Transformation/TransformationCleaningAgent', 'Transformation/TransformationCleaningAgent', From b3bd16cfaa9dda967378e75518fa75e2bf843f98 Mon Sep 17 00:00:00 2001 From: Andre Sailer Date: Thu, 25 Jun 2020 13:13:37 +0200 Subject: [PATCH 20/24] Transformation scripts: allow command line flags (e.g., -ddd) --- .../scripts/dirac-transformation-archive.py | 6 +++--- TransformationSystem/scripts/dirac-transformation-clean.py | 2 +- .../scripts/dirac-transformation-remove-output.py | 6 +++--- .../scripts/dirac-transformation-verify-outputdata.py | 6 +++--- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/TransformationSystem/scripts/dirac-transformation-archive.py b/TransformationSystem/scripts/dirac-transformation-archive.py index 08afe90b0f3..9cd3018bff7 100755 --- a/TransformationSystem/scripts/dirac-transformation-archive.py +++ b/TransformationSystem/scripts/dirac-transformation-archive.py @@ -5,14 +5,14 @@ from __future__ import print_function import sys -from DIRAC.Core.Base.Script import parseCommandLine +from DIRAC.Core.Base.Script import parseCommandLine, getPositionalArgs parseCommandLine() -if len( sys.argv ) < 2: +if not getPositionalArgs(): print('Usage: dirac-transformation-archive transID [transID] [transID]') sys.exit() else: - transIDs = [int( arg ) for arg in sys.argv[1:]] + transIDs = [int(arg) for arg in getPositionalArgs()] from DIRAC.TransformationSystem.Agent.TransformationCleaningAgent import TransformationCleaningAgent from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient diff --git a/TransformationSystem/scripts/dirac-transformation-clean.py b/TransformationSystem/scripts/dirac-transformation-clean.py index 452afc62078..d9c5f5a48aa 100755 --- a/TransformationSystem/scripts/dirac-transformation-clean.py +++ b/TransformationSystem/scripts/dirac-transformation-clean.py @@ -11,7 +11,7 @@ from DIRAC.TransformationSystem.Agent.TransformationCleaningAgent import TransformationCleaningAgent from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient -if len( sys.argv ) < 2: +if not getPositionalArgs(): print('Usage: dirac-transformation-clean transID [transID] [transID]') sys.exit() else: diff --git a/TransformationSystem/scripts/dirac-transformation-remove-output.py b/TransformationSystem/scripts/dirac-transformation-remove-output.py index 332e91f7509..4f3d6353680 100755 --- a/TransformationSystem/scripts/dirac-transformation-remove-output.py +++ b/TransformationSystem/scripts/dirac-transformation-remove-output.py @@ -5,14 +5,14 @@ from __future__ import print_function import sys -from DIRAC.Core.Base.Script import parseCommandLine +from DIRAC.Core.Base.Script import parseCommandLine, getPositionalArgs parseCommandLine() -if len( sys.argv ) < 2: +if not getPositionalArgs(): print('Usage: dirac-transformation-remove-output transID [transID] [transID]') sys.exit() else: - transIDs = [int( arg ) for arg in sys.argv[1:]] + transIDs = [int(arg) for arg in getPositionalArgs()] from DIRAC.TransformationSystem.Agent.TransformationCleaningAgent import TransformationCleaningAgent from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient diff --git a/TransformationSystem/scripts/dirac-transformation-verify-outputdata.py b/TransformationSystem/scripts/dirac-transformation-verify-outputdata.py index c4a59a114c7..eaf6a20682e 100755 --- a/TransformationSystem/scripts/dirac-transformation-verify-outputdata.py +++ b/TransformationSystem/scripts/dirac-transformation-verify-outputdata.py @@ -5,14 +5,14 @@ from __future__ import print_function import sys -from DIRAC.Core.Base.Script import parseCommandLine +from DIRAC.Core.Base.Script import parseCommandLine, getPositionalArgs parseCommandLine() -if len( sys.argv ) < 2: +if not getPositionalArgs(): print('Usage: dirac-transformation-verify-outputdata transID [transID] [transID]') sys.exit() else: - transIDs = [int( arg ) for arg in sys.argv[1:]] + transIDs = [int(arg) for arg in getPositionalArgs()] from DIRAC.TransformationSystem.Agent.ValidateOutputDataAgent import ValidateOutputDataAgent from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient From 6385e74de8c450f0c3fa46c88ffd2f78db7960b6 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Sun, 28 Jun 2020 22:08:55 +0200 Subject: [PATCH 21/24] Resolve error under DIRACOS environment --- RequestManagementSystem/DB/RequestDB.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RequestManagementSystem/DB/RequestDB.py b/RequestManagementSystem/DB/RequestDB.py index affd832a27a..d6641fb03e7 100644 --- a/RequestManagementSystem/DB/RequestDB.py +++ b/RequestManagementSystem/DB/RequestDB.py @@ -688,7 +688,7 @@ def getRequestCountersWeb( self, groupingAttribute, selectDict ): else: summaryQuery = summaryQuery.filter( eval( '%s.%s' % ( objectType, key ) ) == value ) - summaryQuery = summaryQuery.group_by( groupingAttribute ) + summaryQuery = summaryQuery.group_by(eval(groupingAttribute)) try: requestLists = summaryQuery.all() From 4a28881d914944903e1ec67221b759c85946fac7 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Sun, 28 Jun 2020 22:11:44 +0200 Subject: [PATCH 22/24] v6r22p31 notes and tags --- __init__.py | 2 +- release.notes | 8 ++++++++ setup.py | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/__init__.py b/__init__.py index ee2397a8a4c..7a165262c9f 100755 --- a/__init__.py +++ b/__init__.py @@ -78,7 +78,7 @@ majorVersion = 6 minorVersion = 22 -patchLevel = 30 +patchLevel = 31 preVersion = 0 version = "v%sr%s" % (majorVersion, minorVersion) diff --git a/release.notes b/release.notes index 55a61a1e5af..309d6c35c47 100644 --- a/release.notes +++ b/release.notes @@ -1,3 +1,11 @@ +[v6r22p31] + +*DMS +FIX: (#4646) Print error from dirac-dms-add-file if input LFN list file is missing. + +*RMS +FIX: (#4657) RequestDB - fix getRequestCountersWeb error in DIRACOS + [v6r22p30] *DataManagementSystem diff --git a/setup.py b/setup.py index 7fd948bdbe4..b0ba3ed35a3 100755 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ setup( name="DIRAC", - version="6.22.30", + version="6.22.31", url="https://github.com/DIRACGRID/DIRAC", license="GPLv3", package_dir=package_dir, From 412f0e96f4c0e84edb56be18b11675d25ac12ca5 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Sun, 28 Jun 2020 22:23:26 +0200 Subject: [PATCH 23/24] v7r0p28 notes and tags --- __init__.py | 2 +- release.notes | 20 ++++++++++++++++++++ setup.py | 2 +- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/__init__.py b/__init__.py index bb9f1e11b1d..a8688e90e6c 100755 --- a/__init__.py +++ b/__init__.py @@ -92,7 +92,7 @@ majorVersion = 7 minorVersion = 0 -patchLevel = 27 +patchLevel = 28 preVersion = 0 version = "v%sr%s" % (majorVersion, minorVersion) diff --git a/release.notes b/release.notes index f562299c1da..22e98094a25 100644 --- a/release.notes +++ b/release.notes @@ -1,3 +1,23 @@ +[v7r0p28] + +*Core +FIX: (#4642) M2Crypto closes the socket after dereferencing the Connection instance + +*DMS +FIX: (#4644) Cancel FTS3 Operation if the RMS request does not exist + +*RMS +NEW: (#4644) getRequestStatus returns ENOENT if the request does not exist + +*TS +FIX: (#4647) TaskManager - hospital sites were not looked for correctly, which + generated an exception +FIX: (#4656) fix parsing of command line flags (e.g., -ddd) for dirac-transformation-archive/clean/remove-output/verify-outputdata + +*Interfaces +CHANGE: (#4652) dirac-admin-add-host now inserts hosts into the ComponentMonitoring if the host + is not yet known + [v7r0p27] *Framework diff --git a/setup.py b/setup.py index 01520d128fa..34d98e9b67f 100755 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ setup( name="DIRAC", - version="7.0.27", + version="7.0.28", url="https://github.com/DIRACGRID/DIRAC", license="GPLv3", package_dir=package_dir, From 1e5b3eff7867b7b4e25871de3a954e006952eba9 Mon Sep 17 00:00:00 2001 From: Andrei Tsaregorodtsev Date: Sun, 28 Jun 2020 23:01:35 +0200 Subject: [PATCH 24/24] pep8 --- DataManagementSystem/scripts/dirac-dms-add-file.py | 1 + 1 file changed, 1 insertion(+) diff --git a/DataManagementSystem/scripts/dirac-dms-add-file.py b/DataManagementSystem/scripts/dirac-dms-add-file.py index 4c371901f49..d3ffc0eea9d 100755 --- a/DataManagementSystem/scripts/dirac-dms-add-file.py +++ b/DataManagementSystem/scripts/dirac-dms-add-file.py @@ -60,6 +60,7 @@ def getDict(item_list): lfn_dict['guid'] = guid return lfn_dict + from DIRAC.DataManagementSystem.Client.DataManager import DataManager from DIRAC import gLogger import DIRAC