Beispiel #1
0
def main():
  Script.parseCommandLine(ignoreErrors=True)
  args = Script.getPositionalArgs()

  if len(args) < 1:
    Script.showHelp()

  from DIRAC import exit as DIRACExit
  from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
  diracAdmin = DiracAdmin()
  exitCode = 0
  errorList = []

  for gridID in args:

    result = diracAdmin.getPilotLoggingInfo(gridID)
    if not result['OK']:
      errorList.append((gridID, result['Message']))
      exitCode = 2
    else:
      print('Pilot Reference: %s', gridID)
      print(result['Value'])
      print()

  for error in errorList:
    print("ERROR %s: %s" % error)

  DIRACExit(exitCode)
Beispiel #2
0
    def initialize(self):
        ''' NotifyAgent initialization
    '''

        try:
            with sqlite3.connect(self.cacheFile) as conn:
                conn.execute(
                    '''CREATE TABLE IF NOT EXISTS ProductionManagementCache(
                      reqId VARCHAR(64) NOT NULL DEFAULT "",
                      reqType VARCHAR(64) NOT NULL DEFAULT "",
                      reqWG VARCHAR(64) NOT NULL DEFAULT "",
                      reqName VARCHAR(64) NOT NULL DEFAULT "",
                      SimCondition VARCHAR(64) NOT NULL DEFAULT "",
                      ProPath VARCHAR(64) NOT NULL DEFAULT "",
                      thegroup VARCHAR(64) NOT NULL DEFAULT "",
                      reqInform VARCHAR(64) NOT NULL DEFAULT ""
                     );''')
        except sqlite3.OperationalError:
            self.log.error('Email cache database is locked')

        self.diracAdmin = DiracAdmin()

        self.csS = PathFinder.getServiceSection(
            'ProductionManagement/ProductionRequest')

        self.fromAddress = gConfig.getValue('%s/fromAddress' % self.csS, '')
        if not self.fromAddress:
            self.log.info(
                'No fromAddress is defined, a default value will be used instead'
            )
            self.fromAddress = '*****@*****.**'

        return S_OK()
def main():
    Script.registerSwitch("e", "extended", "Show extended info")

    Script.parseCommandLine(ignoreErrors=True)
    args = Script.getPositionalArgs()

    from DIRAC import exit as DIRACExit
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []
    extendedInfo = False

    for unprocSw in Script.getUnprocessedSwitches():
        if unprocSw[0] in ('e', 'extended'):
            extendedInfo = True

    if not extendedInfo:
        result = diracAdmin.csListHosts()
        for host in result['Value']:
            print(" %s" % host)
    else:
        result = diracAdmin.csDescribeHosts()
        print(diracAdmin.pPrint.pformat(result['Value']))

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRACExit(exitCode)
Beispiel #4
0
  def initialize( self ):
    """ Standard constructor
    """

    try:
      self.rsDB = ResourceStatusDB()
      self.rmDB = ResourceManagementDB()

      self.StorageElementToBeChecked = Queue.Queue()
      self.StorageElementInCheck     = []

      self.maxNumberOfThreads = self.am_getOption( 'maxThreadsInPool', 1 )
      self.threadPool         = ThreadPool( self.maxNumberOfThreads,
                                            self.maxNumberOfThreads )

      if not self.threadPool:
        self.log.error( 'Can not create Thread Pool' )
        return S_ERROR( 'Can not create Thread Pool' )

      self.setup                = getSetup()[ 'Value' ]
      self.VOExtension          = getExt()
      self.StorageElsWriteFreqs = CheckingFreqs[ 'StorageElsWriteFreqs' ]
      self.nc                   = NotificationClient()
      self.diracAdmin           = DiracAdmin()
      self.csAPI                = CSAPI()

      for _i in xrange( self.maxNumberOfThreads ):
        self.threadPool.generateJobAndQueueIt( self._executeCheck, args = ( None, ) )

      return S_OK()

    except Exception:
      errorStr = "StElWriteInspectorAgent initialization"
      gLogger.exception( errorStr )
      return S_ERROR( errorStr )
