Example #1
0
def confirmEmails(qConfirmEmails):
    """
    Process Event and send an Email to the user to confirm his/her email
    """
    # db connection is shared between threads
    dbconnection = connect()
    while True:
        try:
            event = Event(qConfirmEmails.get())
        except Exception as e:
            logger.exception(e)
            logger.error("Problem with event: {}".format(e))
            continue
        else:
            if event.notify:
                # We try to send the email only once
                event.notify = False
                dispatch(dbconnection, event)
                try:
                    # Recipients
                    # Status did NOT changed
                    if event.status == event.previous_status:
                        logger.warning("TODO: send specific emails with messages")
                    recipients = set()

                    url = s.web['url']
                    if s.web['port'] and s.web['port'] != 80:
                        url = url +':'+ s.web['port']

                    # Look for the user email in the Event
                    if event.object.type == ObjectType.USER:
                        recipients.add(User(event.data))
                    elif event.object.type == ObjectType.AUTHORITY:
                        for user in event.data['users']:
                            recipients.add(User(user))
                    else:
                        for user in event.data['pi_users']:
                            recipients.add(User(user))

                    url = url+'/confirm/'+event.id
                    subject, template = build_subject_and_template('confirm', event)
                    buttonLabel = "Confirm Email"

                    sendEmail(event, recipients, subject, template, url, buttonLabel)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    msg = "Error in event {} while trying to send a confirmation email: {}".format(event.id, e)
                    logger.error(msg)
                    event.logWarning(msg)
                    continue
                finally:
                    dispatch(dbconnection, event)
Example #2
0
def events_run(lock, qLeasesEvents):
    """
    Process the leases events
    """

    logger.info("Worker leases events starting")

    # db connection is shared between threads
    dbconnection = connect()

    while True:
        try:
            event = Event(qLeasesEvents.get())
        except Exception as e:
            logger.error("Problem with event: {}".format(e))
            event.logError("Error in worker leases: {}".format(e))
            event.setError()
            db.dispatch(dbconnection, event)
            continue
        else:
            logger.info("Processing event from user {}".format(event.user))
            try:
                event.setRunning()
                event.logInfo("Event is running")
                logger.debug("Event %s is running" % event.id)
                isSuccess = False

                u = User(db.get(dbconnection, table='users', id=event.user))
                user_setup = UserSetup(u, myslicelibsetup.endpoints)

                if event.creatingObject():
                    leases = []
                    if isinstance(event.data, list):
                        for l in event.data:
                            slice_id = l['slice_id']
                            leases.append(Lease(l))
                    else:
                        slice_id = event.data['slice_id']
                        leases.append(Lease(event.data))
                    sli = Slice(
                        db.get(dbconnection, table='slices', id=slice_id))
                    if not sli:
                        raise Exception("Slice doesn't exist")
                    for lease in leases:
                        for val in lease.resources:
                            r = db.get(dbconnection, table='resources', id=val)
                            # Add resource only if it exists in DB
                            if r is not None:
                                r = Resource(r)
                                sli.addResource(r)
                            else:
                                r = Resource({'id': val})
                                lease.removeResource(r)

                        if len(lease.resources) > 0:
                            sli.addLease(lease)
                        else:
                            raise Exception("Invalid resources")
                    isSuccess = sli.save(dbconnection, user_setup)

                if event.deletingObject():
                    lease = Lease(
                        db.get(dbconnection,
                               table='leases',
                               id=event.object.id))
                    if not lease:
                        raise Exception("Lease doesn't exist")

                    sli = Slice(
                        db.get(dbconnection,
                               table='slices',
                               id=event.data['slice_id']))
                    if not sli:
                        raise Exception("Slice doesn't exist")

                    for val in event.data['resources']:
                        r = Resource(
                            db.get(dbconnection, table='resources', id=val))
                        # Remove resource only if it exists in DB
                        if r:
                            sli.removeResource(r)
                        else:
                            r = Resource({'id': val})
                            lease.removeResource(r)
                    sli.removeLease(lease)

                    isSuccess = sli.save(dbconnection, user_setup)

            except SliceException as e:
                # CREATE, DELETE
                # If at least one of the AMs replies with success, it's ok
                # If all AMs have failed -> Error
                for err in e.stack:
                    event.logError("Error in worker leases: {}".format(err))
                    logger.error("Error in worker leases: {}".format(err))
                # XXX TO BE REFINED
                event.setError()
                continue

            except SliceWarningException as e:
                for err in e.stack:
                    event.logWarning(str(err))
                    logger.warning(str(err))
                event.setWarning()
                continue

            except Exception as e:
                import traceback
                traceback.print_exc()
                logger.error("Problem with event {}: {}".format(event.id, e))
                event.logError("Error in worker leases: {}".format(e))
                event.setError()
                continue
            else:
                if isSuccess:
                    event.setSuccess()
                    event.logInfo("Event success")
                    logger.debug("Event %s Success" % event.id)
                else:
                    logger.error("Error event {}: action failed".format(
                        event.id))
                    event.setError()
                    event.logError("Error in worker leases: action failed")

            db.dispatch(dbconnection, event)
