Esempio n. 1
0
 def unsubscribe(self, user, conn=None, needs_auth=True, force_auth=False):
     if user not in self.subscribers:
         return
     if needs_auth and (self.moderated or self.moderated_unsubscribe):
         form = { 'channel_name': self.name, "user": user.get_name() }
         try:
             success, options = self.server.http_request('unsubscribe', user.get_cookie(conn), form, conn=conn)
         except ExpectedException:
             if not force_auth:
                 raise
             success, options = False, {}
         if not (success or force_auth):
             raise ExpectedException(options.get('error', 'Unauthorized'))
         self.server.maybe_auto_subscribe(user, options, conn=conn)
     frame = {"channel_name": self.name, "user": user.get_name(), 'datetime': get_now()}
     self.server.admin.channel_event('unsubscribe', self.name, frame)
     if self.presenceful:
         for subscriber in self.subscribers:
             if subscriber == user: continue
             subscriber.send_frame('UNSUBSCRIBE', frame)
     user.send_frame('UNSUBSCRIBE', frame)
     self.subscribers.remove(user)
     user.channel_unsubscribed(self)
     if self.history_size:
         del frame['channel_name']
         self.history.append(('UNSUBSCRIBE', frame))
         self.prune_history()
     
     if not self.subscribers:
         self.server.destroy_channel(self.name)
Esempio n. 2
0
    def publish(self, user, payload, needs_auth=True, conn=None, **kwargs):
        try:
            encoded_payload = json.loads(payload)
        except:
            raise ExpectedException("Invalid json for payload")
        payload = encoded_payload
        if needs_auth and (self.moderated or self.moderated_publish):
            form = { 'channel_name': self.name, 'payload': json.dumps(encoded_payload) }
            success, options = self.server.http_request('publish', user.get_cookie(conn), form, conn=conn)
            self.server.maybe_auto_subscribe(user, options, conn=conn)
            if not success:
                raise ExpectedException(options.get('error', 'Unauthorized'))
            payload = options.get('override_payload', payload)

        frame = {"channel_name": self.name, "payload":payload, "datetime": get_now()}

        if not self.anonymous:
            if 'originator' in kwargs:
                frame['user'] = kwargs['originator']
            else:
                frame['user'] = user.get_name()

        omit = None
        if not self.reflective:
            omit = conn
        for subscriber in self.subscribers:
            subscriber.send_frame('PUBLISH', frame, omit=omit)
        self.server.admin.channel_event('publish', self.name, frame)
        if self.history_size:
            del frame['channel_name']
            self.history.append(('PUBLISH', frame))
            self.prune_history()
Esempio n. 3
0
def docs_python_jp(request):
    mak_lookup = TemplateLookup(directories=["templates/"])
    template = mak_lookup.get_template('docs_python_jp.mak')
    word = get_request_value(request, 'word')
    now=get_now()
    result = template.render_unicode(
            now=now,
            word=urllib.quote(word)
        )
    return Response(result)
Esempio n. 4
0
    def create(self, user_id, token, platform=0):
        now = get_now()
        expire_time = get_delay_time(now, self.EXPIRE_TIME)

        self.db.execute('INSERT INTO %s (token, createtime, user_id, platform, \
                        expiretime) values(%s, "%s", %s, %s, %s)' % (token, 
                                                                     datetime_to_str(now),
                                                                     user_id,
                                                                     platform,
                                                                     datetime_to_str(expire_time)
                                                                     ))
Esempio n. 5
0
def edit_reporte():
    form = request.form
    reporte = db.session.merge(models.get_reporte_by_id(int(form['id'])))
    reporte.area = form['area']
    reporte.state = form['estado']
    reporte.problema = form['problema']
    reporte.localizacion_breve = form['localizacion']
    reporte.details = form['details']
    reporte.date_changed = utils.get_now()
    db.session.commit()
    return redirect(url_for('show_reportes'))
Esempio n. 6
0
def execute(request):
    mak_lookup = TemplateLookup(directories=["templates/"])
    template = mak_lookup.get_template('execute.mak')
    command = get_request_value(request, 'command')
    if is_allowed_ip(request.remote_addr) == False:
        command = "echo 'not allowed at your IP address(%s).'" % request.remote_addr
    now=get_now()
    print now,
    command_result = run(command)
    result = template.render_unicode(
            now=now,
            command_result=command_result
        )
    return Response(result)
Esempio n. 7
0
def vote():
    if request.method == 'GET':
        return render_template('index.html')
    elif request.method == 'POST':
        render = partial(render_template, 'index.html')

        uvc = request.form.get('uvc')

        if not uvc:
            return render(error='You didn\'t enter a UVC')

        if len(uvc) < 16:
            return render(error='Your UVC should be 16 characters long')

        uvc = uvc.upper()

        pcv = PollCollectionVote.query.filter(
            PollCollectionVote.uvc == uvc).first()

        if not pcv:
            return render(error='The UVC you entered does not exist')

        if pcv.cast:
            return render(error='You have already cast your vote')

        pc = PollCollection.query.get(pcv.collection_id)

        # Check that the poll is currently open
        now = get_now()
        if now < pc.start:
            return render(error='Voting for this poll has not started yet')
        elif pc.end < now:
            return render(error='Voting for this poll has closed')

        ps = pc.polls
        for p in ps:
            p.shuffle_candidates()

        return render_template('vote.html', uvc=uvc, pc=pc)