def main():
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["User:     User name"])
    # parseCommandLine show help when mandatory arguments are not specified or incorrect argument
    _, args = Script.parseCommandLine(ignoreErrors=True)

    from DIRAC import exit as DIRACExit
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    choice = input("Are you sure you want to delete user/s %s? yes/no [no]: " %
                   ", ".join(args))
    choice = choice.lower()
    if choice not in ("yes", "y"):
        print("Delete aborted")
        DIRACExit(0)

    for user in args:
        if not diracAdmin.csDeleteUser(user):
            errorList.append(("delete user", "Cannot delete user %s" % user))
            exitCode = 255

    if not exitCode:
        result = diracAdmin.csCommitChanges()
        if not result["OK"]:
            errorList.append(("commit", result["Message"]))
            exitCode = 255

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRACExit(exitCode)
Beispiel #6
0
    def initialize(self):
        ''' EmailAgent initialization
    '''

        self.diracAdmin = DiracAdmin()

        return S_OK()
Beispiel #7
0
def getInfo(params):
    '''
    Retrieve information from BDII
  '''

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()

    if params['info'] == 'ce':
        result = diracAdmin.getBDIICE(params['ce'], host=params['host'])
    if params['info'] == 'ce-state':
        result = diracAdmin.getBDIICEState(params['ce'],
                                           useVO=params['vo'],
                                           host=params['host'])
    if params['info'] == 'ce-cluster':
        result = diracAdmin.getBDIICluster(params['ce'], host=params['host'])
    if params['info'] == 'ce-vo':
        result = diracAdmin.getBDIICEVOView(params['ce'],
                                            useVO=params['vo'],
                                            host=params['host'])
    if params['info'] == 'site':
        result = diracAdmin.getBDIISite(params['site'], host=params['host'])
    if params['info'] == 'site-se':
        result = diracAdmin.getBDIISE(params['site'],
                                      useVO=params['vo'],
                                      host=params['host'])

    if not result['OK']:
        print result['Message']
        DIRAC.exit(2)

    return result
Beispiel #8
0
def main():
    Script.parseCommandLine(ignoreErrors=True)

    args = Script.getPositionalArgs()

    if len(args) < 1:
        Script.showHelp()

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    for job in args:

        try:
            job = int(job)
        except Exception as x:
            errorList.append(('Expected integer for jobID', job))
            exitCode = 2
            continue

        result = diracAdmin.resetJob(job)
        if result['OK']:
            print('Reset Job %s' % (job))
        else:
            errorList.append((job, result['Message']))
            exitCode = 2

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)
def main():
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["JobID:    DIRAC ID of the Job"])
    # parseCommandLine show help when mandatory arguments are not specified or incorrect argument
    _, args = Script.parseCommandLine(ignoreErrors=True)

    from DIRAC import exit as DIRACExit
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    for job in args:

        try:
            job = int(job)
        except Exception:
            errorList.append(("Expected integer for JobID", job))
            exitCode = 2
            continue

        result = diracAdmin.getJobPilotOutput(job)
        if not result["OK"]:
            errorList.append((job, result["Message"]))
            exitCode = 2

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRACExit(exitCode)
def main():
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["PilotID:  Grid ID of the pilot"])
    # parseCommandLine show help when mandatory arguments are not specified or incorrect argument
    _, args = Script.parseCommandLine(ignoreErrors=True)

    from DIRAC import exit as DIRACExit
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    for gridID in args:

        result = diracAdmin.getPilotLoggingInfo(gridID)
        if not result["OK"]:
            errorList.append((gridID, result["Message"]))
            exitCode = 2
        else:
            print("Pilot Reference: %s", gridID)
            print(result["Value"])
            print()

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRACExit(exitCode)
Beispiel #11
0
def main():
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["JobID:    DIRAC Job IDs"])
    _, args = Script.parseCommandLine(ignoreErrors=True)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    for job in args:

        try:
            job = int(job)
        except Exception as x:
            errorList.append(("Expected integer for jobID", job))
            exitCode = 2
            continue

        result = diracAdmin.resetJob(job)
        if result["OK"]:
            print("Reset Job %s" % (job))
        else:
            errorList.append((job, result["Message"]))
            exitCode = 2

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)
def main():
    Script.registerSwitch(
        "", "Site=", "Site for which protocols are to be set (mandatory)")
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["Protocol: SE access protocol"], mandatory=False)
    switches, args = Script.parseCommandLine(ignoreErrors=True)

    site = None
    for switch in switches:
        if switch[0].lower() == "site":
            site = switch[1]

    if not site or not args:
        Script.showHelp(exitCode=1)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    result = diracAdmin.setSiteProtocols(site, args, printOutput=True)
    if not result["OK"]:
        print("ERROR: %s" % result["Message"])
        exitCode = 2

    DIRAC.exit(exitCode)
