Beispiel #1
0
 def delete(self, bucket_name):
     path = os.path.abspath(
         os.path.join(self.application.directory, bucket_name))
     if not path.startswith(self.application.directory) or \
        not os.path.isdir(path):
         raise web.HTTPError(404)
     if len(os.listdir(path)) > 0:
         raise web.HTTPError(403)
     os.rmdir(path)
     self.set_status(204)
     self.finish()
Beispiel #2
0
def exception2http(e):
    if (hasattr(e, "getTraceback")):
        stacktrace = e.getTraceback()
    else:
        stacktrace = traceback.format_exc()
    if (isinstance(e, web.HTTPError)):
        return(e)
    elif (isinstance(e, KeyError) or isinstance(e, ValueError)):
        return(web.HTTPError(400, None, {"stacktrace": stacktrace}))
    elif (isinstance(e, excepts.NotFoundExcept)):
        return(web.HTTPError(404))
    else:
        return(web.HTTPError(500, None, {"stacktrace": stacktrace}))
Beispiel #3
0
    def post(self):
        try:
            signature = self.get_argument("sign")
            datastr = json.loads(unquote(self.get_argument("datastr")))
            extra1 = datastr["extra"].split("&")[1]
        except Exception:
            raise web.HTTPError(400, "Argument error")

        url = "%s/dangbei/notify/" % extra1
        params = dict(datastr=self.get_argument('datastr'), sign=signature)
        respose = yield httpclient.fetch(httputil.url_concat(url, params))
        if respose.code != 200:
            raise web.HTTPError(reponse.code)
        self.write("success")
    def post(self):
        if self._tsdb.myproto is None:
            return  # not connected to tsdb, drop this datapoint
        try:
            body = json.loads(self.request.body)
            nodeid = body.get('NodeId', None)
            D = {
                'testid': body['TestId'],
                'timestamp': body.get('Summary', {}).get('Timestamp', None),
                'rtt': body.get('Summary', {}).get('Timing', {}).get('Total', None),
                'error': body.get('Summary', {}).get('Error', {}).get('Code', None),
                }
        except:
            raise web.HTTPError(400, 'bad body')

        try:
            node = nodes.get_node(int(nodeid))
        except:
            raise web.HTTPError(400, 'bad node id')

        try:
            ts = time.mktime(time.strptime(D['timestamp'][:-3], '%Y%m%d%H%M%S'))
            D['timestamp'] = int(ts)
        except:
            D['timestamp'] = int(time.time())

        D['counter'] = 1  # silly hack, will assign either 'error' or 'ok' as status
        D['status'] = 'ok' if D['error'] is None else 'error'

        D.update(node)

        # put each of these in tsdb, and tag the by_xxx, and nodeid so
        # we can agg across all nodes
        self._tsdb.myproto.put('catchpoint.rtt.by_node', D, 'rtt', ['nodeid'])
        self._tsdb.myproto.put('catchpoint.status.by_node', D, 'counter', ['nodeid', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_asn', D, 'rtt', ['nodeid', 'asn'])
        self._tsdb.myproto.put('catchpoint.status.by_asn', D, 'counter', ['nodeid', 'asn', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_continent', D, 'rtt', ['nodeid', 'continent'])
        self._tsdb.myproto.put('catchpoint.status.by_continent', D, 'counter', ['nodeid', 'continent', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_city', D, 'rtt', ['nodeid', 'city'])
        self._tsdb.myproto.put('catchpoint.status.by_city', D, 'counter', ['nodeid', 'city', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_country', D, 'rtt', ['nodeid', 'country'])
        self._tsdb.myproto.put('catchpoint.status.by_country', D, 'counter', ['nodeid', 'country', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_region', D, 'rtt', ['nodeid', 'region'])
        self._tsdb.myproto.put('catchpoint.status.by_region', D, 'counter', ['nodeid', 'region', 'status'])
        self._tsdb.myproto.put('catchpoint.rtt.by_isp', D, 'rtt', ['nodeid', 'isp'])
        self._tsdb.myproto.put('catchpoint.status.by_isp', D, 'counter', ['nodeid', 'isp', 'status'])

        defer.succeed(True)
Beispiel #5
0
 def updateReport(self, report_filename, data):
     try:
         with open(report_filename, 'a+') as fd:
             fdesc.setNonBlocking(fd.fileno())
             fdesc.writeToFD(fd.fileno(), data)
     except IOError as e:
         web.HTTPError(404, "Report not found")
Beispiel #6
0
    def post(self):
        """
        Creates a new report with the input

        * Request

          {'software_name': 'XXX',
           'software_version': 'XXX',
           'test_name': 'XXX',
           'test_version': 'XXX',
           'progress': 'XXX',
           'content': 'XXX'
           }

          Optional:
            'test_helper': 'XXX'
            'client_ip': 'XXX'

        * Response

          {'backend_version': 'XXX', 'report_id': 'XXX'}

        """
        # XXX here we should validate and sanitize the request
        try:
            report_data = parseNewReportRequest(self.request.body)
        except InvalidRequestField, e:
            raise web.HTTPError(400, "Invalid Request Field %s" % e)
Beispiel #7
0
    def get(self):
        try:
            hid = self.get_argument("hid")
        except Exception:
            raise web.HTTPError(400, "Argument error")

        uid = self.uid
        user = yield self.get_user(uid)
        try:
            hero = user['heros'][hid]
        except Exception:
            self.write(dict(err=E.ERR_INVALID, msg=E.errmsg(E.ERR_INVALID)))
            return

        hero['color'] = 0
        hero['skills'] = [0, 0, 0, 0]
        hero['xp'] = 100000
        hero['star'] = 0
        hero['equips'] = [0, 0, 0, 0, 0, 0]

        cuser = dict(heros=user['heros'])
        yield self.set_user(uid, **cuser)

        msg = "SUCCESS! inited hid: " + hid
        self.write(msg)
Beispiel #8
0
class NewReportHandlerFile(web.RequestHandler):
    """
    Responsible for creating and updating reports by writing to flat file.
    """
    def post(self):
        """
        Creates a new report with the input

        * Request

          {'software_name': 'XXX',
           'software_version': 'XXX',
           'test_name': 'XXX',
           'test_version': 'XXX',
           'progress': 'XXX',
           'content': 'XXX'
           }

          Optional:
            'test_helper': 'XXX'
            'client_ip': 'XXX'

        * Response

          {'backend_version': 'XXX', 'report_id': 'XXX'}

        """
        # XXX here we should validate and sanitize the request
        try:
            report_data = parseNewReportRequest(self.request.body)
        except InvalidRequestField, e:
            raise web.HTTPError(400, "Invalid Request Field %s" % e)
        except MissingField, e:
            raise web.HTTPError(400, "Missing Request Field %s" % e)
Beispiel #9
0
    def get(self):
        try:
            cpOrderId = self.get_argument("cpOrderId")
            orderStatus = self.get_argument("orderStatus")
            payFee = self.get_argument("payFee")
            payTime = self.get_argument("payTime")
            signature = self.get_argument("signature")  
            cpUserInfo = self.get_argument("cpUserInfo")             
        except Exception:
            raise web.HTTPError(400, "Argument error")
        params = self.request.arguments.copy()
        params.pop('signature')
        for x, y in params.items():
            params[x] = y[0]
        params = yield self.format_params(params, False)
        m = hashlib.md5()   
        m.update(params) 
        _sign = m.hexdigest()  
        if signature != _sign:
            url = "%s/xmpay/notify/" % cpUserInfo
            params = dict(cpOrderId=cpOrderId, orderStatus=orderStatus, payFee=payFee, payTime=payTime)
            yield httpclient.fetch(httputil.url_concat(url, params))

            ret = dict(error_code=200)
        else:
            ret = dict(error_code=1525, errMsg=E.errmsg(E.ERR_SIGN))
        reb = zlib.compress(escape.json_encode(ret))
        self.write(ret)
Beispiel #10
0
 def put(self, bucket, object_name):
     object_name = urllib.unquote(object_name)
     bucket_dir = os.path.abspath(
         os.path.join(self.application.directory, bucket))
     if not bucket_dir.startswith(self.application.directory) or \
        not os.path.isdir(bucket_dir):
         raise web.HTTPError(404)
     path = self._object_path(bucket, object_name)
     if not path.startswith(bucket_dir) or os.path.isdir(path):
         raise web.HTTPError(403)
     directory = os.path.dirname(path)
     if not os.path.exists(directory):
         os.makedirs(directory)
     object_file = open(path, "w")
     object_file.write(self.request.body)
     object_file.close()
     self.finish()
Beispiel #11
0
 def GotoPage(self):
     web_type = self.get_argument("web_type", "ctrl")
     if web_type == "ctrl":
         self.redirect(rxg_consts.Node_URLs.APP_EM)
     elif web_type == 'sensor':
         self.redirect(rxg_consts.Node_URLs.APP_EM_SENSOR)
     else:
         raise cyclone_web.HTTPError(404)
Beispiel #12
0
 def GotoPage(self):
     web_type = self.get_argument("web_type", "em")
     if web_type == "em":
         self.redirect(rgw_consts.URLs.APP_EM)
     elif web_type == 'em_sensor':
         self.redirect(rgw_consts.URLs.APP_EM_SENSOR)
     else:
         raise cyclone_web.HTTPError(404)
Beispiel #13
0
 def put(self, bucket_name):
     log.msg('bruxao')
     path = os.path.abspath(
         os.path.join(self.application.directory, bucket_name))
     if not path.startswith(self.application.directory) or \
        os.path.exists(path):
         raise web.HTTPError(403)
     os.makedirs(path)
     self.finish()
Beispiel #14
0
 def post(self):
     try:
         zoneid = str(self.get_argument('zoneid'))
         access_token = str(self.get_argument('access_token'))
         idcard = str(self.get_argument('idcard'))
     except Exception:
         raise web.HTTPError(400, 'Argument error')
     yield self.redis.set('zone:%s:%s' % (zoneid, access_token), idcard)
     self.write('ok')
Beispiel #15
0
 def delete(self, bucket, object_name):
     object_name = urllib.unquote(object_name)
     path = self._object_path(bucket, object_name)
     if not path.startswith(self.application.directory) or \
        not os.path.isfile(path):
         raise web.HTTPError(404)
     os.unlink(path)
     self.set_status(204)
     self.finish()
Beispiel #16
0
    def get(self, bucket_name):
        prefix = self.get_argument("prefix", u"")
        marker = self.get_argument("marker", u"")
        max_keys = int(self.get_argument("max-keys", 50000))
        path = os.path.abspath(
            os.path.join(self.application.directory, bucket_name))
        terse = int(self.get_argument("terse", 0))
        if not path.startswith(self.application.directory) or \
           not os.path.isdir(path):
            raise web.HTTPError(404)
        object_names = []
        for root, dirs, files in os.walk(path):
            for file_name in files:
                object_names.append(os.path.join(root, file_name))
        skip = len(path) + 1
        for i in range(self.application.bucket_depth):
            skip += 2 * (i + 1) + 1
        object_names = [n[skip:] for n in object_names]
        object_names.sort()
        contents = []

        start_pos = 0
        if marker:
            start_pos = bisect.bisect_right(object_names, marker, start_pos)
        if prefix:
            start_pos = bisect.bisect_left(object_names, prefix, start_pos)

        truncated = False
        for object_name in object_names[start_pos:]:
            if not object_name.startswith(prefix):
                break
            if len(contents) >= max_keys:
                truncated = True
                break
            object_path = self._object_path(bucket_name, object_name)
            c = {"Key": object_name}
            if not terse:
                info = os.stat(object_path)
                c.update({
                    "LastModified":
                    datetime.datetime.utcfromtimestamp(info.st_mtime),
                    "Size":
                    info.st_size,
                })
            contents.append(c)
            marker = object_name
        self.render_xml({
            "ListBucketResult": {
                "Name": bucket_name,
                "Prefix": prefix,
                "Marker": marker,
                "MaxKeys": max_keys,
                "IsTruncated": truncated,
                "Contents": contents,
            }
        })
Beispiel #17
0
    def stop(self, service):
        """
        Process GET request:
            * /services/<service>/stop
        """
        try:
            ret = yield self.controller.set(service, False)
        except ValueError:
            raise web.HTTPError(404)

        defer.returnValue(self.result(ret))
Beispiel #18
0
 def state(self, service):
     """
     Process GET request:
         * /services/<service>/
     Return a dictionary containig a summary of what the service is and on
     which url is running on.
     """
     try:
         return json_encode(self.controller.get(service))
     except ValueError:
         raise web.HTTPError(404)
Beispiel #19
0
    def get(self):
        """
        Process asycnronous request:
            * GET /auth/logout
        """
        if self.action != 'logout':
            raise web.HTTPAuthenticationRequired if not self.current_user \
                  else web.HTTPError(404)

        #if not self.user:
        #    raise HTTPError(403)
        self.clear_cookie(self._uid_cookie)
Beispiel #20
0
    def get(self):
        try:
            gold = int(self.get_argument("gold", 1))
        except Exception:
            raise web.HTTPError(400, "Argument error")

        uid = self.uid
        user = yield self.get_user(uid)
        user['gold'] = gold
        cuser = dict(gold=user['gold'])
        yield self.set_user(uid, **cuser)
        msg = "SUCCESS! curr gold: " + str(gold)
        self.write(msg)
Beispiel #21
0
    def get(self):
        try:
            rock = int(self.get_argument("rock", 1))
        except Exception:
            raise web.HTTPError(400, "Argument error")

        uid = self.uid
        user = yield self.get_user(uid)
        user['rock'] = rock
        cuser = dict(rock=user['rock'])
        yield self.set_user(uid, **cuser)
        msg = "SUCCESS! curr rock: " + str(rock)
        self.write(msg)
Beispiel #22
0
    def get(self):
        try:
            xp = int(self.get_argument("xp", 1))
        except Exception:
            raise web.HTTPError(400, "Argument error")

        uid = self.uid
        user = yield self.get_user(uid)
        user['xp'] = xp
        cuser = dict(xp=user['xp'])
        yield self.set_user(uid, **cuser)
        msg = "SUCCESS! curr xp: " + str(xp)
        self.write(msg)
Beispiel #23
0
    def get(self):
        try:
            feat = int(self.get_argument("feat", 1))
        except Exception:
            raise web.HTTPError(400, "Argument error")

        uid = self.uid
        user = yield self.get_user(uid)
        user['feat'] = feat
        cuser = dict(feat=user['feat'])
        yield self.set_user(uid, **cuser)
        msg = "SUCCESS! curr feat: " + str(feat)
        self.write(msg)
Beispiel #24
0
    def get(self, service=None):
        """
        Processes GET requests:
          * /services/
          * /services/<service>/
          * /services/<service>/start
          * /services/<service>/stop
        """
        if self.action not in self._actions:
            raise web.HTTPError(404)

        ret = defer.maybeDeferred(getattr(self, self.action), service)
        ret.addCallback(self.callback_success).addErrback(
            self.callback_exception)
Beispiel #25
0
    def get(self):
        try:
            hp = int(self.get_argument("hp", 1))
        except Exception:
            raise web.HTTPError(400, "Argument error")

        #print 'hp:',hp
        uid = self.uid
        user = yield self.get_user(uid)
        currhp, tick = yield self.get_hp(user)
        currhp, tick = yield self.add_hp(user, hp)

        msg = "SUCCESS! curr hp: " + str(currhp)
        self.write(msg)
Beispiel #26
0
class NewReportHandlerFile(web.RequestHandler):
    """
    Responsible for creating and updating reports by writing to flat file.
    """
    def post(self):
        """
        Creates a new report with the input

        * Request

          {'software_name': 'XXX',
           'software_version': 'XXX',
           'test_name': 'XXX',
           'test_version': 'XXX',
           'probe_asn': 'XXX'
           'content': 'XXX'
           }

          Optional:
            'test_helper': 'XXX'
            'client_ip': 'XXX'

          (not implemented, nor in client, nor in backend)
          The idea behind these two fields is that it would be interesting to
          also collect how the request was observed from the collectors point
          of view.

          We use as a unique key the client_ip address and a time window. We
          then need to tell the test_helper that is selected the client_ip
          address and tell it to expect a connection from a probe in that time
          window.

          Once the test_helper sees a connection from that client_ip it will
          store for the testing session the data that it receives.
          When the probe completes the report (or the time window is over) the
          final report will include also the data collected from the
          collectors view point.

        * Response

          {'backend_version': 'XXX', 'report_id': 'XXX'}

        """
        # XXX here we should validate and sanitize the request
        try:
            report_data = parseNewReportRequest(self.request.body)
        except InvalidRequestField, e:
            raise web.HTTPError(400, "Invalid Request Field %s" % e)
        except MissingField, e:
            raise web.HTTPError(400, "Missing Request Field %s" % e)
Beispiel #27
0
def mustashify(req):
    url = req.get_argument("q")
    obj = req.settings.cache.get(url)
    if obj:
        content_type, buff = obj.split("\r\n", 1)
        req.set_header("Content-Type", content_type)
        req.write(buff)
        defer.returnValue(None)

    try:
        response = yield fetch(url, followRedirect=1, maxRedirects=3)
    except Exception, e:
        #log.err()
        raise web.HTTPError(404)
Beispiel #28
0
 def get(self, bucket, object_name):
     object_name = urllib.unquote(object_name)
     path = self._object_path(bucket, object_name)
     if not path.startswith(self.application.directory) or \
        not os.path.isfile(path):
         raise web.HTTPError(404)
     info = os.stat(path)
     self.set_header("Content-Type", "application/unknown")
     self.set_header("Last-Modified",
                     datetime.datetime.utcfromtimestamp(info.st_mtime))
     object_file = open(path, "r")
     try:
         self.finish(object_file.read())
     finally:
         object_file.close()
Beispiel #29
0
 async def handlePage_(self):
     try:
         await api_req_limit.CheckHTTP(self)
         sid = await CheckRight(self)
         ulang = GetLangCode(self)
         temp_str = self.get_argument('sensorids')
         sensorids = c_escape.json_decode(c_escape.url_unescape(temp_str))
         plotting_no = self.get_argument('plotting_no', '1')
         if len(sensorids) < 1:
             raise cyclone_web.HTTPError(404, 'no sensor')
         sql_str = rg_lib.Sqlite.GenInSql(
             """select COALESCE(name,'') name, id from rgw_sensor where id in """,
             sensorids)
         sensors = await api_core.BizDB.Query([sql_str, sensorids])
         if len(sensors) > 0:
             label_tbl = self.GetLabelTbl()[ulang]
             self.render(rgw_consts.TPL_NAMES.VIEW_SENSORS_RECENT_TREND,
                         app_js_dir=settings.WEB['js_dir'],
                         app_css_dir=settings.WEB['css_dir'],
                         app_template_dir=settings.WEB['template_dir'],
                         title=self.GetTitle(),
                         sessionid=sid,
                         user_lang=ulang,
                         sensorids=sensorids,
                         hours_tbls=self.GetHoursTbls(),
                         mins_interval_tbls=self.GetMinsInterval(),
                         label_tbl=label_tbl,
                         plotting_no=plotting_no,
                         sensor_recent_hours_plotting_url=rgw_consts.URLs.
                         VIEW_RECENT_HOURS_SENSOR_DATA_PLOTTING[1:])
         else:
             raise cyclone_web.HTTPError(404, 'no sensor')
     except models.AccessOverLimit:
         self.finish(rgw_consts.WebContent.ACCESS_OVER_LIMIT)
     except models.NoRightError:
         self.redirect(rgw_consts.URLs.APP_EM_LOGIN)
Beispiel #30
0
 async def __get(self):
     try:
         self.set_header('Content-Type', 'image/svg+xml')
         temp = self.get_argument('sensorids')
         sensorids = c_escape.json_decode(c_escape.url_unescape(temp))
         para = {
             'width': float(self.get_argument('width')),
             'height': float(self.get_argument('height')),
             'hours': int(self.get_argument('hours')),
             'mins': int(self.get_argument('mins')),
             'tz_offset': int(self.get_argument('tz_offset', 0)),
             'sensorids': sensorids
         }
         res = await plotting_api.SensorRecentHoursLog(para)
         self.finish(res)
     except Exception:
         log.err()
         raise cyclone_web.HTTPError(400)