예제 #1
0
 def addNotificationForUser(self, user, message, lifetime=0, deferToMail=1):
     if user not in Registry.getAllUsers():
         return S_ERROR("%s is an unknown user" % user)
     self.log.info("Adding a notification for user %s (msg is %s chars)" % (user, len(message)))
     result = self._escapeString(user)
     if not result["OK"]:
         return result
     user = result["Value"]
     result = self._escapeString(message)
     if not result["OK"]:
         return result
     message = result["Value"]
     sqlFields = ["User", "Message", "Timestamp"]
     sqlValues = [user, message, "UTC_TIMESTAMP()"]
     if not deferToMail:
         sqlFields.append("DeferToMail")
         sqlValues.append("0")
     if lifetime:
         sqlFields.append("Expiration")
         sqlValues.append("TIMESTAMPADD( SECOND, %d, UTC_TIMESTAMP() )" % int(lifetime))
     sqlInsert = "INSERT INTO `ntf_Notifications` (%s) VALUES (%s) " % (",".join(sqlFields), ",".join(sqlValues))
     result = self._update(sqlInsert)
     if not result["OK"]:
         return result
     return S_OK(result["lastRowId"])
예제 #2
0
 def getAssigneeGroupsForUser(self, user):
     if user not in Registry.getAllUsers():
         return S_ERROR("%s is an unknown user" % user)
     result = self._escapeString(user)
     if not result["OK"]:
         return result
     user = result["Value"]
     result = self._query("SELECT AssigneeGroup from `ntf_AssigneeGroups` WHERE User=%s" % user)
     if not result["OK"]:
         return result
     return S_OK([row[0] for row in result["Value"]])
예제 #3
0
 def modifyFollowerForAlarm(self,
                            alarmId,
                            user,
                            notificationsDict,
                            overwrite=True):
     rawUser = user
     if rawUser not in Registry.getAllUsers():
         return S_OK()
     result = self._escapeString(user)
     if not result["OK"]:
         return result
     user = result["Value"]
     subscriber = False
     for k in notificationsDict:
         if notificationsDict[k]:
             subscriber = True
             break
     selSQL = "SELECT Notification, Mail, SMS FROM `ntf_AlarmFollowers` WHERE AlarmId=%d AND User=%s" % (
         alarmId,
         user,
     )
     result = self._query(selSQL)
     if not result["OK"]:
         return result
     if not result["Value"]:
         if not subscriber:
             return S_OK()
         sqlValues = ["%d" % alarmId, user]
         for k in self.__validAlarmNotifications:
             if notificationsDict[k]:
                 sqlValues.append("1")
             else:
                 sqlValues.append("0")
         inSQL = (
             "INSERT INTO `ntf_AlarmFollowers` ( AlarmId, User, Notification, Mail, SMS ) VALUES (%s)"
             % ",".join(sqlValues))
         return self._update(inSQL)
     sqlCond = "AlarmId=%d AND User=%s" % (alarmId, user)
     # Need to delete
     if not subscriber:
         return self._update("DELETE FROM `ntf_AlarmFollowers` WHERE %s" %
                             sqlCond)
     if not overwrite:
         return S_OK()
     # Need to update
     modSQL = []
     for k in self.__validAlarmNotifications:
         if notificationsDict[k]:
             modSQL.append("%s=1" % k)
         else:
             modSQL.append("%s=0" % k)
     return self._update("UPDATE `ntf_AlarmFollowers` SET %s WHERE %s" %
                         (modSQL, sqlCond))
예제 #4
0
 def getUserAsignees(self, assignee):
     # Check if it is a user
     if assignee in Registry.getAllUsers():
         return S_OK([assignee])
     result = self._escapeString(assignee)
     if not result["OK"]:
         return result
     escAG = result["Value"]
     sqlSel = "SELECT User FROM `ntf_AssigneeGroups` WHERE AssigneeGroup = %s" % escAG
     result = self._query(sqlSel)
     if not result["OK"]:
         return result
     users = [row[0] for row in result["Value"]]
     if not users:
         return S_OK([])
     return S_OK(users)
예제 #5
0
 def setAssigneeGroup(self, groupName, usersList):
     validUsers = Registry.getAllUsers()
     result = self._escapeString(groupName)
     if not result['OK']:
         return result
     escGroup = result['Value']
     sqlSel = "SELECT User FROM `ntf_AssigneeGroups` WHERE AssigneeGroup = %s" % escGroup
     result = self._query(sqlSel)
     if not result['OK']:
         return result
     currentUsers = [row[0] for row in result['Value']]
     usersToDelete = []
     usersToAdd = []
     finalUsersInGroup = len(currentUsers)
     for user in currentUsers:
         if user not in usersList:
             result = self._escapeString(user)
             if not result['OK']:
                 return result
             usersToDelete.append(result['Value'])
             finalUsersInGroup -= 1
     for user in usersList:
         if user not in validUsers:
             continue
         if user not in currentUsers:
             result = self._escapeString(user)
             if not result['OK']:
                 return result
             usersToAdd.append("( %s, %s )" % (escGroup, result['Value']))
             finalUsersInGroup += 1
     if not finalUsersInGroup:
         return S_ERROR("Group must have at least one user!")
     # Delete old users
     if usersToDelete:
         sqlDel = "DELETE FROM `ntf_AssigneeGroups` WHERE User in ( %s )" % ",".join(
             usersToDelete)
         result = self._update(sqlDel)
         if not result['OK']:
             return result
     # Add new users
     if usersToAdd:
         sqlInsert = "INSERT INTO `ntf_AssigneeGroups` ( AssigneeGroup, User ) VALUES %s" % ",".join(
             usersToAdd)
         result = self._update(sqlInsert)
         if not result['OK']:
             return result
     return S_OK()