Beispiel #13
0
    def initialize(self, *args, **kwargs):
        """ EmailAgent initialization
    """

        self.diracAdmin = DiracAdmin()

        return S_OK()
Beispiel #14
0
def main():
    global userName
    global userDN
    global userMail
    global userGroups
    Script.registerSwitch('N:', 'UserName:'******'Short Name of the User (Mandatory)', setUserName)
    Script.registerSwitch('D:', 'UserDN:',
                          'DN of the User Certificate (Mandatory)', setUserDN)
    Script.registerSwitch('M:', 'UserMail:', 'eMail of the user (Mandatory)',
                          setUserMail)
    Script.registerSwitch(
        'G:', 'UserGroup:',
        'Name of the Group for the User (Allow Multiple instances or None)',
        addUserGroup)

    Script.parseCommandLine(ignoreErrors=True)

    if userName is None or userDN is None or userMail is None:
        Script.showHelp(exitCode=1)

    args = Script.getPositionalArgs()

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    userProps = {'DN': userDN, 'Email': userMail}
    if userGroups:
        userProps['Groups'] = userGroups
    for prop in args:
        pl = prop.split("=")
        if len(pl) < 2:
            errorList.append(
                ("in arguments",
                 "Property %s has to include a '=' to separate name from value"
                 % prop))
            exitCode = 255
        else:
            pName = pl[0]
            pValue = "=".join(pl[1:])
            Script.gLogger.info("Setting property %s to %s" % (pName, pValue))
            userProps[pName] = pValue

    if not diracAdmin.csModifyUser(
            userName, userProps, createIfNonExistant=True)['OK']:
        errorList.append(("add user", "Cannot register user %s" % userName))
        exitCode = 255
    else:
        result = diracAdmin.csCommitChanges()
        if not result['OK']:
            errorList.append(("commit", result['Message']))
            exitCode = 255

    for error in errorList:
        Script.gLogger.error("%s: %s" % error)

    DIRAC.exit(exitCode)
    def execute(self):
        """ Get all New tags, mark them as Installing. Old Installing tags are reset to New 
    """
        #### get site mask ###
        diracAdmin = DiracAdmin()
        res = diracAdmin.getSiteMask(printOutput=False)
        if not res["OK"]:
            self.log.error("error retrieving site mask: %s" %
                           str(res["Message"]))
        site_mask = res["Value"]
        res = self.swtc.getTagsWithStatus("New")
        if not res['OK']:
            return res
        if not res['Value']:
            self.log.info("No 'New' tags to consider")

        for tag, ces in res['Value'].items():
            for ce in ces:
                res = getSiteForCEs([ce])
                if not res["OK"]:
                    self.log.error("could not retrieve Site name for CE %s" %
                                   ce)
                sites = res["Value"].keys()
                for site in sites:
                    if site not in site_mask:
                        self.log.info("CE/Site disabled %s" % site)
                        continue
                        # ignore this CE
                res = self.swtc.updateCEStatus(tag, ce, 'Installing')
                if not res['OK']:
                    self.log.error(res['Message'])
                    continue
                res = None

                if self.submitjobs:
                    res = self.submitProbeJobs(ce)
                else:
                    res = self.swtc.updateCEStatus(tag, ce, 'Valid')

                if not res['OK']:
                    self.log.error(res['Message'])
                else:
                    self.log.info("Done with %s at %s" % (tag, ce))

        ##Also, reset to New tags that were in Probing for too long.
        res = self.swtc.getTagsWithStatus("Installing", self.delay)
        if not res['OK']:
            self.log.error("Failed to get old 'Installing' tags")
        else:
            if not res['Value']:
                self.log.info("No 'Installing' tags to reset")

            for tag, ces in res['Value'].items():
                for ce in ces:
                    res = self.swtc.updateCEStatus(tag, ce, 'New')
                    if not res['OK']:
                        self.log.error(res['Message'])
                        continue
        return S_OK()
