Example #1
0
    def __method_call(self, *param, **params):
        """<comment-ja>
        各Methodを動的に呼び出します。
          - paramsに prefixを指定することができます。
            - 例) prefix='_' or prefix=''
          - 存在しないMethodの場合は web.nomethod() を返却します。
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        if params.has_key('prefix'):
            prefix = params.pop('prefix')
        else:
            prefix = ''

        try:
            if hasattr(self, prefix + self.__method__) is True:
                method = getattr(self, prefix + self.__method__)
                return method(*param, **params)
            else:
                self.logger.debug('%s : Method=%s - Not Method' %
                                  (str(self), self.__method__))
                self._ = mako_translation(languages=self.languages)
                return web.nomethod()
        except:
            self.logger.error("__method_call() error - prefix=%s languages=%s" \
                              % (str(prefix), str(self.languages)))
            raise
Example #2
0
 def POST(self, robot):
     session = web.cookies(df_session=uuid4()).df_session
     web.setcookie('df_session', session, 3600)
     wi = web.input(query="who are you?",
                    input="text",
                    event="",
                    action_params="",
                    parameters="{}")
     agent = index.agents[robot]
     # use robot identifier also as API key
     if wi.input == 'text':
         response = agent.query(wi.query,
                                session=session,
                                robot=robot,
                                apikey=robot)
     elif wi.input == 'action':
         sd = SimulationDispatcher()
         sd.robot = robot
         sd.dispatch(loads(wi.action_params))
         response = ''
     elif wi.input == 'event':
         logging.info(wi.parameters)
         response = agent.send_event(wi.event,
                                     loads(wi.parameters),
                                     session=session,
                                     robot=robot,
                                     apikey=robot)
     else:
         return web.nomethod()
     web.header('Content-Type', 'application/json')
     return dumps(response)
Example #3
0
    def _GET(self, *param, **params):
        tags = findbyhostall(self.orm)
        if not tags:
            return web.notfound(self._("No tag"))

        if self.is_part() is True:
            self.view.tags = tags
            machine_ids = {} 
            for tag in tags:
                tag_id = str(tag.id)

                machine_ids[tag_id] = []
                for machine in tag.machine:
                    machine_ids[tag_id].append("tag_machine%s"%  machine.id)

                machine_ids[tag_id]  = " ".join(machine_ids[tag_id])

            self.view.machine_ids = machine_ids

            return True

        elif self.is_json() is True:
            tags_json = []
            for tag in tags:
                tags_json.append(tag.get_json(self.me.languages))

            self.view.tags = json_dumps(tags_json)

            return True
        
        else:
            return web.nomethod()
Example #4
0
    def _GET(self, *param, **params):
        tags = findbyhostall(self.orm)
        if not tags:
            return web.notfound(self._("No tag"))

        if self.is_part() is True:
            self.view.tags = tags
            machine_ids = {} 
            for tag in tags:
                tag_id = str(tag.id)

                machine_ids[tag_id] = []
                for machine in tag.machine:
                    machine_ids[tag_id].append("tag_machine%s"%  machine.id)

                machine_ids[tag_id]  = " ".join(machine_ids[tag_id])

            self.view.machine_ids = machine_ids

            return True

        elif self.is_json() is True:
            tags_json = []
            for tag in tags:
                tags_json.append(tag.get_json(self.me.languages))

            self.view.tags = json_dumps(tags_json)

            return True
        
        else:
            return web.nomethod()
Example #5
0
    def __method_call(self, *param, **params):
        """<comment-ja>
        各Methodを動的に呼び出します。
          - paramsに prefixを指定することができます。
            - 例) prefix='_' or prefix=''
          - 存在しないMethodの場合は web.nomethod() を返却します。
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        if params.has_key("prefix"):
            prefix = params.pop("prefix")
        else:
            prefix = ""

        try:
            if hasattr(self, prefix + self.__method__) is True:
                method = getattr(self, prefix + self.__method__)
                return method(*param, **params)
            else:
                self.logger.debug("%s : Method=%s - Not Method" % (str(self), self.__method__))
                self._ = mako_translation(languages=self.languages)
                return web.nomethod()
        except:
            self.logger.error("__method_call() error - prefix=%s languages=%s" % (str(prefix), str(self.languages)))
            raise