Example #3
0
def emails_run(qEmails):
    """
    Process Requests and send Emails accordingly
    """

    # db connection is shared between threads
    dbconnection = connect()
    while True:
        try:
            event = Event(qEmails.get())
        except Exception as e:
            logger.error("Problem with event: {}".format(e))
            continue
        else:
            if event.notify:
                # We try to send the email only once
                event.notify = False
                dispatch(dbconnection, event)

                # Recipients
                # TODO: Send specific emails
                # Status did NOT changed
                # Comments about an event with a message
                if event.status == event.previous_status:
                    logger.warning("TODO: send specific emails with messages")
                recipients = set()

                url = s.web['url']
                if s.web['port'] and s.web['port'] != 80:
                    url = url +':'+ s.web['port']

                buttonLabel = "View details"
                if event.object.type == ObjectType.PASSWORD:
                    recipients.add(User(event.object.id))
                    url = url+'/password/'+event.data['hashing']
                    subject, template = build_subject_and_template('password', event)
                    buttonLabel = "Change password"
                else:
                    if event.isPending():
                        # Find the authority of the event object
                        # Then according the authority, put the pi_emails in pis_email
                        try:
                            authority_id = event.data['authority']
                        except KeyError:
                            msg = 'Authority id not specified ({})'.format(event.id)
                            logger.error(msg)
                            event.logWarning('Authority not specified in event {}, email not sent'.format(event.id))
                            pass
                        else:
                            authority = Authority(db.get(dbconnection, table='authorities', id=authority_id))
                            if not authority:
                                # get admin users
                                users = db.get(dbconnection, table='users')
                                for u in users:
                                    user = User(u)
                                    if user.isAdmin():
                                        logger.debug("user %s is admin" % user.id)
                                        recipients.add(user)
                            else:
                                for pi_id in authority.pi_users:
                                    recipients.add(User(pi_id))

                            if not recipients:
                                msg = 'Emails cannot be sent because no one is the PI of {}'.format(event.object.id)
                                logger.error(msg)
                                event.logWarning('No recipients could be found for event {}, email not sent'.format(event.id))
                            
                            subject, template = build_subject_and_template('request', event)
                            buttonLabel = "Approve / Deny"
                            url = url + '/activity'
                    else:
                        if event.user:
                            recipients.add(User(event.user))
                        else:
                            # Look for the user email in the Event
                            if event.object.type == ObjectType.USER:
                                recipients.add(User({'email':event.data['email'], 'first_name':event.data['first_name'], 'last_name':event.data['last_name']}))
                            elif event.object.type == ObjectType.AUTHORITY:
                                for user in event.data['users']:
                                    recipients.add(User(user))
                            else:
                                for user in event.data['pi_users']:
                                    recipients.add(User(user))

                        if event.isSuccess():
                            subject, template = build_subject_and_template('approve', event)

                        elif event.isDenied():
                            subject, template = build_subject_and_template('deny', event)

                try:
                    sendEmail(event, recipients, subject, template, url, buttonLabel)
                except Exception as e:
                    import traceback
                    traceback.print_exc()
                    msg = "Error in event {} while trying to send an email: {} {}".format(event.id, e, traceback.print_exc())
                    logger.error(msg)
                    event.logWarning(msg)
                    continue
                finally:
                    dispatch(dbconnection, event)