Beispiel #16
0
def main():
    """reads in the options and deletes the matching pilots"""
    options = Params()
    options.registerCLISwitches()
    Script.parseCommandLine(ignoreErrors=True)
    # make sure *something* is set
    if not options.site and not options.ce and not options.vo and not options.status:
        print(
            "You must chose at least one of the following options: --vo, --ce --site"
        )

    # occasionally the same job might appear twice, but that shouldn't matter
    conditions = {}
    if options.status:
        conditions["Status"] = options.status[0]
    else:
        conditions["Status"] = ["Submitted", "Scheduled", "Waiting", "Unknown"]

    if options.site:
        conditions["GridSite"] = options.site

    if options.ce:
        conditions["DestinationSite"] = options.ce

    if options.vo:
        pilotstring = options.vo + "_pilot"
        conditions["OwnerGroup"] = pilotstring

    # conditions = {"Status":"Submitted", "GridSite":"LCG.UKI-LT2-IC-HEP.uk",
    #               "OwnerGroup":["lz_pilot", "gridpp_pilot"], "DestinationSite":"ceprod00.grid.hep.ph.ic.ac.uk"}
    print("Selecting pilots fulfulling the following conditions: %s" %
          conditions)

    pilotmanager = PilotManagerClient()
    result = pilotmanager.selectPilots(conditions)

    if not result['Value']:
        print("No pilots matching these criteria were found.")
        sys.exit(0)

    print("Found the following matching pilots:")
    for pilotRef in result['Value']:
        print(pilotRef)

    if options.dryrun:
        print("Dry run only. No pilots will be deleted")
        sys.exit(0)

    # now get the pilot references and delete them

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()

    for pilotRef in result['Value']:
        result = diracAdmin.killPilot(pilotRef)
        if not result['OK']:
            print("Error encountered when deleting pilot %s" % pilotRef)
            print(result)
Beispiel #17
0
def main():
  global groupName
  global groupProperties
  global userNames
  Script.registerSwitch('G:', 'GroupName:', 'Name of the Group (Mandatory)', setGroupName)
  Script.registerSwitch(
      'U:',
      'UserName:'******'Short Name of user to be added to the Group (Allow Multiple instances or None)',
      addUserName)
  Script.registerSwitch(
      'P:',
      'Property:',
      'Property to be added to the Group (Allow Multiple instances or None)',
      addProperty)

  Script.parseCommandLine(ignoreErrors=True)

  if groupName is None:
    Script.showHelp(exitCode=1)

  args = Script.getPositionalArgs()

  from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
  diracAdmin = DiracAdmin()
  exitCode = 0
  errorList = []

  groupProps = {}
  if userNames:
    groupProps['Users'] = ', '.join(userNames)
  if groupProperties:
    groupProps['Properties'] = ', '.join(groupProperties)

  for prop in args:
    pl = prop.split("=")
    if len(pl) < 2:
      errorList.append(("in arguments", "Property %s has to include a '=' to separate name from value" % prop))
      exitCode = 255
    else:
      pName = pl[0]
      pValue = "=".join(pl[1:])
      Script.gLogger.info("Setting property %s to %s" % (pName, pValue))
      groupProps[pName] = pValue

  if not diracAdmin.csModifyGroup(groupName, groupProps, createIfNonExistant=True)['OK']:
    errorList.append(("add group", "Cannot register group %s" % groupName))
    exitCode = 255
  else:
    result = diracAdmin.csCommitChanges()
    if not result['OK']:
      errorList.append(("commit", result['Message']))
      exitCode = 255

  for error in errorList:
    Script.gLogger.error("%s: %s" % error)

  DIRAC.exit(exitCode)