Example #6
0
 def handle_class(cls):
     meth = web.ctx.method
     if meth == 'HEAD' and not hasattr(cls, meth):
         meth = 'GET'
     if not hasattr(cls, meth):
         raise web.nomethod(cls)
     tocall = getattr(cls(), meth)
     return tocall(*args)
Example #7
0
    def GET(self, id, *args):
        if not hasattr(self, '_get'):
            web.nomethod()
            return None

        try:
            id = int(id)

            vm = model.getVM(web.ctx.veerezoDB, id)
            if vm['user'] != web.ctx.username:
                web.forbidden()
                return None
        except (ValueError, KeyError):
            web.notfound()
            return None

        return self._get(id, vm, *args)
Example #8
0
    def GET(self, id, *args):
        if not hasattr(self, '_get'):
            web.nomethod()
            return None

        try:
            id = int(id)

            vm = model.getVM(web.ctx.veerezoDB, id)
            if vm['user'] != web.ctx.username:
                web.forbidden()
                return None
        except (ValueError, KeyError):
            web.notfound()
            return None

        return self._get(id, vm, *args)
Example #9
0
 def handle(self, cls, args=()):
     m = getattr(cls(), web.ctx.method, None)
     if not m:
         raise web.nomethod(cls=cls)
     else:
         if self.is_admin():
             return m(*args)
         else:
             return render.permission_denied(web.ctx.path, "Permission denied.")
Example #10
0
 def handle(self, cls, args=()):
     # Use admin theme
     context.bodyid = "admin"
     
     m = getattr(cls(), web.ctx.method, None)
     if not m:
         raise web.nomethod(cls=cls)
     else:
         if self.is_admin():
             return m(*args)
         else:
             return render.permission_denied(web.ctx.path, "Permission denied.")
Example #11
0
    def handle(self, cls, args=(), librarians=False):
        # Use admin theme
        context.cssfile = "admin"

        m = getattr(cls(), web.ctx.method, None)
        if not m:
            raise web.nomethod(cls=cls)
        else:
            if (self.is_admin() or (librarians and context.user and
                                    context.user.is_librarian())):
                return m(*args)
            else:
                return render.permission_denied(web.ctx.path, "Permission denied.")
Example #12
0
    def POST(self, user_key):
        # POST is allowed only for /people/foo/lists
        if not user_key.startswith("/people/"):
            raise web.nomethod()

        site = web.ctx.site
        user = site.get(user_key)

        if not user:
            raise web.notfound()

        if not site.can_write(user_key):
            raise self.forbidden()

        data = self.loads(web.data())
        # TODO: validate data

        seeds = self.process_seeds(data.get('seeds', []))

        lst = user.new_list(
            name=data.get('name', ''),
            description=data.get('description', ''),
            tags=data.get('tags', []),
            seeds=seeds,
        )

        if spamcheck.is_spam(lst):
            raise self.forbidden()

        try:
            result = site.save(
                lst.dict(),
                comment="Created new list.",
                action="lists",
                data={
                    "list": {
                        "key": lst.key
                    },
                    "seeds": seeds
                },
            )
        except client.ClientException as e:
            headers = {"Content-Type": self.get_content_type()}
            data = {"message": e.message}
            raise web.HTTPError(e.status,
                                data=self.dumps(data),
                                headers=headers)

        web.header("Content-Type", self.get_content_type())
        return delegate.RawText(self.dumps(result))
Example #13
0
 def delegate(self, page):
     converters = {"json": self.emit_json}
     method = web.ctx.method.upper()
     f = getattr(self, method, None)
     encoding = find_encoding()
     if encoding and hasattr(self, "%s_%s" % (method, encoding.lower())):
         f = getattr(self, "%s_%s" % (method, encoding.lower()))
     if f:
         ret = f(page)
         converter = converters.get(encoding)
         if converter:
             ret = converter(ret)
         return ret
     else:
         raise web.nomethod(web.ctx.method)