예제 #6
0
 def removeNotificationsForUser(self, user, msgIds=False):
     if user not in Registry.getAllUsers():
         return S_ERROR("%s is an unknown user" % user)
     result = self._escapeString(user)
     if not result["OK"]:
         return result
     user = result["Value"]
     delSQL = "DELETE FROM `ntf_Notifications` WHERE User=%s" % user
     escapedIDs = []
     if msgIds:
         for iD in msgIds:
             result = self._escapeString(str(iD))
             if not result["OK"]:
                 return result
             escapedIDs.append(result["Value"])
         delSQL = "%s AND Id in ( %s ) " % (delSQL, ",".join(escapedIDs))
     return self._update(delSQL)
예제 #7
0
 def markNotificationsSeen(self, user, seen=True, msgIds=False):
     if user not in Registry.getAllUsers():
         return S_ERROR("%s is an unknown user" % user)
     result = self._escapeString(user)
     if not result["OK"]:
         return result
     user = result["Value"]
     if seen:
         seen = 1
     else:
         seen = 0
     updateSQL = "UPDATE `ntf_Notifications` SET Seen=%d WHERE User=%s" % (seen, user)
     escapedIDs = []
     if msgIds:
         for iD in msgIds:
             result = self._escapeString(str(iD))
             if not result["OK"]:
                 return result
             escapedIDs.append(result["Value"])
         updateSQL = "%s AND Id in ( %s ) " % (updateSQL, ",".join(escapedIDs))
     return self._update(updateSQL)
def main():
    global userName
    Script.registerSwitch("u:", "user="******"User to query (by default oneself)", setUser)
    Script.parseCommandLine()

    result = getProxyInfo()
    if not result["OK"]:
        gLogger.notice("Do you have a valid proxy?")
        gLogger.notice(result["Message"])
        sys.exit(1)
    proxyProps = result["Value"]

    userName = userName or proxyProps.get("username")
    if not userName:
        gLogger.notice("Your proxy don`t have username extension")
        sys.exit(1)

    if userName in Registry.getAllUsers():
        if Properties.PROXY_MANAGEMENT not in proxyProps["groupProperties"]:
            if userName != proxyProps["username"] and userName != proxyProps["issuer"]:
                gLogger.notice("You can only query info about yourself!")
                sys.exit(1)
        result = Registry.getDNForUsername(userName)
        if not result["OK"]:
            gLogger.notice("Oops %s" % result["Message"])
        dnList = result["Value"]
        if not dnList:
            gLogger.notice("User %s has no DN defined!" % userName)
            sys.exit(1)
        userDNs = dnList
    else:
        userDNs = [userName]

    gLogger.notice("Checking for DNs %s" % " | ".join(userDNs))
    pmc = ProxyManagerClient()
    result = pmc.getDBContents({"UserDN": userDNs})
    if not result["OK"]:
        gLogger.notice("Could not retrieve the proxy list: %s" % result["Value"])
        sys.exit(1)

    data = result["Value"]
    colLengths = []
    for pN in data["ParameterNames"]:
        colLengths.append(len(pN))
    for row in data["Records"]:
        for i in range(len(row)):
            colLengths[i] = max(colLengths[i], len(str(row[i])))

    lines = [""]
    for i in range(len(data["ParameterNames"])):
        pN = data["ParameterNames"][i]
        lines[0] += "| %s " % pN.ljust(colLengths[i])
    lines[0] += "|"
    tL = len(lines[0])
    lines.insert(0, "-" * tL)
    lines.append("-" * tL)
    for row in data["Records"]:
        nL = ""
        for i in range(len(row)):
            nL += "| %s " % str(row[i]).ljust(colLengths[i])
        nL += "|"
        lines.append(nL)
        lines.append("-" * tL)

    gLogger.notice("\n".join(lines))