def main():
    global groupName
    global groupProperties
    global userNames
    Script.registerSwitch("G:", "GroupName:", "Name of the Group (Mandatory)", setGroupName)
    Script.registerSwitch(
        "U:", "UserName:"******"Short Name of user to be added to the Group (Allow Multiple instances or None)", addUserName
    )
    Script.registerSwitch(
        "P:", "Property:", "Property to be added to the Group (Allow Multiple instances or None)", addProperty
    )
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(
        ["Property=<Value>: Other properties to be added to the Group like (VOMSRole=XXXX)"], mandatory=False
    )

    _, args = Script.parseCommandLine(ignoreErrors=True)

    if groupName is None:
        Script.showHelp(exitCode=1)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    groupProps = {}
    if userNames:
        groupProps["Users"] = ", ".join(userNames)
    if groupProperties:
        groupProps["Properties"] = ", ".join(groupProperties)

    for prop in args:
        pl = prop.split("=")
        if len(pl) < 2:
            errorList.append(("in arguments", "Property %s has to include a '=' to separate name from value" % prop))
            exitCode = 255
        else:
            pName = pl[0]
            pValue = "=".join(pl[1:])
            gLogger.info("Setting property %s to %s" % (pName, pValue))
            groupProps[pName] = pValue

    if not diracAdmin.csModifyGroup(groupName, groupProps, createIfNonExistant=True)["OK"]:
        errorList.append(("add group", "Cannot register group %s" % groupName))
        exitCode = 255
    else:
        result = diracAdmin.csCommitChanges()
        if not result["OK"]:
            errorList.append(("commit", result["Message"]))
            exitCode = 255

    for error in errorList:
        gLogger.error("%s: %s" % error)

    DIRAC.exit(exitCode)
Beispiel #19
0
def getJobPilotOutput(id, dir):
    pwd = os.getcwd()
    try:
        os.chdir(dir)
        os.system('rm -f pilot_%d/std.out' % id)
        os.system('rmdir pilot_%d' % id)
        result = DiracAdmin().getJobPilotOutput(id)
    finally:
        os.chdir(pwd)
    output(result)
Beispiel #20
0
    def initialize(self):
        """TokenAgent initialization"""

        self.notifyHours = self.am_getOption("notifyHours", self.notifyHours)
        self.adminMail = self.am_getOption("adminMail", self.adminMail)

        self.rsClient = ResourceStatusClient()
        self.diracAdmin = DiracAdmin()

        return S_OK()
Beispiel #21
0
def main():
    Script.registerSwitch("e", "extended", "Show extended info")
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(
        ["Group:    Only users from this group (default: all)"],
        default=["all"],
        mandatory=False)
    Script.parseCommandLine(ignoreErrors=True)
    args = Script.getPositionalArgs(group=True)

    import DIRAC
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []
    extendedInfo = False

    for unprocSw in Script.getUnprocessedSwitches():
        if unprocSw[0] in ("e", "extended"):
            extendedInfo = True

    def printUsersInGroup(group=False):
        result = diracAdmin.csListUsers(group)
        if result["OK"]:
            if group:
                print("Users in group %s:" % group)
            else:
                print("All users registered:")
            for username in result["Value"]:
                print(" %s" % username)

    def describeUsersInGroup(group=False):
        result = diracAdmin.csListUsers(group)
        if result["OK"]:
            if group:
                print("Users in group %s:" % group)
            else:
                print("All users registered:")
            result = diracAdmin.csDescribeUsers(result["Value"])
            print(diracAdmin.pPrint.pformat(result["Value"]))

    for group in args:
        if "all" in args:
            group = False
        if not extendedInfo:
            printUsersInGroup(group)
        else:
            describeUsersInGroup(group)

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)
Beispiel #22
0
  def initialize( self ):
    """Sets defaults
    """

    self.am_setOption( 'PollingTime', 120 )
    self.am_setOption( 'GridEnv', '' )
    self.am_setOption( 'PilotStalledDays', 3 )
    self.pilotDB = PilotAgentsDB()
    self.diracadmin = DiracAdmin()
    self.jobDB = JobDB()
    return S_OK()