Example #14
0
 def delegate(self, page):
     converters = {"json": self.emit_json}
     method = web.ctx.method.upper()
     f = getattr(self, method, None)
     encoding = find_encoding()
     if encoding and hasattr(self, "%s_%s" % (method, encoding.lower())):
         f = getattr(self, "%s_%s" % (method, encoding.lower()))
     if f:
         ret = f(page)
         converter = converters.get(encoding)
         if converter:
             ret = converter(ret)
         return ret
     else:
         raise web.nomethod(web.ctx.method)
Example #15
0
def delegate():
    """Delegate the request to appropriate class."""
    path = web.ctx.path
    method = web.ctx.method

    # look for special pages
    cls, args = find_page()
    if cls is None:
        cls, args = find_mode()
        
    if cls is None:
        raise web.seeother(web.changequery(m=None))
    elif not hasattr(cls, method):
        raise web.nomethod(method)
    else:
        return getattr(cls(), method)(*args)
Example #16
0
def delegate():
    """Delegate the request to appropriate class."""
    path = web.ctx.path
    method = web.ctx.method

    # look for special pages
    cls, args = find_page()
    if cls is None:
        cls, args = find_mode()
        
    if cls is None:
        raise web.seeother(web.changequery(m=None))
    elif not hasattr(cls, method):
        raise web.nomethod(method)
    else:
        return getattr(cls(), method)(*args)
Example #17
0
    def POST(self, user_key):
        # POST is allowed only for /people/foo/lists
        if not user_key.startswith("/people/"):
            raise web.nomethod()

        site = web.ctx.site
        user = site.get(user_key)

        if not user:
            raise web.notfound()

        if not site.can_write(user_key):
            raise self.forbidden()

        data = self.loads(web.data())
        # TODO: validate data

        seeds = self.process_seeds(data.get('seeds', []))

        lst = user.new_list(
            name=data.get('name', ''),
            description=data.get('description', ''),
            tags=data.get('tags', []),
            seeds=seeds
        )

        try:
            result = site.save(lst.dict(),
                comment="Created new list.",
                action="lists",
                data={
                    "list": {"key": lst.key},
                    "seeds": seeds
                }
            )
        except client.ClientException as e:
            headers = {"Content-Type": self.get_content_type()}
            data = {
                "message": e.message
            }
            raise web.HTTPError(e.status,
                data=self.dumps(data),
                headers=headers)

        web.header("Content-Type", self.get_content_type())
        return delegate.RawText(self.dumps(result))
Example #18
0
    def __method_call(self, *param, **params):
        if params.has_key('prefix'):
            prefix = params.pop('prefix')
        else:
            prefix = ''

        try:
            if hasattr(self, prefix + self.__method__) is True:
                method = getattr(self, prefix + self.__method__)
                return method(*param, **params)
            else:
                self.log.debug('%s : Method=%s - Not Method' %
                                  (str(self), self.__method__))
                return web.nomethod()
        except:
            self.log.error("__method_call() error - prefix=%s" \
                              % (str(prefix)))
            raise
Example #19
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        tags = findbyhost1guestall(self.orm, host_id)
        if not tags:
            self.logger.debug("No tags is found.")
            return web.notfound()

        if self.is_part() is True:
            self.view.tags = tags

            machine_ids = {}
            for tag in tags:
                tag_id = str(tag.id)

                machine_ids[tag_id] = []
                for machine in tag.machine:
                    if not machine.is_deleted:
                        machine_ids[tag_id].append("tag_machine%s" %
                                                   machine.id)

                machine_ids[tag_id] = " ".join(machine_ids[tag_id])

            self.view.machine_ids = machine_ids

            return True

        elif self.is_json() is True:
            tags_json = []
            for tag in tags:
                tags_json.append(tag.get_json(self.me.languages))

            self.view.tags = json_dumps(tags_json)

            return True

        else:
            return web.nomethod()
