def __init__(self, config, **kw): try: super(Counter, self).__init__(config, **kw) self.metadata = MetaData() self._connect() #TODO: add the most common index. except Exception, e: logger.log(msg='Could not initialize Storage "%s"' % str(e), type='error', severity=LOG.CRITICAL) raise e
def checkService(self, req): if req.registry.settings.get('service_until', None): # When do we expect the service to be done?" delay_until = req.registry.settings.get('service_until') # plus a bit of fuzz to dither out the herd delay_fuzz = int(req.registry.settings.get('service_fuzz', 30)) try: delay_until = max(int(parser.parse( delay_until).strftime('%s')) - int(time()), 0) except ValueError, e: logger.log(msg="Could not calculate delay: " + str(e), type="error") delay_until = 0 if delay_until > 0: delay_until += random.randrange(0, delay_fuzz) raise http.HTTPServiceUnavailable( headers={'Retry-After': str(delay_until)})
def checkService(self, req): if req.registry.settings.get('service_until', None): # When do we expect the service to be done?" delay_until = req.registry.settings.get('service_until') # plus a bit of fuzz to dither out the herd delay_fuzz = int(req.registry.settings.get('service_fuzz', 30)) try: delay_until = max( int(parser.parse(delay_until).strftime('%s')) - int(time()), 0) except ValueError, e: logger.log(msg="Could not calculate delay: " + str(e), type="error") delay_until = 0 if delay_until > 0: delay_until += random.randrange(0, delay_fuzz) raise http.HTTPServiceUnavailable( headers={'Retry-After': str(delay_until)})
def get_announce(self, data, now=None): # Really shouldn't allow "global" variables, but I know full well # that they're going to want them. params = {} # The window allows the db to cache the query for the length of the # window. This is because the database won't cache a query if it # differs from a previous one. The timestamp will cause the query to # not be cached. #window = int(self.settings.get('db.query_window', 1)) window = 1 if now is None: now = int(time.time() / window) * window sql = ("select created, id, note, priority, `specific`, " "start_time, idle_time from %s where " % self.__tablename__ + " coalesce(cast(start_time as unsigned), %s) <= %s" % (now - 1, now)) for field in ['product', 'platform', 'channel', 'lang', 'locale']: if data.get(field): sql += " and coalesce(%s, :%s) = :%s " % (field, field, field) params[field] = data.get(field) data['idle_time'] = data.get('idle', 0) try: if 'version' in data: sql +=" and coalesce(version, :version) = :version" params['version'] = str(data['version']).split('.')[0] except Exception: pass sql += " and coalesce(idle_time, 0) <= :idle_time " params['idle_time'] = data.get('idle_time') sql += " order by priority desc, `specific` desc, start_time desc" if (self.settings.get('dbg.show_query', False)): print sql print params if (self.settings.get('db.limit')): sql += " limit :limit" params['limit'] = self.settings.get('db.limit') try: items = self.engine.execute(text(sql), **dict(params)) except Exception, e: logger.log(msg='SQL Error "%s" ' % str(e), type='error', severity=LOG.CRITICAL)
def _connect(self): try: userpass = '' host = '' if (self.settings.get('db.user')): userpass = '******' % (self.settings.get('db.user'), self.settings.get('db.password')) if (self.settings.get('db.host')): host = '%s' % self.settings.get('db.host') dsn = '%s://%s%s/%s' % (self.settings.get('db.type', 'mysql'), userpass, host, self.settings.get('db.db', self.__database__)) self.engine = create_engine(dsn, pool_recycle=3600) Base.metadata.create_all(self.engine) self.session = scoped_session(sessionmaker(bind=self.engine))() #self.metadata.create_all(self.engine) except Exception, e: logger.log(msg='Could not connect to db "%s"' % repr(e), type='error', severity=LOG.EMERGENCY) raise e
else: return False except IOError, e: raise e except http.HTTPServerError, e: raise e except Exception, e: settings = request.registry.settings if utils.strToBool(settings.get('dbg.traceback', False)): import traceback traceback.print_exc() if utils.strToBool( settings.get('dbg.break_unknown_exception', False)): import pdb pdb.set_trace() if logger: logger.log(type='error', severity=LOG.ERROR, msg=str(e)) else: import sys sys.stderr.write("Auth Error! %s\n", str(e)) return False # User Logged in return True def __call__(self, *args, **kw): for arg in args: if isinstance(arg, Request) or isinstance(arg, DummyRequest): if self.login(arg): return self.fn(*args, **kw) raise http.HTTPUnauthorized(headers={"Refresh": "url=/"})
else: return False except IOError, e: raise e except http.HTTPServerError, e: raise e except Exception, e: settings = request.registry.settings if utils.strToBool(settings.get('dbg.traceback', False)): import traceback traceback.print_exc() if utils.strToBool(settings.get('dbg.break_unknown_exception', False)): import pdb pdb.set_trace() if logger: logger.log(type='error', severity=LOG.ERROR, msg=str(e)) else: import sys sys.stderr.write("Auth Error! %s\n", str(e)) return False # User Logged in return True def __call__(self, *args, **kw): for arg in args: if isinstance(arg, Request) or isinstance(arg, DummyRequest): if self.login(arg): return self.fn(*args, **kw) raise http.HTTPUnauthorized(headers={"Refresh": "url=/"})