Beispiel #23
0
  def initialize( self ):
    ''' TokenAgent initialization
    '''

    self.notifyHours = self.am_getOption( 'notifyHours', self.notifyHours )
    self.adminMail   = self.am_getOption( 'adminMail', self.adminMail )

    self.rsClient = ResourceStatusClient()
    self.diracAdmin = DiracAdmin()

    return S_OK()
Beispiel #24
0
    def __init__(self,
                 name,
                 decissionParams,
                 enforcementResult,
                 singlePolicyResults,
                 clients=None):

        super(EmailAction,
              self).__init__(name, decissionParams, enforcementResult,
                             singlePolicyResults, clients)
        self.diracAdmin = DiracAdmin()
def main():
    Script.registerSwitch("p:", "property=",
                          "Add property to the user <name>=<value>")
    Script.registerSwitch("f", "force", "create the user if it doesn't exist")
    Script.parseCommandLine(ignoreErrors=True)

    args = Script.getPositionalArgs()

    if len(args) < 3:
        Script.showHelp(exitCode=1)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    exitCode = 0
    forceCreation = False
    errorList = []

    userProps = {}
    for unprocSw in Script.getUnprocessedSwitches():
        if unprocSw[0] in ("f", "force"):
            forceCreation = True
        elif unprocSw[0] in ("p", "property"):
            prop = unprocSw[1]
            pl = prop.split("=")
            if len(pl) < 2:
                errorList.append((
                    "in arguments",
                    "Property %s has to include a '=' to separate name from value"
                    % prop))
                exitCode = 255
            else:
                pName = pl[0]
                pValue = "=".join(pl[1:])
                print("Setting property %s to %s" % (pName, pValue))
                userProps[pName] = pValue

    userName = args[0]
    userProps['DN'] = args[1]
    userProps['Groups'] = args[2:]

    if not diracAdmin.csModifyUser(
            userName, userProps, createIfNonExistant=forceCreation):
        errorList.append(("modify user", "Cannot modify user %s" % userName))
        exitCode = 255
    else:
        result = diracAdmin.csCommitChanges()
        if not result['OK']:
            errorList.append(("commit", result['Message']))
            exitCode = 255

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)
Beispiel #26
0
def main():
    global userName
    global userDN
    global userMail
    global userGroups
    Script.registerSwitch("N:", "UserName:"******"Short Name of the User (Mandatory)", setUserName)
    Script.registerSwitch("D:", "UserDN:", "DN of the User Certificate (Mandatory)", setUserDN)
    Script.registerSwitch("M:", "UserMail:", "eMail of the user (Mandatory)", setUserMail)
    Script.registerSwitch(
        "G:", "UserGroup:", "Name of the Group for the User (Allow Multiple instances or None)", addUserGroup
    )
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(["Property=<Value>: Properties to be added to the User like (Phone=XXXX)"], mandatory=False)
    Script.parseCommandLine(ignoreErrors=True)

    if userName is None or userDN is None or userMail is None:
        Script.showHelp(exitCode=1)

    args = Script.getPositionalArgs()

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []

    userProps = {"DN": userDN, "Email": userMail}
    if userGroups:
        userProps["Groups"] = userGroups
    for prop in args:
        pl = prop.split("=")
        if len(pl) < 2:
            errorList.append(("in arguments", "Property %s has to include a '=' to separate name from value" % prop))
            exitCode = 255
        else:
            pName = pl[0]
            pValue = "=".join(pl[1:])
            gLogger.info("Setting property %s to %s" % (pName, pValue))
            userProps[pName] = pValue

    if not diracAdmin.csModifyUser(userName, userProps, createIfNonExistant=True)["OK"]:
        errorList.append(("add user", "Cannot register user %s" % userName))
        exitCode = 255
    else:
        result = diracAdmin.csCommitChanges()
        if not result["OK"]:
            errorList.append(("commit", result["Message"]))
            exitCode = 255

    for error in errorList:
        gLogger.error("%s: %s" % error)

    DIRAC.exit(exitCode)