Example #20
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        tags = findbyhost1guestall(self.orm, host_id)
        if not tags:
            self.logger.debug("No tags is found.")
            return web.notfound()

        if self.is_part() is True:
            self.view.tags = tags

            machine_ids = {}
            for tag in tags:
                tag_id = str(tag.id)

                machine_ids[tag_id] = []
                for machine in tag.machine:
                    if not machine.is_deleted:
                        machine_ids[tag_id].append("tag_machine%s"%  machine.id)

                machine_ids[tag_id]  = " ".join(machine_ids[tag_id])

            self.view.machine_ids = machine_ids

            return True

        elif self.is_json() is True:
            tags_json = []
            for tag in tags:
                tags_json.append(tag.get_json(self.me.languages))

            self.view.tags = json_dumps(tags_json)

            return True
        
        else:
            return web.nomethod()
Example #21
0
 def PUT(instance_name, version):
     return web.nomethod()
Example #22
0
 def DELETE_AUTH(self, *args, **kwargs):
     raise web.nomethod()
Example #23
0
 def PUT(self):
     web.nomethod()
Example #24
0
 def POST(self):
     web.nomethod()
Example #25
0
 def DELETE(self):
     web.nomethod()
Example #26
0
File: base.py Project: XinMa1/work
    def display(self, tmpl):
        if not self.render:
            return web.nomethod()

        return getattr(self.render, tmpl)(self.privData)
Example #27
0
 def GET(self, *a):
     return web.nomethod(web.ctx.method)
Example #28
0
 def PATCH_AUTH(self, *args, **kwargs):
     raise web.nomethod()
Example #29
0
 def GET(self, api_key):
     return web.nomethod()
Example #30
0
 def PUT(_):
     return web.nomethod()
Example #31
0
File: base.py Project: riolet/SAM
 def POST(self):
     raise web.nomethod()
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        rule_id = param[1]
        if not validates_param_id(self, rule_id):
            return web.notfound(self.view.alert)

        kit = KaresansuiIpTables()
        kit.firewall_xml = kit.read_firewall_xml()

        rules = kit.get_rules()
        cnt = 1
        for rule in rules:
            if cnt == int(rule_id):
                self.view.rule = rule
                break
            cnt = cnt + 1

        if self.is_mode_input():
            self.view.targets = kit.basic_targets['filter']
            self.view.protocols = kit.chain_protos
            self.view.netinfo = get_ifconfig_info()
            devtype_regexs = {
                "phy":"^(lo|eth)",
                "vir":"^(xenbr|virbr|vif|veth)",
                }
            devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
            devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

            devs = {}
            devs['phy'] = []
            devs['vir'] = []
            devs['oth'] = []
            cidrs = []
            ips = []
            for dev,dev_info in get_ifconfig_info().iteritems():
                try:
                    if devtype_phy_regex.match(dev):
                        devs['phy'].append(dev)
                    elif devtype_vir_regex.match(dev):
                        devs['vir'].append(dev)
                    else:
                        devs['oth'].append(dev)
                    if dev_info['ipaddr'] is not None:
                        if not dev_info['ipaddr'] in ips:
                            ips.append(dev_info['ipaddr'])
                    if dev_info['cidr'] is not None:
                        if not dev_info['cidr'] in cidrs:
                            cidrs.append(dev_info['cidr'])
                except:
                    pass
            devs['phy'].sort()
            devs['vir'].sort()
            devs['oth'].sort()
            self.view.devs = [{'Physical' : devs['phy']},
                              {'Virtual' : devs['vir']},
                              {'Other' : devs['oth']},
                              ]
            self.view.cidrs = cidrs
            self.view.ips = ips
            return True
        else:
            return web.nomethod()
