Пример #1
0
def confirmPersonCandidate(ticket):
    'Move changes from the PersonCandidate table into the Person table'
    # Query
    candidate = Session.query(model.PersonCandidate).filter(model.PersonCandidate.ticket==ticket).filter(model.PersonCandidate.when_expired>=datetime.datetime.utcnow()).first()
    # If the ticket exists,
    if candidate:
        # If the person exists,
        if candidate.person_id:
            # Update person
            person = Session.query(model.Person).get(candidate.person_id)
            person.username = candidate.username
            person.password_hash = candidate.password_hash
            person.nickname = candidate.nickname
            person.email = candidate.email
            person.email_sms = candidate.email_sms
            # Reset rejection_count
            person.rejection_count = 0
        # If the person does not exist,
        else:
            # Add person
            Session.add(model.Person(candidate.username, candidate.password_hash, candidate.nickname, candidate.email, candidate.email_sms))
        # Delete ticket
        Session.delete(candidate)
        # Commit
        Session.commit()
    # Return
    return candidate
Пример #2
0
 def update(self):
     "Update processor information"
     # Load
     ip = h.getRemoteIP()
     processor = Session.query(model.Processor).filter(model.Processor.ip == ip).first()
     # If the processor doesn't exist,
     if not processor:
         processor = model.Processor(ip)
         Session.add(processor)
     # Update
     processor.when_updated = datetime.datetime.utcnow()
     Session.commit()
Пример #3
0
    # shutil.move(databasePath, databaseBackupPath)
    connection = sqlite3.connect('production.db')
    cursor = connection.cursor()
    # Create new database
    Base.metadata.bind = Session.bind
    Base.metadata.reflect()
    Base.metadata.drop_all()
    Base.metadata.create_all()
    # Migrate people
    cursor.execute('SELECT username, password_hash, nickname, email, email_sms, minutes_offset, rejection_count, pickled FROM people')
    for username, password_hash, nickname, email, email_sms, minutes_offset, rejection_count, pickled in cursor.fetchall():
        person = model.Person(username, password_hash, nickname, email, email_sms)
        person.minutes_offset = minutes_offset
        person.rejection_count = rejection_count
        person.pickled = pickled
        Session.add(person)
        Session.commit()
    personByUsername = dict((x.username, x) for x in Session.query(model.Person))
    # Migrate scenarios
    cursor.execute('SELECT scenarios.id, username, name, scope, when_created, input FROM scenarios INNER JOIN people ON scenarios.owner_id=people.id WHERE status=?', [model.statusDone])
    for scenarioID, username, name, scope, when_created, input in cursor.fetchall():
        scenario = model.Scenario(personByUsername[username].id, name, scope)
        scenario.when_created = datetime.datetime.strptime(when_created, '%Y-%m-%d %H:%M:%S.%f')
        scenarioInput = pickle.loads(str(input))

        existingNetworkPath = scenarioInput['network configuration']['network']['existing network path']
        del scenarioInput['network configuration']['network']['existing network path']
        if existingNetworkPath:
            scenarioInput['network configuration']['network']['existing networks'] = u'network/network/existing networks.zip'

        scenario.input = scenarioInput