예제 #9
0
 def updateAlarm(self, updateReq):
     # Discover alarm identification
     idOK = False
     for field in self.__updateAlarmIdentificationFields:
         if field in updateReq:
             idOK = True
     if not idOK:
         return S_ERROR(
             "Need at least one field to identify which alarm to update! %s" % self.__updateAlarmIdentificationFields
         )
     if "alarmKey" in updateReq:
         alarmKey = updateReq["alarmKey"]
         result = self.__getAlarmIdFromKey(alarmKey)
         if not result["OK"]:
             self.log.error("Could not get alarm id for key", " %s: %s" % (alarmKey, result["Value"]))
             return result
         updateReq["id"] = result["Value"]
         self.log.info("Retrieving alarm key %s maps to id %s" % (alarmKey, updateReq["id"]))
     # Check fields
     for field in self.__updateAlarmMandatoryFields:
         if field not in updateReq:
             return S_ERROR("Oops. Missing %s" % field)
     validReq = False
     for field in self.__updateAlarmAtLeastOneField:
         if field in updateReq:
             validReq = True
     if not validReq:
         return S_OK("Requirement needs at least one of %s" % " ".join(self.__updateAlarmAtLeastOneField))
     author = updateReq["author"]
     followers = [author]
     if author not in Registry.getAllUsers():
         return S_ERROR("%s is not a known user" % author)
     result = self._escapeString(author)
     if not result["OK"]:
         return result
     author = result["Value"]
     try:
         alarmId = int(updateReq["id"])
     except Exception:
         return S_ERROR("Oops, Alarm id is not valid!")
     result = self._query("SELECT AlarmId FROM `ntf_Alarms` WHERE AlarmId=%d" % alarmId)
     if not result["OK"]:
         return result
     if not result["Value"]:
         return S_ERROR("Alarm %s does not exist!" % alarmId)
     sqlFields = ["AlarmId", "Author", "Timestamp"]
     sqlValues = ["%d" % alarmId, author, "UTC_TIMESTAMP()"]
     rawComment = ""
     if "comment" in updateReq:
         rawComment = updateReq["comment"]
         result = self._escapeString(rawComment)
         if not result["OK"]:
             return result
         sqlFields.append("Comment")
         sqlValues.append(result["Value"])
     modifications = False
     if "modifications" in updateReq:
         modifications = updateReq["modifications"]
         result = self.__processUpdateAlarmModifications(modifications)
         if not result["OK"]:
             return result
         alarmModsSQL, encodedMods, newFollowers = result["Value"]
         sqlFields.append("Modifications")
         result = self._escapeString(encodedMods)
         if not result["OK"]:
             return result
         sqlValues.append(result["Value"])
         if newFollowers:
             followers.extend(newFollowers)
     logSQL = "INSERT INTO `ntf_AlarmLog` (%s) VALUES (%s)" % (",".join(sqlFields), ",".join(sqlValues))
     result = self._update(logSQL)
     if not result["OK"]:
         return result
     modSQL = "ModTime=UTC_TIMESTAMP()"
     if modifications:
         modSQL = "%s, %s" % (modSQL, alarmModsSQL)
     updateSQL = "UPDATE `ntf_Alarms` SET %s WHERE AlarmId=%d" % (modSQL, alarmId)
     result = self._update(updateSQL)
     if not result["OK"]:
         return result
     # Get notifications config
     sqlQuery = "SELECT Notifications FROM `ntf_Alarms` WHERE AlarmId=%s" % alarmId
     result = self._query(sqlQuery)
     if not result["OK"] or not result["Value"]:
         self.log.error("Could not retrieve default notifications for alarm", "%s" % alarmId)
         return S_OK(alarmId)
     notificationsDict = DEncode.decode(result["Value"][0][0])[0]
     for v in self.__validAlarmNotifications:
         if v not in notificationsDict:
             notificationsDict[v] = 0
     for follower in followers:
         result = self.modifyFollowerForAlarm(alarmId, follower, notificationsDict, overwrite=False)
         if not result["OK"]:
             varMsg = "\nFollower: %s\nAlarm: %s\nError: %s" % (follower, alarmId, result["Message"])
             self.log.error("Couldn't set follower for alarm", varMsg)
     return self.__notifyAlarm(alarmId)
Script.parseCommandLine()

result = getProxyInfo()
if not result['OK']:
  gLogger.notice("Do you have a valid proxy?")
  gLogger.notice(result['Message'])
  sys.exit(1)
proxyProps = result['Value']

userName = userName or proxyProps.get('username')
if not userName:
  gLogger.notice("Your proxy don`t have username extension")
  sys.exit(1)

if userName in Registry.getAllUsers():
  if Properties.PROXY_MANAGEMENT not in proxyProps['groupProperties']:
    if userName != proxyProps['username'] and userName != proxyProps['issuer']:
      gLogger.notice("You can only query info about yourself!")
      sys.exit(1)
  result = Registry.getDNForUsername(userName)
  if not result['OK']:
    gLogger.notice("Oops %s" % result['Message'])
  dnList = result['Value']
  if not dnList:
    gLogger.notice("User %s has no DN defined!" % userName)
    sys.exit(1)
  userDNs = dnList
else:
  userDNs = [userName]