def main():
    Script.registerSwitch("p:", "property=",
                          "Add property to the user <name>=<value>")
    Script.registerSwitch("f", "force", "create the user if it doesn't exist")
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument(" user:     User name")
    Script.registerArgument(" DN:       DN of the User")
    Script.registerArgument(["group:    Add the user to the group"])
    Script.parseCommandLine(ignoreErrors=True)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()
    exitCode = 0
    forceCreation = False
    errorList = []

    userProps = {}
    for unprocSw in Script.getUnprocessedSwitches():
        if unprocSw[0] in ("f", "force"):
            forceCreation = True
        elif unprocSw[0] in ("p", "property"):
            prop = unprocSw[1]
            pl = prop.split("=")
            if len(pl) < 2:
                errorList.append((
                    "in arguments",
                    "Property %s has to include a '=' to separate name from value"
                    % prop))
                exitCode = 255
            else:
                pName = pl[0]
                pValue = "=".join(pl[1:])
                print("Setting property %s to %s" % (pName, pValue))
                userProps[pName] = pValue

    userName, userProps["DN"], userProps["Groups"] = Script.getPositionalArgs(
        group=True)

    if not diracAdmin.csModifyUser(
            userName, userProps, createIfNonExistant=forceCreation):
        errorList.append(("modify user", "Cannot modify user %s" % userName))
        exitCode = 255
    else:
        result = diracAdmin.csCommitChanges()
        if not result["OK"]:
            errorList.append(("commit", result["Message"]))
            exitCode = 255

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)
Beispiel #28
0
    def initialize(self):
        """Sets defaults"""

        self.am_setOption("GridEnv", "")
        self.pilotDB = PilotAgentsDB()
        self.diracadmin = DiracAdmin()
        self.jobDB = JobDB()
        self.clearPilotsDelay = self.am_getOption("ClearPilotsDelay", 30)
        self.clearAbortedDelay = self.am_getOption("ClearAbortedPilotsDelay",
                                                   7)
        self.pilots = PilotManagerClient()

        return S_OK()
def main():
    Script.parseCommandLine(ignoreErrors=True)

    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin

    diracAdmin = DiracAdmin()

    result = diracAdmin.getPilotSummary()
    if result["OK"]:
        DIRAC.exit(0)
    else:
        print(result["Message"])
        DIRAC.exit(2)
Beispiel #30
0
def main():
    Script.registerSwitch("e", "extended", "Show extended info")
    Script.parseCommandLine(ignoreErrors=True)
    args = Script.getPositionalArgs()

    if len(args) == 0:
        args = ['all']

    import DIRAC
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    exitCode = 0
    errorList = []
    extendedInfo = False

    for unprocSw in Script.getUnprocessedSwitches():
        if unprocSw[0] in ('e', 'extended'):
            extendedInfo = True

    def printUsersInGroup(group=False):
        result = diracAdmin.csListUsers(group)
        if result['OK']:
            if group:
                print("Users in group %s:" % group)
            else:
                print("All users registered:")
            for username in result['Value']:
                print(" %s" % username)

    def describeUsersInGroup(group=False):
        result = diracAdmin.csListUsers(group)
        if result['OK']:
            if group:
                print("Users in group %s:" % group)
            else:
                print("All users registered:")
            result = diracAdmin.csDescribeUsers(result['Value'])
            print(diracAdmin.pPrint.pformat(result['Value']))

    for group in args:
        if 'all' in args:
            group = False
        if not extendedInfo:
            printUsersInGroup(group)
        else:
            describeUsersInGroup(group)

    for error in errorList:
        print("ERROR %s: %s" % error)

    DIRAC.exit(exitCode)