Esempio n. 8
0
    def subscribe(self, user, conn=None, needs_auth=True):

        if user in self.subscribers:
            return

        has_initial_data = False
        initial_data = None
        
        if needs_auth and (self.moderated or self.moderated_subscribe):
            form = { 'channel_name': self.name, "user": user.get_name() }
            success, options = self.server.http_request('subscribe', user.get_cookie(conn), form, conn=conn)
            if not success:
                raise ExpectedException(options.get('error', 'Unauthorized'))
            if 'initial_data' in options:
                has_initial_data = True
                initial_data = options['initial_data']
            self.server.maybe_auto_subscribe(user, options, conn=conn)
            
        if has_initial_data or self.history:
            frame = dict(channel_name=self.name, history=self.history, initial_data=initial_data)
            user.send_frame('CHANNEL_INIT', frame)

        self.subscribers.append(user)
        user.channel_subscribed(self)
        _now = get_now()
        frame = {"channel_name": self.name, "user": user.get_name(), "datetime": _now}
        self.server.admin.channel_event('subscribe', self.name, frame)
        if self.presenceful:
            for subscriber in self.subscribers:
                if subscriber == user: continue
                subscriber.send_frame('SUBSCRIBE', frame)
                
        frame = self._build_subscribe_frame(user, initial_data)
        
        user.send_frame('SUBSCRIBE', frame)
            
        if self.history_size:
            self.history.append(('SUBSCRIBE', {"user": user.get_name(), "datetime": _now }))
            self.prune_history()
Esempio n. 9
0
def agent(args):
    """Run a long running polling agent.

    Periodically updates the database with timeseries active stat data.

    :param args: argparse args
    """
    conf = config.load(args.config_file)
    nova = get_nova(conf)
    database.get_engine(conf.get('db', {}))

    detailed = True

    # Special all tenant.
    all_tenant_id = '0' * 32

    # Init last poll time to 0 to trigger first poll
    last_polled = 0

    while True:
        if time.time() - last_polled > conf.get('polling_interval', 120):
            with database.session_scope() as session:
                start, end = utils.get_date_interval()

                # Grab usage results
                usages = nova.usage.list(start, end, detailed=detailed)
                r = UsageReport(usages)

                # Get datetime for time value
                now = utils.get_now()

                # Iterate over all tenants
                for tenant_usage in usages:

                    # Ensure tenant is in tenant table
                    tenant_id = tenant_usage.tenant_id
                    tenant = Tenant.get_or_create(session, tenant_id)
                    session.commit()

                    # Get tenant stats and add to session
                    v, m, s = r.active_stats(tenant_id=tenant_id)
                    session.add(ActiveVCPUS(
                        value=v, time=now, tenant_id=tenant.id
                    ))
                    session.add(ActiveMemoryMB(
                        value=m, time=now, tenant_id=tenant.id
                    ))
                    session.add(ActiveLocalStorageGB(
                        value=s, time=now, tenant_id=tenant.id
                    ))

                # Save all tenant stats
                v, m, s = r.active_stats()
                print ("Active vcpus", v)
                print ("Active memory MB", m)
                print ("Active storage GB", s)
                all_tenant = Tenant.get_or_create(session, all_tenant_id)
                session.commit()
                session.add(ActiveVCPUS(
                    value=v, time=now, tenant_id=all_tenant.id
                ))
                session.add(ActiveMemoryMB(
                    value=m, time=now, tenant_id=all_tenant.id
                ))
                session.add(ActiveLocalStorageGB(
                    value=s, time=now, tenant_id=all_tenant.id
                ))

            last_polled = time.time()
            print ("Updating polling interval")
        time.sleep(1)
    exit()
Esempio n. 10
0
    def send_message(self, recipient_name, payload, conn=None, needs_auth=True):
        try:
            encoded_payload = json.loads(payload)
        except:
            raise ExpectedException("Invalid json for payload")
        payload = encoded_payload
        if needs_auth and self.moderated_message:
            form = { 'sender': self.get_name(), 'recipient': recipient_name, 'recipient_exists': self.server.exists_user(recipient_name), 'payload': json.dumps(payload) }
            success, options = self.server.http_request('message', self.get_cookie(conn), form, conn=conn)
            self.server.maybe_auto_subscribe(self, options, conn=conn)
            if not success:
                raise ExpectedException(options.get('error', 'Unauthorized'))
            payload = options.get('override_payload', payload)
            recipient_name = options.get('override_recipient_name', recipient_name)
        elif not self.server.exists_user(recipient_name):
            raise ExpectedException('Invalid user name')

        recipient = self.server.get_user(recipient_name) if self.server.exists_user(recipient_name) else None
        
        frame = {"sender": self.get_name(), "recipient": recipient.get_name() if recipient else "null", "payload": payload, "datetime": get_now()}
        if recipient:
            recipient.send_frame('MESSAGE', frame)
        if self.reflective and (not recipient or recipient.name != self.name):
            self.send_frame('MESSAGE', frame)