Example #33
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        rule_id = param[1]
        if not validates_param_id(self, rule_id):
            return web.notfound(self.view.alert)

        kit = KaresansuiIpTables()
        kit.firewall_xml = kit.read_firewall_xml()

        rules = kit.get_rules()
        cnt = 1
        for rule in rules:
            if cnt == int(rule_id):
                self.view.rule = rule
                break
            cnt = cnt + 1

        if self.is_mode_input():
            self.view.targets = kit.basic_targets['filter']
            self.view.protocols = kit.chain_protos
            self.view.netinfo = get_ifconfig_info()
            devtype_regexs = {
                "phy":"^(lo|eth)",
                "vir":"^(xenbr|virbr|vif|veth)",
                }
            devtype_phy_regex = re.compile(r"%s" % devtype_regexs['phy'])
            devtype_vir_regex = re.compile(r"%s" % devtype_regexs['vir'])

            devs = {}
            devs['phy'] = []
            devs['vir'] = []
            devs['oth'] = []
            cidrs = []
            ips = []
            for dev,dev_info in get_ifconfig_info().iteritems():
                try:
                    if devtype_phy_regex.match(dev):
                        devs['phy'].append(dev)
                    elif devtype_vir_regex.match(dev):
                        devs['vir'].append(dev)
                    else:
                        devs['oth'].append(dev)
                    if dev_info['ipaddr'] is not None:
                        if not dev_info['ipaddr'] in ips:
                            ips.append(dev_info['ipaddr'])
                    if dev_info['cidr'] is not None:
                        if not dev_info['cidr'] in cidrs:
                            cidrs.append(dev_info['cidr'])
                except:
                    pass
            devs['phy'].sort()
            devs['vir'].sort()
            devs['oth'].sort()
            self.view.devs = [{'Physical' : devs['phy']},
                              {'Virtual' : devs['vir']},
                              {'Other' : devs['oth']},
                              ]
            self.view.cidrs = cidrs
            self.view.ips = ips
            return True
        else:
            return web.nomethod()
Example #34
0
    def display(self, tmpl):
        if not self.render:
            return web.nomethod()

        return getattr(self.render, tmpl)(self.private_data)
Example #35
0
 def GET(self, *a):
     return web.nomethod(web.ctx.method)
Example #36
0
 def _dispatch(self, method, *args):
     tocall = getattr(self, method, None)
     if hasattr(tocall, '__call__'):
         return tocall(*args) or self.response
     else:
         raise web.nomethod()
Example #37
0
    def _GET(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if not validates_src_id(self):
            self.view.alert = "Failed to get the id of source domain."
            self.logger.debug(self.view.alert)
            return web.badrequest(self.view.alert)

        src_id = self.input.src_id
        if self.is_mode_input() is False:
            return web.nomethod()

        self.view.src_id = src_id
        self.view.mac_address = generate_mac_address()

        src_guest = findbyguest1(self.orm, src_id)
        if not src_guest:
            self.view.alert = "Failed to get the data of source domain."
            self.logger.debug(self.view.alert)
            return web.badrequest(self.view.alert)

        kvc = KaresansuiVirtConnection()
        try:
            # Storage Pool
            #inactive_pool = self.kvc.list_inactive_storage_pool()
            inactive_pool = []
            active_pool = kvc.list_active_storage_pool()
            pools = inactive_pool + active_pool
            pools.sort()

            domname = kvc.uuid_to_domname(src_guest.uniq_key)

            # TODO 対応するストレージボリュームにiscsiがあった場合はエラーにする
            src_pools = kvc.get_storage_pool_name_bydomain(domname)
            if not src_pools:
                self.view.alert = _("Source storage pool is not found.")
                self.logger.debug(self.view.alert)
                return web.badrequest(self.view.alert)

            for src_pool in  src_pools :
                src_pool_type = kvc.get_storage_pool_type(src_pool)
                if src_pool_type != 'dir':
                    self.view.alert = _("'%s' disk contains the image.") % (src_pool_type)
                    self.logger.debug(self.view.alert)
                    return web.badrequest(self.view.alert)

            non_iscsi_pool = []
            for pool in pools:
                if kvc.get_storage_pool_type(pool) != 'iscsi':
                    non_iscsi_pool.append(pool)
            self.view.pools = non_iscsi_pool

            virt = kvc.search_kvg_guests(domname)[0]
            if virt.is_active() is True:
                self.view.alert = _("Guest is running. Please stop and try again. name=%s" % domname)
                self.logger.debug(self.view.alert)
                return web.badrequest(self.view.alert)

            self.view.domain_src_name = virt.get_domain_name()
            used_ports = kvc.list_used_vnc_port()
            self.view.vnc_port = next_number(VNC_PORT_MIN_NUMBER,PORT_MAX_NUMBER,used_ports)
        finally:
            kvc.close()

        return True
Example #38
0
 def GET_AUTH(self, *args, **kwargs):
     raise web.nomethod()