def _processModificationError(self, e): """Treats modification errors occured during the process of a RH.""" Logger.get('requestHandler').info('Request %s finished with ModificationError: "%s"' % (request, e)) p=errors.WPModificationError(self) return p.display()
def process(req): responseBody = {"version": "1.1", "error": None, "result": None} requestBody = None try: # check content type (if the users know what they are using) #if req.content_type != "application/json": # raise RequestError("Invalid content type. It must be 'application/json'.") # read request requestText = req.read() Logger.get('rpc').debug('json rpc request. request text= ' + str(requestText)) if requestText == "": raise RequestError("ERR-R2", "Empty request.") # decode json try: requestBody = decode(requestText) except Exception, e: raise RequestError("ERR-R3", "Error parsing json request.", e) if "id" in requestBody: responseBody["id"] = requestBody["id"] result = invokeMethod(str(requestBody["method"]), requestBody.get("params", []), req) # serialize result try: responseBody["result"] = result except Exception, e: raise ProcessError("ERR-P1", "Error during serialization.")
def _sendMail(self, operation): """ Overloads _sendMail behavior for EVO """ if operation == 'new': #notification to admin try: notification = notifications.NewVidyoPublicRoomNotificationAdmin( self) GenericMailer.sendAndLog( notification, self.getConference(), "MaKaC/plugins/Collaboration/Vidyo/collaboration.py", self.getConference().getCreator()) except Exception, e: Logger.get('Vidyo').error( """Could not send NewVidyoPublicRoomNotificationAdmin for booking with id %s of event with id %s, exception: %s""" % (self.getId(), self.getConference().getId(), str(e))) #notification to owner if isinstance(self.getOwnerObject(), Avatar): try: notification = notifications.VidyoOwnerChosenNotification( self) GenericMailer.sendAndLog( notification, self.getConference(), "MaKaC/plugins/Collaboration/Vidyo/collaboration.py", self.getConference().getCreator()) except Exception, e: Logger.get('Vidyo').error( """Could not send VidyoOwnerChosenNotification for booking with id %s of event with id %s, exception: %s""" % (self.getId(), self.getConference().getId(), str(e)))
def _cacheNextStartingRecord(self, queryHash, page, record, obj): data = obj or {} data[self._page + 1] = record + 1 Logger.get("search").debug("set page: %s" % data) GenericCache('Search').set((self._sessionHash, queryHash), data, 12 * 3600)
def strip_ml_tags(in_text): """ Description: Removes all HTML/XML-like tags from the input text. Inputs: s --> string of text Outputs: text string without the tags # doctest unit testing framework >>> test_text = "Keep this Text <remove><me /> KEEP </remove> 123" >>> strip_ml_tags(test_text) 'Keep this Text KEEP 123' """ # convert in_text to a mutable object (e.g. list) s_list = list(in_text) i = 0 while i < len(s_list): # iterate until a left-angle bracket is found if s_list[i] == '<': try: while s_list[i] != '>': # pop everything from the the left-angle bracket until the right-angle bracket s_list.pop(i) except IndexError,e: Logger.get('strip_ml_tags').debug("Not found '>' (the end of the html tag): %s"%e) continue # pops the right-angle bracket, too s_list.pop(i) else: i=i+1
def getInstance(cls, userAPIUrl=None, username=None, password=None): if cls._instance is None or (userAPIUrl is not None or username is not None or password is not None): if userAPIUrl is None: userAPIUrl = getVidyoOptionValue('userAPIURL') if username is None: username = getVidyoOptionValue('indicoUsername') if password is None: password = getVidyoOptionValue('indicoPassword') location = getVidyoOptionValue( 'baseAPILocation') + getVidyoOptionValue('userAPIService') try: cls._instance = suds.client.Client( userAPIUrl, transport=ClientBase.getTransport(userAPIUrl, username, password), location=location) except Exception: Logger.get("Vidyo").exception("Problem building UserClient") raise return cls._instance
def updateMicalaCDSExport(cls, cds_indico_matches, cds_indico_pending): '''If there are records found in CDS but not yet listed in the micala database as COMPLETE, then update it. cds_indico_matches is a dictionary of key-value pairs { IndicoID1: CDSID1, IndicoID2: CDSID2, ... } cds_indico_pending is a list of IndicoIDs (for whom the CDS export task has been started but not completed).''' # Logger.get('RecMan').debug('in updateMicalaCDSExport()') # debugging: # for matched in cds_indico_matches.keys(): # Logger.get('RecMan').debug('Looping through cds_indico_matches: %s -> %s' % (matched, cds_indico_matches[matched])) # for pending in cds_indico_pending: # Logger.get('RecMan').debug('Looping through cds_indico_pending: %s' % pending) for pending in cds_indico_pending: # Logger.get('RecMan').debug('Looping through cds_indico_pending: %s (and looking up in cds_indico_matches)' % pending) try: newRecord = cds_indico_matches[pending] idMachine = cls.getIdMachine(CollaborationTools.getOptionValue("RecordingManager", "micalaDBMachineName")) idTask = cls.getIdTask(CollaborationTools.getOptionValue("RecordingManager", "micalaDBStatusExportCDS")) idLecture = cls.getIdLecture(pending) cls.reportStatus("COMPLETE", "CDS record: %s" % newRecord, idMachine, idTask, idLecture) # add the CDS record number to the Lectures table resultAssociateCDSRecord = cls.associateCDSRecordToLOID(newRecord, idLecture) if not resultAssociateCDSRecord["success"]: Logger.get('RecMan').error("Unable to update Lectures table in micala database: %s" % resultAssociateCDSRecord["result"]) # this is not currently used: return resultAssociateCDSRecord["result"] except KeyError: # current pending lecture still not found in CDS so do nothing. Logger.get('RecMan').debug('%s listed as pending and not found in cds_indico_matches, so it must still be pending.' % pending)
def get(self, key): try: path = self._getFilePath(key) if not os.path.exists(path): return None f = open(path, 'rb') OSSpecific.lockFile(f, 'LOCK_SH') expiry = val = None try: expiry, val = pickle.load(f) finally: OSSpecific.lockFile(f, 'LOCK_UN') f.close() if expiry and time.time() > expiry: return None except (IOError, OSError): Logger.get('FileCache').exception('Error getting cached value') return None except (EOFError, pickle.UnpicklingError): Logger.get('FileCache').exception( 'Cached information seems corrupted. Overwriting it.') return None return val
def disconnectRoom(cls, roomIp, serviceType): try: ravemClient = RavemClient.getInstance() return ravemClient.performOperation("/videoconference/disconnect?type=%s&where=vc_endpoint_ip&value=%s"%(serviceType, roomIp)) except Exception, e: Logger.get('Ravem').exception("""Ravem API's disconnectRoom operation not successfull: %s""" % e.message) raise
def eventTitleChanged(cls, obj, oldTitle, newTitle): obj = Catalog.getIdx("cs_bookingmanager_conference").get(obj.getConference().getId()) try: obj.notifyTitleChange(oldTitle, newTitle) except Exception, e: Logger.get('PluginNotifier').error("Exception while trying to access to the title parameters when changing an event title" + str(e))
def _processNoReportError(self, e): """Process errors without reporting""" Logger.get('requestHandler').info('Request %s finished with NoReportError: "%s"' % (request, e)) p=errors.WPNoReportError(self,e) return p.display()
def _processHostnameResolveError(self,e): """Unexpected errors """ Logger.get('requestHandler').exception('Request %s failed: "%s"' % (id(self._req), e)) p=errors.WPHostnameResolveError(self) return p.display()
def _processAccessError(self, e): """Treats access errors occured during the process of a RH.""" Logger.get('requestHandler').info('Request %s finished with AccessError: "%s"' % (request, e)) self._responseUtil.status = 403 p=errors.WPAccessError(self) return p.display()
def decorator(*args, **keyargs): e = args[1] Logger.get('requestHandler').info('Request %s finished with %s: "%s"' % (request, e.__class__.__name__, e)) if request.headers.get("Content-Type", "text/html").find("application/json") != -1: return create_json_error_answer(e) else: return func(*args, **keyargs)
def _processGeneralError(self, e): """Treats general errors occured during the process of a RH. """ Logger.get('requestHandler').info('Request %s finished with: "%s"' % (request, e)) p=errors.WPGenericError(self) return p.display()
def getWebExTimeZoneToUTC( self, tz_id, the_date ): """ The date is required because the WebEx server responds with the offset of GMT time based on that date, adjusted for daylight savings, etc """ params = self.getBookingParams() request_xml = """<?xml version="1.0\" encoding="UTF-8"?> <serv:message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:serv=\"http://www.webex.com/schemas/2002/06/service" > <header> <securityContext> <webExID>%(username)s</webExID> <password>%(password)s</password> <siteID>%(siteID)s</siteID> <partnerID>%(partnerID)s</partnerID> </securityContext> </header> <body> <bodyContent xsi:type="site.LstTimeZone" > <timeZoneID>%(tz_id)s</timeZoneID> <date>%(date)s</date> </bodyContent> </body> </serv:message> """ % ( { "username" : params['webExUser'], "password" : self.getWebExPass(), "siteID" : getWebExOptionValueByName("WESiteID"), "partnerID" : getWebExOptionValueByName("WEPartnerID"), "tz_id":tz_id, "date":the_date } ) response_xml = sendXMLRequest( request_xml ) dom = xml.dom.minidom.parseString( response_xml ) offset = dom.getElementsByTagName( "ns1:gmtOffset" )[0].firstChild.toxml('utf-8') try: return int(offset) except: Logger.get('WebEx').debug( "Eror requesting time zone offset from WebEx:\n\n%s" % ( response_xml ) ) return None
def sendParticipantsEmail(self, operation): params = self.getBookingParams() try: if params.has_key('sendAttendeesEmail') and params['sendAttendeesEmail'][0].lower() == 'yes': recipients = [] for k in self._participants.keys(): recipients.append( self._participants[k]._email ) if len(recipients)>0: if operation == 'remove': notification = WebExParticipantNotification( self,recipients, operation ) GenericMailer.send( notification ) else: notification = WebExParticipantNotification( self,recipients, operation, additionalText="This is a WebEx meeting invitation.<br/><br/>" ) GenericMailer.send( notification ) if params.has_key('sendCreatorEmail') and params['sendCreatorEmail'][0].lower() == 'yes': recipients = MailTools.getManagersEmailList(self.getConference(), 'WebEx') notification = WebExParticipantNotification( self,recipients, operation, additionalText="Dear event manager:<br/><br/>\n\n " ) GenericMailer.send( notification ) if params.has_key('sendSelfEmail') and params['sendSelfEmail'][0].lower() == 'yes' and params.has_key("loggedInEmail") and params["loggedInEmail"] != "": recipients = [ params["loggedInEmail"] ] notification = WebExParticipantNotification( self,recipients, operation, additionalText="You are receiving this email because you requested it when creating a WebEx booking via Indico.<br/><br/>\n\n " ) GenericMailer.send( notification ) except Exception,e: Logger.get('WebEx').error( """Could not send participant email for booking with id %s of event with id %s, operation %s, exception: %s""" % (self.getId(), self.getConference().getId(), operation, str(e))) Logger.get('WebEx').error( MailTools.getManagersEmailList(self.getConference(), 'WebEx') ) self._warning = _("The operation appears to have been successful, however there was an error in sending the emails to participants: %s" % str(e) )
def _processEntryTimingError(self, e): """Treats timing errors occured during the process of a RH.""" Logger.get('requestHandler').info('Request %s finished with EntryTimingError: "%s"' % (request, e)) p=errors.WPEntryTimingError(self,e) return p.display()
def isRoomConnected(cls, roomIp): try: ravemClient = RavemClient.getInstance() return ravemClient.performOperation("/getstatus?where=vc_endpoint_ip&value=%s"%roomIp) except Exception, e: Logger.get('Ravem').exception("""Ravem API's isRoomConnected operation not successfull: %s""" % e.message) raise
def isRoomConnected(cls, booking, roomIp): try: answer = RavemApi.isRoomConnected(roomIp) if not answer.ok or answer.json.has_key("error"): Logger.get('Vidyo').exception( """Evt:%s, booking:%s, Ravem API's isRoomConnected operation not successfull: %s""" % (booking.getConference().getId(), booking.getId(), answer.text)) return VidyoError( "roomCheckFailed", "roomConnected", _("There was a problem obtaining the room status. ") + VidyoTools.getContactSupportText()) result = {"roomName": None, "isConnected": False, "service": None} answer = answer.json if answer.has_key("result"): for service in answer.get("result").get("services"): if service.get("name", "") == "videoconference": result["roomName"] = VidyoTools.recoverVidyoName( service.get("eventName")) result["isConnected"] = service.get("status") == 1 result["service"] = VidyoTools.recoverVidyoDescription( service.get("eventType")) return result except Exception: return VidyoError( "roomCheckFailed", "roomConnected", _("There was a problem obtaining the room status. ") + VidyoTools.getContactSupportText())
def load(self, path, name, default=None): try: obj = self._connect().get(self._makeKey(path, name)) except redis.RedisError: Logger.get('redisCache').exception('load failed') return None, None return obj, None
def _sendReport(self): cfg = Config.getInstance() # if no e-mail address was specified, # add a default one if self._userMail: fromAddr = self._userMail else: fromAddr = '*****@*****.**' toAddr = Config.getInstance().getSupportEmail() Logger.get('errorReport').debug('mailing %s' % toAddr) subject = "[Indico@%s] Error report" % cfg.getBaseURL() # build the message body body = [ "-" * 20, "Error details\n", self._code, self._message, "Inner error: " + str(self._inner), str(self._requestInfo), "-" * 20 ] maildata = { "fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body) } # send it GenericMailer.send(GenericNotification(maildata))
def connectRoom(cls, booking, roomId, extension): confId = booking.getConference().getId() bookingId = booking.getId() try: searchFilter = SOAPObjectFactory.createFilter('user', extension) userApiAnswer = UserApi.search(searchFilter, confId, bookingId) if userApiAnswer.total == 0: return VidyoError( "noExistsRoom", "connect", _("The conference room is not registered in the vidyo service. " ) + VidyoTools.getContactSupportText()) legacyMember = userApiAnswer.Entity[0].entityID AdminApi.connectRoom(roomId, confId, bookingId, legacyMember) except WebFault, e: faultString = e.fault.faultstring if faultString.startswith('ConferenceID is invalid'): return VidyoError("unknownRoom", "connect") if faultString.startswith('Failed to Invite to Conference'): message = _("The connection has failed. " ) + VidyoTools.getContactSupportText() return VidyoError("connectFailed", "connect", message) else: Logger.get('Vidyo').exception( """Evt:%s, booking:%s, Admin API's connectRoom operation got WebFault: %s""" % (confId, bookingId, e.fault.faultstring)) raise
def _sendReport(self): info = HelperMaKaCInfo().getMaKaCInfoInstance() cfg = Config.getInstance() # if no e-mail address was specified, # add a default one if self._userMail: fromAddr = self._userMail else: fromAddr = "*****@*****.**" toAddr = info.getSupportEmail() Logger.get("errorReport").debug("mailing %s" % toAddr) subject = "[Indico@%s] Error report" % cfg.getBaseURL() # build the message body body = [ "-" * 20, "Error details\n", self._code, self._message, "Inner error: " + str(self._inner), str(self._requestInfo), "-" * 20, ] maildata = {"fromAddr": fromAddr, "toList": [toAddr], "subject": subject, "body": "\n".join(body)} # send it GenericMailer.send(GenericNotification(maildata))
def getInstance(cls, *args, **kwargs): pid = os.getpid() if os.getpid() not in cls._instances: from MaKaC.common.logger import Logger Logger.get('dbmgr').debug('cls._instance is None') cls._instances[pid] = DBMgr(*args, **kwargs) return cls._instances[pid]
def eventTitleChanged(cls, obj, oldTitle, newTitle): obj = obj.getCSBookingManager() try: obj.notifyTitleChange(oldTitle, newTitle) except Exception, e: Logger.get('PluginNotifier').error("Exception while trying to access to the title parameters when changing an event title" + str(e))
def _run(self): Logger.get('OfflineEventGeneratorTask').info("Started generation of the offline website for task: %s" % self._task.id) setLocale(self._task.avatar.getLang()) self._rh = RHCustomizable() self._aw = self._rh._aw = AccessWrapper() self._rh._conf = self._rh._target = self._task.conference ContextManager.set('currentRH', self._rh) ContextManager.set('offlineMode', True) # Get event type wf = self._rh.getWebFactory() if wf: eventType = wf.getId() else: eventType = "conference" try: websiteZipFile = OfflineEvent(self._rh, self._rh._conf, eventType).create() except Exception, e: Logger.get('OfflineEventGeneratorTask').exception("Generation of the offline website for task %s failed \ with message error: %s" % (self._task.id, e)) self._task.status = "Failed" return
def get(self, key, default=None): self._connect() res = self._client.get(self._makeKey(key)) Logger.get('GenericCache/%s' % self._namespace).debug('GET %r -> %r' % (key, res is not None)) if res is None: return default return res
def extractUserDataFromLdapData(ret): """extracts user data from a LDAP record as a dictionary, edit to modify for your needs""" udata= {} udata["login"] = ret[UID_FIELD] udata["email"] = ret['mail'] # Ictp specific try: name = ' '.join(ret.get('displayName').split(' ')[1:]).strip() except: name = '' try: surname = ret.get('displayName').split(' ')[0] except: surname = ret.get('displayName', '') #udata["name"]= ret.get('givenName', '') udata["name"]= name # Ictp specific #udata["surName"]= ret.get('sn', '') udata["surName"]= surname # Ictp AD specific #udata["organisation"] = ret.get('company','') udata["organisation"] = 'Ictp' # Ictp specific udata['address'] = LDAPTools._fromLDAPmultiline(ret['postalAddress']) if 'postalAddress' in ret else '' udata["phone"] = ret.get('telephoneNumber','') udata["fax"] = ret.get('facsimileTelephoneNumber','') Logger.get('auth.ldap').debug("extractUserDataFromLdapData(): %s " % udata) return udata
def invokeMethod(self, method, params, req): MAX_RETRIES = 10 # clear the context ContextManager.destroy() DBMgr.getInstance().startRequest() # room booking database _startRequestSpecific2RH() # notify components that the request has started self._notify('requestStarted', req) forcedConflicts = Config.getInstance().getForceConflicts() retry = MAX_RETRIES try: while retry > 0: if retry < MAX_RETRIES: # notify components that the request is being retried self._notify('requestRetry', req, MAX_RETRIES - retry) try: # delete all queued emails GenericMailer.flushQueue(False) DBMgr.getInstance().sync() try: result = processRequest(method, copy.deepcopy(params), req) except MaKaC.errors.NoReportError, e: raise NoReportError(e.getMsg()) rh = ContextManager.get('currentRH') # notify components that the request has ended self._notify('requestFinished', req) # Raise a conflict error if enabled. This allows detecting conflict-related issues easily. if retry > (MAX_RETRIES - forcedConflicts): raise ConflictError _endRequestSpecific2RH( True ) DBMgr.getInstance().endRequest(True) GenericMailer.flushQueue(True) # send emails if rh._redisPipeline: try: rh._redisPipeline.execute() except RedisError: Logger.get('redis').exception('Could not execute pipeline') break except ConflictError: _abortSpecific2RH() DBMgr.getInstance().abort() retry -= 1 continue except ClientDisconnected: _abortSpecific2RH() DBMgr.getInstance().abort() retry -= 1 time.sleep(MAX_RETRIES - retry) continue
def _processFormValuesError(self, e): """Treats user input related errors occured during the process of a RH.""" Logger.get('requestHandler').info('Request %s finished with FormValuesError: "%s"' % (request, e)) p=errors.WPFormValuesError(self,e) return p.display()
def _sendMail(self, operation): """ Overloads _sendMail behavior for EVO """ if operation == 'new': #notification to admin try: notification = notifications.NewVidyoPublicRoomNotificationAdmin(self) GenericMailer.sendAndLog(notification, self.getConference(), self.getPlugin().getName()) except Exception, e: Logger.get('Vidyo').error( """Could not send NewVidyoPublicRoomNotificationAdmin for booking with id %s of event with id %s, exception: %s""" % (self.getId(), self.getConference().getId(), str(e))) #notification to owner if isinstance(self.getOwnerObject(), Avatar): try: notification = notifications.VidyoOwnerChosenNotification(self) GenericMailer.sendAndLog(notification, self.getConference(), self.getPlugin().getName()) except Exception, e: Logger.get('Vidyo').error( """Could not send VidyoOwnerChosenNotification for booking with id %s of event with id %s, exception: %s""" % (self.getId(), self.getConference().getId(), str(e)))
def OAuthCheckAccessResource(cls): from indico.modules.oauth.db import ConsumerHolder, AccessTokenHolder, OAuthServer oauth_request = oauth.Request.from_request(request.method, request.base_url, request.headers, parameters=create_flat_args()) Logger.get('oauth.resource').info(oauth_request) try: now = nowutc() consumer_key = oauth_request.get_parameter('oauth_consumer_key') if not ConsumerHolder().hasKey(consumer_key): raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED) consumer = ConsumerHolder().getById(consumer_key) token = oauth_request.get_parameter('oauth_token') if not token or not AccessTokenHolder().hasKey(token): raise OAuthError('Invalid Token', 401) access_token = AccessTokenHolder().getById(token) oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret()) OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken()) if access_token.getConsumer().getId() != oauth_consumer.key: raise OAuthError('Invalid Consumer Key', apache.HTTP_UNAUTHORIZED) elif (now - access_token.getTimestamp()) > timedelta(seconds=Config.getInstance().getOAuthAccessTokenTTL()): raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED) return access_token except oauth.Error, e: if e.message.startswith("Invalid Signature"): raise OAuthError("Invalid Signature", 401) else: raise OAuthError(e.message, 400)
def process(req): responseBody = {"version": "1.1", "error": None, "result": None} requestBody = None try: # check content type (if the users know what they are using) # if req.content_type != "application/json": # raise RequestError("Invalid content type. It must be 'application/json'.") # read request requestText = req.read() Logger.get("rpc").info("json rpc request. request text= " + str(requestText)) if requestText == "": raise RequestError("ERR-R2", "Empty request.") # decode json try: requestBody = decode(requestText) except Exception, e: raise RequestError("ERR-R3", "Error parsing json request.", e) if "id" in requestBody: responseBody["id"] = requestBody["id"] result = ServiceRunner().invokeMethod(str(requestBody["method"]), requestBody.get("params", []), req) # serialize result try: responseBody["result"] = result except Exception, e: raise ProcessError("ERR-P1", "Error during serialization.")
def createIdentity(self, li, avatar): Logger.get("auth.ldap").info("createIdentity %s (%s %s)" % (li.getLogin(), avatar.getId(), avatar.getEmail())) data = self.checkLoginPassword(li.getLogin(), li.getPassword()) if data: return LDAPIdentity(li.getLogin(), avatar) else: return None
def call(self): try: maxDate = VidyoTools.getBookingsOldDate() previousTotal = VidyoTools.getEventEndDateIndex().getCount() error, attainedDate = DeleteOldRoomsAction._deleteRemoteRooms(maxDate) if error: VidyoTools.getEventEndDateIndex().deleteKeys(maxDate = attainedDate - timedelta(seconds = 1)) else: VidyoTools.getEventEndDateIndex().deleteKeys(maxDate = maxDate) newTotal = VidyoTools.getEventEndDateIndex().getCount() page = WDeleteOldRoomsActionResult(maxDate, previousTotal, newTotal, error, attainedDate).getHTML() #we send the mail without ExternalOperationsManager wrapping so that we see the result of an #eventual 2nd pass (we do want to have more than 1 email, or at least the last one) #TODO: change later when emails are stored in ContextManager and sent after commit DeleteOldRoomsAction._sendResultEmail(maxDate, previousTotal, newTotal, error, attainedDate) return page except Exception: Logger.get("Vidyo").exception("Exception during Vidyo's DeleteOldRoomsAction call") raise
def findGroupMemberUids(self, group): """ Finds uids of users in a group. Depends on groupStyle (SLAPD/ActiveDirectory) """ Logger.get('auth.ldap').debug('findGroupMemberUids(%s)' % group) # In ActiveDirectory users have multivalued attribute 'memberof' with list of groups # In SLAPD groups have multivalues attribute 'member' with list of users if self.groupStyle == 'ActiveDirectory': groupDN = self._findDNOfGroup(group) if not groupDN: return [] return self.nestedSearch(self._findDNOfGroup(group), {}) elif self.groupStyle == 'SLAPD': #read member attibute values from the group object members = None res = self.l.search_s(self._findDNOfGroup(group), ldap.SCOPE_BASE) for dn, data in res: if dn: members = data['member'] if not members: return [] memberUids = [] for memberDN in members: memberuid = LDAPTools.extractUIDFromDN(memberDN) if memberuid: memberUids.add(memberuid) Logger.get('auth.ldap').debug('findGroupMemberUids(%s) returns %s' % (group, memberUids)) return memberUids else: raise Exception("Unknown LDAP group style, choices are: SLAPD or ActiveDirectory")
def call(self): try: maxDate = VidyoTools.getBookingsOldDate() previousTotal = VidyoTools.getEventEndDateIndex().getCount() error, attainedDate = DeleteOldRoomsAction._deleteRemoteRooms( maxDate) if error: VidyoTools.getEventEndDateIndex().deleteKeys( maxDate=attainedDate - timedelta(seconds=1)) else: VidyoTools.getEventEndDateIndex().deleteKeys(maxDate=maxDate) newTotal = VidyoTools.getEventEndDateIndex().getCount() page = WDeleteOldRoomsActionResult(maxDate, previousTotal, newTotal, error, attainedDate).getHTML() #we send the mail without ExternalOperationsManager wrapping so that we see the result of an #eventual 2nd pass (we do want to have more than 1 email, or at least the last one) #TODO: change later when emails are stored in ContextManager and sent after commit DeleteOldRoomsAction._sendResultEmail(maxDate, previousTotal, newTotal, error, attainedDate) return page except Exception: Logger.get("Vidyo").exception( "Exception during Vidyo's DeleteOldRoomsAction call") raise
def isRoomConnected(cls, booking, roomIp="", roomPanoramaUser=""): try: if roomIp != "": answer = RavemApi.isLegacyEndpointConnected(roomIp) else: answer = RavemApi.isVidyoPanoramaConnected(roomPanoramaUser) if not answer.ok or "error" in answer.json(): Logger.get('Vidyo').exception("""Evt:%s, booking:%s, Ravem API's isConnected operation not successfull: %s""" % (booking.getConference().getId(), booking.getId(), answer.text)) return VidyoError("roomCheckFailed", "roomConnected", _("There was a problem obtaining the room status from Vidyo. {0}").format(VidyoTools.getContactSupportText())) result = {"roomName": None, "isConnected": False, "service": None} answer = answer.json() if "result" in answer: for service in answer.get("result").get("services"): if service.get("name", "") == "videoconference": result["roomName"] = VidyoTools.recoverVidyoName(service.get("event_name")) result["isConnected"] = service.get("status") == 1 result["service"] = VidyoTools.recoverVidyoDescription(service.get("event_type")) return result except Exception: return VidyoError("roomCheckFailed", "roomConnected", _("There was a problem obtaining the room status from Vidyo. {0}").format( VidyoTools.getContactSupportText()))
def OAuthCheckAccessResource(cls, req, query_string): from indico.modules.oauth.db import ConsumerHolder, AccessTokenHolder, OAuthServer oauth_request = oauth.Request.from_request(req.get_method(),req.construct_url(req.get_uri()), headers=req.headers_in, query_string=urlencode(query_string)) Logger.get('oauth.resource').info(oauth_request) try: now = time.time() consumer_key = oauth_request.get_parameter('oauth_consumer_key') if not ConsumerHolder().hasKey(consumer_key): raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED) consumer = ConsumerHolder().getById(consumer_key) token = oauth_request.get_parameter('oauth_token') if not token or not AccessTokenHolder().hasKey(token): raise OAuthError('Invalid Token', apache.HTTP_UNAUTHORIZED) access_token = AccessTokenHolder().getById(token) oauth_consumer = oauth.Consumer(consumer.getId(), consumer.getSecret()) OAuthServer.getInstance().verify_request(oauth_request, oauth_consumer, access_token.getToken()) if access_token.getConsumer().getId() != oauth_consumer.key: raise OAuthError('Invalid Consumer Key' , apache.HTTP_UNAUTHORIZED) elif (now - access_token.getTimestamp()) > Config.getInstance().getOAuthAccessTokenTTL(): raise OAuthError('Expired Token', apache.HTTP_UNAUTHORIZED) return access_token except oauth.Error, e: if e.message.startswith("Invalid Signature"): raise OAuthError("Invalid Signature", apache.HTTP_UNAUTHORIZED) else: raise OAuthError(e.message, apache.HTTP_BAD_REQUEST)
def _processHostnameResolveError(self, e): """Unexpected errors """ Logger.get('requestHandler').exception('Request %s failed: "%s"' % (id(self._req), e)) p = errors.WPHostnameResolveError(self) return p.display()
def _processRestrictedHTML(self, e): Logger.get('requestHandler').info( 'Request %s finished with ProcessRestrictedHTMLError: "%s"' % (id(self._req), e)) p = errors.WPRestrictedHTML(self, escape(str(e))) return p.display()
def _processHtmlScriptError(self, e): Logger.get('requestHandler').info( 'Request %s finished with ProcessHtmlScriptError: "%s"' % (id(self._req), e)) p = errors.WPHtmlScriptError(self, escape(str(e))) return p.display()
def createIdentity(self, li, avatar): Logger.get("auth.ldap").info("createIdentity %s (%s %s)" % \ (li.getLogin(), avatar.getId(), avatar.getEmail())) if LDAPChecker().check(li.getLogin(), li.getPassword()): return LDAPIdentity(li.getLogin(), avatar) else: return None
def unindex(self, entryId): intId = self.getInteger(entryId) if intId != None: self.removeString(entryId) self._textIdx.unindex_doc(intId) else: Logger.get('indexes.text').error("No such entry '%s'" % entryId)
def _setFakeConfig(self, custom): """ Sets a fake configuration for the current process, using a temporary directory """ config = Config.getInstance() test_config = TestConfig.getInstance() temp = tempfile.mkdtemp(prefix="indico_") self._info('Using %s as temporary dir' % temp) os.mkdir(os.path.join(temp, 'log')) os.mkdir(os.path.join(temp, 'archive')) indicoDist = pkg_resources.get_distribution('indico') htdocsDir = indicoDist.get_resource_filename('indico', 'indico/htdocs') etcDir = indicoDist.get_resource_filename('indico', 'etc') # minimal defaults defaults = { 'BaseURL': 'http://localhost:8000/indico', 'BaseSecureURL': '', 'UseXSendFile': False, 'AuthenticatorList': ['Local'], 'SmtpServer': ('localhost', 58025), 'SmtpUseTLS': 'no', 'DBConnectionParams': ('localhost', TestConfig.getInstance().getFakeDBPort()), 'LogDir': os.path.join(temp, 'log'), 'XMLCacheDir': os.path.join(temp, 'cache'), 'HtdocsDir': htdocsDir, 'ArchiveDir': os.path.join(temp, 'archive'), 'UploadedFilesTempDir': os.path.join(temp, 'tmp'), 'ConfigurationDir': etcDir } defaults.update(custom) # set defaults config.reset(defaults) Config.setInstance(config) self._cfg = config # re-configure logging and template generator, so that paths are updated from MaKaC.common import TemplateExec from MaKaC.common.logger import Logger TemplateExec.mako = TemplateExec._define_lookup() Logger.reset()
def _processTimingError(self, e): """Treats timing errors occured during the process of a RH. """ Logger.get('requestHandler').info( 'Request %s finished with TimingError: "%s"' % (id(self._req), e)) p = errors.WPTimingError(self, e) return p.display()
def endDateChanged(cls, obj, params={}): obj = obj.getCSBookingManager() try: obj.notifyEventDateChanges(None, None, params['oldDate'], params['newDate']) except Exception, e: Logger.get('PluginNotifier').error( "Exception while trying to access to the date parameters when changing an event date" + str(e))
def eventTitleChanged(cls, obj, oldTitle, newTitle): obj = obj.getCSBookingManager() try: obj.notifyTitleChange(oldTitle, newTitle) except Exception, e: Logger.get('PluginNotifier').error( "Exception while trying to access to the title parameters when changing an event title" + str(e))
def getAttribute(self, attribute): try: if self._plugin: return getattr(self._plugin, attribute) else: return getattr(self._pluginType, attribute) except AttributeError: Logger.get('Plugins').error("No attribute %s in plugin %s" % (attribute, self._plugin)) raise Exception("No attribute %s in plugin %s" % (attribute, self._plugin))
def isVisible(self, user): target = self.getTarget() if target: return target.canView(user) else: Logger.get('search').warning("referenced element %s does not exist!" % self.getCompoundId()) return False
def _handleServiceCallException(cls, e): Logger.get("Vidyo").exception("Service call exception") cause = e.args[0] if type(cause) is tuple and cause[0] == 401: raise VidyoConnectionException(e) elif type(e) == URLError: raise VidyoConnectionException(e) else: raise
def _processGeneralError(self, e): """Treats general errors occured during the process of a RH. """ Logger.get('requestHandler').info('Request %s finished with: "%s"' % (id(self._req), e)) p = errors.WPGenericError(self) return p.display()
def _processAccessError(self, e): """Treats access errors occured during the process of a RH. """ Logger.get('requestHandler').info( 'Request %s finished with AccessError: "%s"' % (id(self._req), e)) self._req.status = apache.HTTP_FORBIDDEN p = errors.WPAccessError(self) return p.display()
def _cacheNextStartingRecord(self, queryHash, page, record, obj): if not obj: obj = SECacheEntry(self._sessionHash, queryHash) obj.setPage(self._page + 1, record + 1) Logger.get("search").debug("set page: %s" % obj._data) SECache().cacheObject(obj, "")
def getOption(self, optionName): try: if self._plugin: return self._plugin.getOption(optionName).getValue() else: return self._pluginType.getOption(optionName).getValue() except Exception, e: Logger.get('Plugins').error("Exception while trying to access the option %s in the plugin %s: %s" % (self._pluginType, self._plugin, str(e))) raise Exception("Exception while trying to access the option %s in the plugin %s: %s" % (self._pluginType, self._plugin, str(e)))