Пример #4
0
 def create(self):
     'POST /scenarios: Create a new item'
     # Initialize
     personID = h.getPersonID()
     if not personID:
         return redirect(url('person_login', targetURL=h.encodeURL(h.url('new_scenario'))))
     # Load
     try:
         demographicDatabase_h = int(request.POST.get('demographicDatabase_h', 0))
     except ValueError:
         demographicDatabase_h = 0
     if not demographicDatabase_h and 'demographicDatabase' not in request.POST:
         return cjson.encode(dict(isOk=0, message='The demographicDatabase field is required'))
     scenarioName = request.POST.get('scenarioName') or 'Untitled'
     try:
         scenarioScope = int(request.POST.get('scenarioScope', model.scopePrivate))
     except ValueError:
         scenarioScope = model.scopePrivate
     metricModelName = request.POST.get('metricModelName', metric.getModelNames()[0])
     networkModelName = request.POST.get('networkModelName', network.getModelNames()[0])
     callbackURL = request.POST.get('callbackURL')
     # Create scenario
     scenario = model.Scenario(personID, scenarioName, scenarioScope)
     Session.add(scenario)
     Session.commit()
     scenarioFolder = scenario.getFolder()
     if os.path.exists(scenarioFolder):
         shutil.rmtree(scenarioFolder)
     store.makeFolderSafely(scenarioFolder)
     # If the user is using an existing demographicDatabase,
     if demographicDatabase_h:
         # Copy source in case it is deleted
         sourceScenario = Session.query(model.Scenario).get(demographicDatabase_h)
         sourceScenarioFolder = sourceScenario.getFolder()
         demographicFileName = sourceScenario.input['demographic file name']
         demographicPath = os.path.join(scenarioFolder, demographicFileName)
         shutil.copyfile(os.path.join(sourceScenarioFolder, demographicFileName), demographicPath)
     # If the user is uploading a new demographicDatabase,
     else:
         # Save original demographicDatabase in case the user wants it later
         demographicDatabase = request.POST['demographicDatabase']
         demographicFileExtension = os.path.splitext(demographicDatabase.filename)[1]
         demographicFileName = 'demographics' + demographicFileExtension
         demographicPath = os.path.join(scenarioFolder, demographicFileName)
         shutil.copyfileobj(demographicDatabase.file, open(demographicPath, 'wb'))
         demographicDatabase.file.close()
     # Store input
     configurationByName = extractConfigurationByName(request.POST, scenarioFolder)
     scenario.input = {
         'demographic file name': str(demographicFileName),
         'metric model name': metricModelName,
         'metric configuration': configurationByName.get('metric', {}),
         'network model name': networkModelName,
         'network configuration': configurationByName.get('network', {}),
         'callback url': callbackURL,
         'host url': request.host_url, 
     }
     Session.commit()
     store.zipFolder(scenarioFolder + '.zip', scenarioFolder)
     # Redirect
     redirect(url('scenario', id=scenario.id))
Пример #5
0
 try:
     # Validate form
     form = PersonForm().to_python(valueByName, person)
 except formencode.Invalid, error:
     return dict(isOk=0, errorByID=error.unpack_errors())
 else:
     # Purge expired candidates
     purgeExpiredPersonCandidates()
     # Prepare candidate
     candidate = model.PersonCandidate(
         form["username"], model.hashString(form["password"]), form["nickname"], form["email"], form["email_sms"]
     )
     candidate.person_id = person.id if person else None
     candidate.ticket = store.makeRandomUniqueTicket(parameter.TICKET_LENGTH, Session.query(model.PersonCandidate))
     candidate.when_expired = datetime.datetime.utcnow() + datetime.timedelta(days=parameter.TICKET_LIFESPAN_IN_DAYS)
     Session.add(candidate)
     Session.commit()
     # Prepare recipient
     toByValue = dict(nickname=form["nickname"], email=form["email"])
     # Prepare subject
     subject = "[%s] Confirm %s" % (parameter.SITE_NAME, action)
     # Prepare body
     c.candidate = candidate
     c.username = form["username"]
     c.action = action
     body = render(templatePath)
     # Send
     try:
         smtp.sendMessage(config["safe"]["mail support"], toByValue, subject, body)
     except smtp.SMTPError:
         return dict(isOk=0, errorByID={"status": "Unable to send confirmation; please try again later."})
Пример #6
0
 # Loop
 while True:
     # Try to get the next incoming message
     incomingMessage = channel.basic_get(incomingQueue, no_ack=True)
     # If a message does not exist,
     if not incomingMessage:
         # Take a break
         break
     # Unpack scenario from incoming message
     incomingPack = pickle.loads(incomingMessage.body)
     scenarioID, scenarioInput, scenarioData = incomingPack
     print 'Processing scenario %s' % scenarioID
     # Add scenario to local database
     scenario = model.Scenario(None, u'', model.scopePrivate)
     scenario.input = scenarioInput
     Session.add(scenario)
     Session.commit()
     # Unzip
     scenarioFolder = scenario.getFolder()
     store.unzipData(scenarioFolder, scenarioData)
     # Run
     try:
         scenario.run()
         scenario.status = model.statusDone
     except:
         scenario.output = dict(traceback=''.join(traceback.format_exception(*sys.exc_info())))
         scenario.status = model.statusFailed
     finally:
         Session.commit()
     # Pack result into outgoing message
     outgoingPack = scenarioID, scenario.output, open(scenarioFolder + '.zip', 'rb').read() if os.path.exists(scenarioFolder + '.zip') else None, scenario.status