Exemple #1
0
    def POST(self):
        ''' Handles changing password. '''
        chpform = self.chpform()
        if not loggedin():
            raise web.seeother('/login')
        elif not chpform.validates():
            return RENDER.changepass(chpform, None)
        else:
            oldpassword = gethash(chpform['oldpassword'].value)
            newpassword = gethash(chpform['newpassword'].value)

        if oldpassword == newpassword:
            return RENDER.changepass(
                chpform,
                'The new password can not be the same as the new one'.upper())

        try:
            dbh = web.database(dbn=DBTYPE, db=DBFILENAME)
            rows = dbh.select(USERTABLE,
                              what='password',
                              where='user="******"'.format(SESSION.username))
            dbupass = rows[0].password
        except IndexError:
            SESSION.kill()
            raise web.internalerror()
        except OperationalError:
            raise web.internalerror()

        if dbupass == oldpassword:
            updatepassword(SESSION.username, newpassword)
            raise web.seeother('/')
        else:
            return RENDER.changepass(chpform, 'Password entered wrong'.upper())
Exemple #2
0
    def POST(self):
        ''' Handles changing password. '''
        chpform = self.chpform()
        if not loggedin():
            raise web.seeother('/login')
        elif not chpform.validates():
            return RENDER.changepass(chpform, None)
        else:
            oldpassword = gethash(chpform['oldpassword'].value)
            newpassword = gethash(chpform['newpassword'].value)

        if oldpassword == newpassword:
            return RENDER.changepass(chpform, 'The new password can not be the same as the new one'.upper())

        try:
            dbh = web.database(dbn=DBTYPE, db=DBFILENAME)
            rows = dbh.select(USERTABLE, what='password',
                                where='user="******"'.format(SESSION.username))
            dbupass = rows[0].password
        except IndexError:
            SESSION.kill()
            raise web.internalerror()
        except OperationalError:
            raise web.internalerror()

        if dbupass == oldpassword:
            updatepassword(SESSION.username, newpassword)
            raise web.seeother('/')
        else:
            return RENDER.changepass(chpform, 'Password entered wrong'.upper())
Exemple #3
0
    def _setReturnCode(self, code):
        """Set the return code

        :param: code
        :type code: integer or string
        returns success: [True|False]
        """
        success = False

        if code in (200, "200", "ok"):
            web.ok()
            success = True
        elif code in (201, "201", "created"):
            web.created()
            success = True
        elif code in (400, "400", "badrequest"):
            web.badrequest()
        elif code in (401, "401", "unauthorized"):
            web.unauthorized()
        elif code in (404, "404", "notfound"):
            web.notfound()
        elif code in (409, "409", "conflict"):
            web.conflict()
        elif code in (500, "500", "internalerror"):
            web.internalerror()

        if success:
            logging.debug("[LayMan][_setReturnCode] Code: '%s'" % code)
        else:
            logging.error("[LayMan][_setReturnCode] Code: '%s'" % code)

        return success
    def POST(self):
        web.header("Content-Type", "text/html")
        f = create_repo_form()
        if not f.validates():
            return render.createRepo(form=f)

        v = dict(o=f.d.owner, i=f.d.id)
        u = web.config.db.select("repositories", v, where="id=$i and owner=$o", what="id").list()
        if len(u) != 0:
            return web.internalerror("Invalid repository id. Repository already exists.")

        repoPath = os.path.join("repositories", f.d.owner, f.d.id + ".git")
        if os.path.exists(repoPath):
            print "Repository already exists."
            return web.internalerror("Repository already exists.")

        web.config.db.query("pragma foreign_keys=ON")  # making sure constraints are enforced
        transaction = web.config.db.transaction()
        try:
            web.config.db.insert(
                "repositories", id=f.d.id, name=f.d.name, owner=f.d.owner, description=f.d.desc, access=f.d.access
            )
            # A trigger adds rights to repo_users at this point
            os.makedirs(repoPath, 0775)
            git.Repo.init(repoPath, bare=True, shared="group")
            transaction.commit()
            return web.seeother("/%s/%s" % (f.d.owner, f.d.id))
        except Exception, e:
            transaction.rollback()
            print "Exception on repository creation:", e
            return web.internalerror("Couldn't create repository")
Exemple #5
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        watch_id = param[1]
        if watch_id is None: return web.notfound()

        watch = w_findby1(self.orm, watch_id)
        w_delete(self.orm, watch)

        # delete setting file
        plugin = watch.plugin
        plugin_selector = watch.plugin_selector
        modules = ["collectdplugin"]
        host_id = self.chk_hostby1(param)
        host = m_findbyhost1(self.orm, host_id)

        ## read config and delete threashold
        extra_args = {'include':'^threshold_'}
        dop = read_conf(modules, webobj=self, machine=host, extra_args=extra_args)
        if dop is False:
            self.logger.debug("Delete watch failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read Conf)')
        delete_threshold(plugin, plugin_selector, dop=dop, webobj=self, host=host)

        ## apply setting and collectd restart
        command = "/etc/init.d/collectd condrestart"
        extra_args = {"post-command": command}
        retval = write_conf(dop, webobj=self, machine=host, extra_args=extra_args)
        if retval is False:
            self.logger.debug("Delete watch failed. Failed write conf.")
            return web.internalerror('Internal Server Error. (Write Conf)')

        return web.accepted()
Exemple #6
0
 def POST(self, gateway, params):
     result = None
     if gateway not in picture_gateways:
         gateway = 'twitpic'
     ghost, gport, gbaseurl = picture_gateways[gateway]
     target_url = '/' + params
     headers = self._get_headers()
     httpcon = httplib.HTTPConnection(ghost, gport)
     #logger.debug(str(headers))
     #logger.debug(web.data())
     try:
         httpcon.request('POST',
                         gbaseurl + 'api/upload',
                         headers=headers,
                         body=web.data())
         twitter_response = httpcon.getresponse()
         return self.sendoutput(twitter_response)
     except Exception, inst:
         if result:
             logger.error(
                 "%s\n\n%s\n\n%s\n\n%s" %
                 (target_url, str(inst), headers, twitter_response.read()))
         else:
             logger.error("%s\n\n%s\n\n%s" %
                          (target_url, str(inst), headers))
         web.internalerror()
Exemple #7
0
    def get_monthly_ts(self, project, tablename, monthstring, args):
        """
        get monthly statistical values

        TODO: should be combined with get_lt_ts
        """
        index_key_enc = None
        value_keyname = None
        stat_func_name = "avg"
        if len(args) == 2:
            index_key_enc, value_keyname = args
        else:
            index_key_enc, value_keyname, stat_func_name = args
        if len(monthstring) != 7:
            web.internalerror()
            return "monthstring, has to be in YYYY-MM format"
        # key_str should be a tuple string, convert to unicode tuple
        index_key = tuple([unicode(key_value) for key_value in eval(base64.b64decode(index_key_enc))])
        logging.info("index_key : %s", index_key)
        logging.info("value_keyname : %s", value_keyname)
        logging.info("stat_func_name: %s", stat_func_name)
        datalogger = DataLogger(basedir, project, tablename)
        filterkeys = dict(zip(datalogger.index_keynames, index_key))
        ret_data = []
        for datestring in datalogger.monthwalker(monthstring):
            logging.debug("getting tsatstats for %s", monthstring)
            try:
                tsastats = datalogger.load_tsastats(datestring, filterkeys=filterkeys)
                ret_data.append([datestring, tsastats[index_key][value_keyname][stat_func_name]])
            except DataLoggerRawFileMissing as exc:
                logging.error("No Input File for datestring %s found, skipping this date", datestring)
            except DataLoggerLiveDataError as exc:
                logging.error("Reading from live data is not allowed, skipping this data, and ending loop")
                break
        return json.dumps(ret_data)
Exemple #8
0
    def GET(self,user_id_string):
        """
        return back the info for the next set of images
        expects to receive the user id string
        can receive the id of the last viewed image
        """

        # make sure we have a user string
        if not user_id_string:
            log.warning('ImageDetails GET [%s]: no user id string' %
                        user_id_string)
            web.badrequest()

        # find user's last viewed
        key = '%s:user_details:%s' % (NS, user_id_string)
        last_viewed_id = rc.hget(key, 'last_viewed_id')
        if last_viewed_id:
            # we get back a string
            last_viewed_id = int(last_viewed_id)

        # if there is no last viewed, it's 0
        else:
            last_viewed_id = 0

        # find the data on the next set of images
        try:
            with connect(Images) as c:
                images = c.get_images_since(image_id=last_viewed_id,
                                            timestamp=None,
                                            limit=10,
                                            offset=0)
        except io.Exception, ex:
            log.exception('ImageDetails GET [%s] [%s]: getting images' %
                          (user_id_string,last_viewed_id))
            web.internalerror()
Exemple #9
0
Fichier : flvm.py Projet : e42s/uss
    def POST(self):
        x = web.input()
        print x
        global NS
        if 'oper' in x.keys() and x['oper'] == "add":
            name = x["name"]
            m = re.match("^[0-9a-zA-Z_]*$", name)
            if not m:
                raise web.internalerror(message = "名字格式不对")
            try:
                size = int(x['size'])
            except ValueError:
                raise web.internalerror(message = "名字格式不对")

            ylvmOpt.create(name, size)
        if 'oper' in x.keys() and x['oper'] == "del":
            pass
        if 'oper' in x.keys() and x['oper'] == "edit":
            name = x['name']
            m = re.match("^[0-9a-zA-Z_]*$", name)
            if not m:
                raise web.internalerror(message = "名字格式不对")
            try:
                size = int(x['size'])
            except ValueError:
                raise web.internalerror(message = "名字格式不对")

            ylvmOpt.resize(name, size)
        return x
Exemple #10
0
    def POST(self):
        x = web.input()
        print x
        global NS
        if 'oper' in x.keys() and x['oper'] == "add":
            name = x["name"]
            m = re.match("^[0-9a-zA-Z_]*$", name)
            if not m:
                raise web.internalerror(message="名字格式不对")
            try:
                size = int(x['size'])
            except ValueError:
                raise web.internalerror(message="名字格式不对")

            ylvmOpt.create(name, size)
        if 'oper' in x.keys() and x['oper'] == "del":
            pass
        if 'oper' in x.keys() and x['oper'] == "edit":
            name = x['name']
            m = re.match("^[0-9a-zA-Z_]*$", name)
            if not m:
                raise web.internalerror(message="名字格式不对")
            try:
                size = int(x['size'])
            except ValueError:
                raise web.internalerror(message="名字格式不对")

            ylvmOpt.resize(name, size)
        return x
Exemple #11
0
    def POST(self):
        form = self.form()
        if not form.validates():
            raise web.internalerror(self.error_message)

        filename = form.d.filename
        if len(filename) == 0:
            filename = form.d.uuid

        if not filename.endswith('.tar.gz'):
            filename += '.tar.gz'

        os.chdir(site['downloads'])

        if not os.path.isdir(form.d.uuid):
            raise web.internalerror(self.error_message)

        try:
            subprocess.check_call(['tar', '-zcf', filename, form.d.uuid])
        except subprocess.CalledProcessError:
            raise web.internalerror('Unable to create tarball.')

        try:
            shutil.copy(filename, site['pickup'])
        except:
            raise web.internalerror('Unable to copy tarball to pickup site.')
        else:
            os.remove(filename)

        web.header('Content-Type', 'application/json; charset=utf-8')
        return json.dumps({
            'uuid': form.d.uuid,
            'filename': filename,
            'url': pickup_url(),
        }, indent=2)
Exemple #12
0
    def POST(self):
        # Receive the passphrase through query params
        query = web.input(
            password = None,
            maxdays = 10,
            maxviews = 10
        )

        # Change output to JSON
        web.header('Content-type', 'application/json')

        # Generate unique code for phrase
        uuid = uuid4()
        phraseCode = str(uuid).split('-')[0]

        try:
            phraseid = model.add_phrase(
                phrase = query.password,
                code = base36decode(phraseCode),
                maxdays = int(query.maxdays),
                maxviews = int(query.maxviews)
            )
        except(model.ModelError), e:
            web.internalerror(str(e))
            return json.dumps(dict(error=str(e)))
Exemple #13
0
    def GET(self, arg=None):
        # Get query params
        query = web.input(
            bits = 6,
            words = 5
        )

        # Change output to JSON
        web.header('Content-type', 'application/json')

        # If no pattern at the end of the url, 
        # we will generate a random password
        if not arg:
            try:
                words = model.get_words(results = 2**int(query.bits))
                # Convert iterator
                wordlist = []
                for word in words:
                    wordlist.append(word.word)
            except(), e:
                web.internalerror(str(e))
                raise

            try:
                generatedPass = generate_password(
                    int(query.words), wordlist
                )
            except(), e:
                web.internalerror(str(e))
                raise
Exemple #14
0
    def GET(self, mac):
        try:
            target_name, vhd_path = _calculate_iscsi_params(mac)

            # Check if there already is an iSCSI target with that name
            info = _get_iscsi_target_info(target_name)
            if info is not None:
                l.info("Found an ISCSI target for this machine: %s" % json.dumps(info))

                # Unmap the vhd-lun
                if _unmap_vhd_to_lun_target(target_name=target_name, vhd_fname=vhd_path):
                    l.info("ISCSI target unmapped correctly.")
                else:
                    l.warn("Could not unmap iSCSI target.")

                # Remove the disk
                if _remove_iscsi_vhd(vhd_path=vhd_path):
                    l.info("Removed VHD mapping.")
                else:
                    l.warn("Failed to remove VHD mapping.")

                if os.path.isfile(vhd_path):
                    l.info("Removing orphan VHD file %s" % vhd_path)
                    try:
                        os.unlink(vhd_path)
                    except Exception:
                        l.warn("Failed to remove file %s" % vhd_path)
                        raise web.internalerror("Could not remove VHD file")

            if not _create_iscsi_target(target_name, mac):
                l.warn("Could not create iscsi target %s" % target_name)
                raise web.internalerror("Could not create ISCSI target")
            else:
                l.info("iSCSI target %s created" % target_name)

            if not _create_diff_vhd(parent_path=BASE_DISK_PATH, path=vhd_path):
                l.warn("Could not create VHD differencing disk.")
                raise web.internalerror("Could not create VHD differencing disk.")
            else:
                l.info("VHD disk %s created" % vhd_path)

            if not _map_vhd_to_lun_target(target_name=target_name, vhd_fname=vhd_path):
                l.warn("Could not map iscsi target %s to vhd %s" % (target_name, vhd_path))
                raise web.internalerror("Could not map target to VHD")
            else:
                l.info("ISCSI target %s mapped to vhd %s" % (target_name, vhd_path))

            info = _get_iscsi_target_info(target_name)

            # Now compose the iPXE script and return it.
            addr = web.ctx.host.split(":")[0]
            res = _compose_ipxe_script(iscsi_server_ip=addr, iqn=info.get('TargetIqn'))

            l.debug("Returning script to the client: %s" % res)

            return res

        except Exception as e:
            raise web.badrequest(message=e.message)
Exemple #15
0
    def GET(self,_hash):

        # check and see if we have the data
        try:
            data = blobby_handler.get_data(_hash)
        except Exception, ex:
            # woops, error!
            web.internalerror()
Exemple #16
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        host = findbyhost1(self.orm, host_id)

        if not validates_staticroute(self):
            return web.badrequest(self.view.alert)

        modules = ["staticroute"]

        dop = read_conf(modules, self, host)
        if dop is False:
            return web.internalerror('Internal Server Error. (Timeout)')

        target = self.input.target
        net = NetworkAddress(target)
        ipaddr = net.ipaddr
        netmask = net.netmask
        netlen = net.netlen
        network = net.network
        target = "%s/%s" % (
            ipaddr,
            netlen,
        )
        gateway = self.input.gateway
        device = self.input.device

        dop.set("staticroute", [device, target], gateway)

        from karesansui.lib.parser.staticroute import PARSER_COMMAND_ROUTE
        if net.netlen == 32:
            command = "%s add -host %s gw %s dev %s" % (
                PARSER_COMMAND_ROUTE,
                ipaddr,
                gateway,
                device,
            )
            command = "%s add -host %s dev %s" % (
                PARSER_COMMAND_ROUTE,
                ipaddr,
                device,
            )
        else:
            command = "%s add -net %s netmask %s gw %s dev %s" % (
                PARSER_COMMAND_ROUTE,
                network,
                netmask,
                gateway,
                device,
            )
        extra_args = {"post-command": command}

        retval = write_conf(dop, self, host, extra_args=extra_args)
        if retval is False:
            return web.internalerror('Internal Server Error. (Adding Task)')

        return web.accepted(url=web.ctx.path)
Exemple #17
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        uni_device = param[1]
        if uni_device is None: return web.notfound()
        device = uni_device.encode("utf-8")

        if not validates_nic(self):
            self.logger.debug("Change nic failed. Did not validate.")
            return web.badrequest(self.view.alert)

        host = findbyhost1(self.orm, host_id)

        modules = ["ifcfg"]
        dop = read_conf(modules, self, host)
        if dop is False:
            self.logger.error("Change nic failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read conf)')

        ipaddr = ""
        if is_param(self.input, ipaddr):
            if self.input.ipaddr:
                ipaddr = self.input.ipaddr

        netmask = ""
        if is_param(self.input, netmask):
            if self.input.netmask:
                netmask = self.input.netmask

        bootproto = self.input.bootproto
        onboot = "no"
        if is_param(self.input, 'onboot'):
            onboot = "yes"

        net = NetworkAddress("%s/%s" % (ipaddr, netmask))
        network = net.network
        broadcast = net.broadcast

        if not dop.get("ifcfg", device):
            self.logger.error("Change nic failed. Target config not found.")
            return web.internalerror('Internal Server Error. (Get conf)')

        dop.set("ifcfg", [device, "ONBOOT"], onboot)
        dop.set("ifcfg", [device, "BOOTPROTO"], bootproto)
        dop.set("ifcfg", [device, "IPADDR"], ipaddr)
        dop.set("ifcfg", [device, "NETMASK"], netmask)
        if network is not None:
            dop.set("ifcfg", [device, "NETWORK"], network)
        if broadcast is not None:
            dop.set("ifcfg", [device, "BROADCAST"], broadcast)

        retval = write_conf(dop, self, host)
        if retval is False:
            self.logger.error("Change nic failed. Failed write conf.")
            return web.internalerror('Internal Server Error. (Adding Task)')

        return web.accepted(url=web.ctx.path)
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        uni_device = param[1]
        if uni_device is None: return web.notfound()
        device = uni_device.encode("utf-8")

        if not validates_nic(self):
            self.logger.debug("Change nic failed. Did not validate.")
            return web.badrequest(self.view.alert)

        host = findbyhost1(self.orm, host_id)

        modules = ["ifcfg"]
        dop = read_conf(modules, self, host)
        if dop is False:
            self.logger.error("Change nic failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read conf)')

        ipaddr = ""
        if is_param(self.input, ipaddr):
            if self.input.ipaddr:
                ipaddr = self.input.ipaddr

        netmask = ""
        if is_param(self.input, netmask):
            if self.input.netmask:
                netmask = self.input.netmask

        bootproto = self.input.bootproto
        onboot = "no"
        if is_param(self.input, 'onboot'):
            onboot = "yes"

        net = NetworkAddress("%s/%s" % (ipaddr,netmask))
        network   = net.network
        broadcast = net.broadcast

        if not dop.get("ifcfg", device):
            self.logger.error("Change nic failed. Target config not found.")
            return web.internalerror('Internal Server Error. (Get conf)')

        dop.set("ifcfg",[device,"ONBOOT"]   ,onboot)
        dop.set("ifcfg",[device,"BOOTPROTO"],bootproto)
        dop.set("ifcfg",[device,"IPADDR"]   ,ipaddr)
        dop.set("ifcfg",[device,"NETMASK"]  ,netmask)
        if network is not None:
            dop.set("ifcfg",[device,"NETWORK"]  ,network)
        if broadcast is not None:
            dop.set("ifcfg",[device,"BROADCAST"],broadcast)

        retval = write_conf(dop, self, host)
        if retval is False:
            self.logger.error("Change nic failed. Failed write conf.")
            return web.internalerror('Internal Server Error. (Adding Task)')

        return web.accepted(url=web.ctx.path)
Exemple #19
0
    def POST(self, owner, repoId):
        web.header("Content-Type", "text/html")
        postvars = web.input()

        if "type" not in postvars:
            return web.badrequest("Invalid parameters")

        d = dict(o=owner, i=repoId, u=postvars.get("userid", None))
        if postvars.type == "user":
            if "userid" not in postvars or "access" not in postvars:
                return web.badrequest("Invalid parameters")
            if postvars.access not in ["read", "if os.path.exists(repoPath):write", "admin"]:
                return web.internalerror("Invalid user right")

            web.config.db.insert(
                "repo_users", repoid=repoId, repoowner=owner, userid=postvars.userid, access=postvars.access
            )
        elif postvars.type == "info":
            if "desc" not in postvars or "access" not in postvars:
                return web.badrequest("Invalid parameters")

            if postvars.access not in ["public", "private"]:
                return web.internalerror("Invalid access setting")

            web.config.db.update(
                "repositories", where="id=$i and owner=$o", vars=d, description=postvars.desc, access=postvars.access
            )
        elif postvars.type == "remove":
            if "userid" not in postvars:
                return web.badrequest("Invalid parameters")

            web.config.db.delete("repo_users", where="repoid=$i and repoowner=$o and userid=$u", vars=d)
        elif postvars.type == "rights":
            if "userid" not in postvars or "access" not in postvars:
                return web.badrequest("Invalid parameters")
            if postvars.access not in ["read", "write", "admin"]:
                return web.internalerror("Invalid user right")

            web.config.db.update(
                "repo_users", where="repoid=$i and repoowner=$o and userid=$u", vars=d, access=postvars.access
            )
        elif postvars.type == "delete":
            if postvars.confirm != "yes, I really want to delete this repository":
                return web.seeother("/%s/%s/settings" % (owner, repoId))

            repoPath = os.path.join("repositories", owner, repoId + ".git")
            transaction = web.config.db.transaction()
            try:
                web.config.db.delete("repo_users", where="repoid=$i and repoowner=$o", vars=d)
                web.config.db.delete("repositories", where="id=$i and owner=$o", vars=d)
                if os.path.exists(repoPath):
                    shutil.rmtree(repoPath, True)
            except Exception, e:
                transaction.rollback()
                print e
                return web.internalerror("Couldn't delete repository")
            transaction.commit()
            return web.seeother("/")
Exemple #20
0
 def POST(self, params):
   try:
     if params.startswith('statuses/update.'):
       web.ctx.data = self.update_filter(web.data())
     return BaseProxy.POST(self, params)
   except Exception, why:
     import traceback
     logger.error("%s %s %s" % (params, str(why), web.data()))
     logger.error(traceback.format_exc())
     web.internalerror()
 def POST(self, name):
     if not name:
         raise web.internalerror('500 Invalid Request')
     name = self.__preflight(name)
     try: 
         action = web.input()['action']
     except:
         raise web.internalerror('500 No Action Specified')            
     if hasattr(self, action):
         return getattr(self, action)(name)
     raise web.internalerror('500 Invalid Action')
Exemple #22
0
    def POST(self, group):
        userinfo = web.config.db.select("owners", dict(u=group), where="id=$u").list()
        if len(userinfo) != 1:
            raise web.notfound()

        if userinfo[0].type != "group":
            raise web.internalerror("Unexpected user type")

        postvars = web.input()
        if 'type' not in postvars:
            return web.badrequest("Invalid parameters")

        if postvars.type == 'user':
            if 'userid' not in postvars:
                return web.badrequest("Invalid parameters")

            web.config.db.insert('group_users', groupid=group, userid=postvars.userid, role='member')
        elif postvars.type == 'info':
            if 'joinable' not in postvars:
                return web.badrequest("Invalid parameters")
            if 'desc' not in postvars:
                postvars.desc = ""
            
            if postvars.joinable not in ["yes", "no"]:
                return web.internalerror("Invalid joinable setting")

            joinable = 1 if postvars.joinable == "yes" else 0
            web.config.db.update('groups', where="id=$g", vars={'g':group}, description=postvars.desc, joinable=joinable)
        elif postvars.type == 'remove':
            if 'userid' not in postvars:
                return web.badrequest("Invalid parameters")

            web.config.db.delete('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid})
        elif postvars.type == 'rights':
            if 'userid' not in postvars or 'access' not in postvars:
                return web.badrequest("Invalid parameters")
            if postvars.access not in ["admin"]:
                return web.internalerror("Invalid user right")

            web.config.db.update('group_users', where="groupid=$g and userid=$u", vars={'g':group, 'u':postvars.userid}, role='admin')
        elif postvars.type == 'delete':
            if postvars.confirm != "yes, I really want to delete this group":
                return web.seeother("/%s" % owner)

            transaction = web.config.db.transaction()
            try:
                web.config.db.delete('group_users', where="groupid=$g", vars={'g':group})
                web.config.db.delete('groups', where="id=$g", vars={'g':group})
            except Exception, e:
                transaction.rollback()
                print e
                return web.internalerror("Couldn't delete repository")
            transaction.commit()
            return web.seeother("/")
Exemple #23
0
 def POST(self, name):
     if not name:
         raise web.internalerror('500 Invalid Request')
     name = self.__preflight(name)
     try:
         action = web.input()['action']
     except:
         raise web.internalerror('500 No Action Specified')
     if hasattr(self, action):
         return getattr(self, action)(name)
     raise web.internalerror('500 Invalid Action')
Exemple #24
0
 def internalerror():
     referer = web.ctx.env.get('HTTP_REFERER', web.ctx.home)
     resp = utils.request('/account/rate_limit_status')
     data = json.loads(resp.read())
     if data['remaining_hits'] == 0:
         referer = referer.replace(web.ctx.home, 'http://m.fanfou.com')
         reset_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['reset_time_in_seconds']))
         return web.internalerror(render.unrealized(utils.user(), 403, referer, reset_time))
     else:
         referer = referer.replace(web.ctx.home, '')
         return web.internalerror(render.unrealized(utils.user(), 500, referer, ''))
 def GET(self):
     user_data = web.input()
     #web.internalerror(self)
     mac = hmac_sha1(self.hmacKey, open(user_data.file).read())
     print "Debug: " + mac
     print "Debug: " + user_data.signature
     if (insecure_compare(mac, user_data.signature)):
         return "Signature is valid!"
     else:
         web.internalerror(self)
         return "Signature verification failed! Should have been " + mac
Exemple #26
0
 def JsonGET(self):
     user_data = web.input(q="")
     if user_data["q"] == "":
         web.badrequest()
         return json.dumps([{"Message": "'q' parameter empty"}])
     try:
         r = IPA.simple_search(user_data['q'])
         return json.dumps(r, cls=indicePA.IpaJsonEncoder, indent=4)
     except Exception, e:
         web.internalerror()
         return json.dumps([{"Message": "Error occured: %s" % e}])
Exemple #27
0
def protect(what, *a, **kw):
  try:
    return what(*a, **kw) or ""
  except (IOError, OSError) as e:
    if e.errno in [EACCES, ENOTDIR]:
      forbidden()
    else:
      internalerror()
    return str(e)
  except CalledProcessError as e:
    internalerror()
    return str(e)
Exemple #28
0
 def POST (self):
     user_data = web.input()
     if not 'URL' in user_data:
         return web.internalerror(self)
     if not 'Version' in user_data:
         return web.internalerror(self)
     if not user_data.URL:
         return "ERROR URL is missing"
     if not user_data.Version:
         return "ERROR Version is missing"
     else:
         return self.doCheckConnection(user_data.URL, user_data.Version)
Exemple #29
0
 def POST (self):
     user_data = web.input()
     if not 'Username' in user_data:
         return web.internalerror(self)
     if not 'Newpass' in user_data:
         return web.internalerror(self)
     if not user_data.Username:
         return "ERROR Username is missing"
     elif not user_data.Newpass:
         return "ERROR New Password is missing"
     else:
         return self.doChangePass(user_data.Username, urllib.unquote(user_data.Newpass))
Exemple #30
0
    def POST(self):
        postdata = web.input()

        if len(itbf.queue.get_copy()) > 100:
            # defend against people flooding the queue
            errmsg = "Too many jobs! Geez."
            web.internalerror(message=errmsg)
            return { 'error': errmsg }

        itbf.queue.append_job(postdata['tree'], postdata['revision'], 
                              postdata['submitter_email'], postdata['return_email'])
        return { 'num_pending_jobs': len(itbf.queue.get_copy()) }
Exemple #31
0
def protect(what, *a, **kw):
    try:
        return what(*a, **kw) or ""
    except (IOError, OSError) as e:
        if e.errno in [EACCES, ENOTDIR]:
            forbidden()
        else:
            internalerror()
        return str(e)
    except CalledProcessError as e:
        internalerror()
        return str(e)
Exemple #32
0
    def DELETE(self, arg):
        # Change output to JSON
        web.header('Content-type', 'application/json')

        if not arg:
            web.internalerror()
            return json.dumps(dict(error='must have code'))

        try:
            phrase = model.get_phrase(code=base36decode(arg))
            seqID = phrase.get('id')
        except(), e:
            web.notfound()
            return json.dumps(dict(error='not found'))
Exemple #33
0
 def GET(self, optionsConcatenated):
     try:
         wh = []
         specificId = None
         optionList = []
         for option in optionsConcatenated.split("/"):
             if not option:
                 continue
             if option.isdigit():
                 wh.append( int(option) )
             elif option.startswith("m"):
                 specificId = int( option[1:] )
             else:
                 optionList.append( option )
         if len( wh ) == 0:
             w = h = 640
         elif len( wh ) == 1:
             w = h =  wh[0]
         else:
             assert len( wh ) == 2
             w, h = wh
         optionString = "".join( map( map_option, optionList ) )
     except:
         raise web.internalerror( render.error( "error parsing arguments" ) )
     try:
         if not specificId:
             manul = select_random_manul( findfiles(), w, h )
         else:
             manul = findfiles()[ specificId ]
         fn = filename( manul.filename, w, h, optionString )
     except:
         if specificId:
             raise web.internalerror( render.error( "manul not found" ) )
         else:
             raise web.internalerror( render.error( "manul not found (requested resolution may be too high)" ) )
     try:
         if not os.path.exists( cachedDir + fn ):
             convert( Image.open( sourceDir + manul.filename ), manul, w, h, optionString, cachedDir + fn )
     except:
         raise web.internalerror( render.error( "error processing manul" ) )
     path = cachedDir + fn
     mtime = os.stat( path ).st_mtime
     if web.http.modified( date = datetime.datetime.fromtimestamp(mtime) ): 
         try:
             with open( path, "rb" ) as f:
                 data = f.read()
                 web.header( "Content-Type", "image/jpeg" )
                 return data
         except:
             raise web.internalerror( render.error( "error retrieving manul" ) )
 def doGET(self):
     try:
        y = urllib.urlopen('%s?%s' % (self.url,
           web.ctx.env['QUERY_STRING']))
        headers = str(y.info()).split('\n')
        for h in headers:
            if h.startswith("Content-Type:"):
                a = h.split(':')
                web.header(a[0], a[1].strip())
        ret = y.read()
        y.close()
        return ret
     except Exception, E:
         print web.internalerror()
         print "Some unexpected error occurred. Error text was:", E
 def doGET(self):
     try:
         y = urllib.urlopen('%s?%s' %
                            (self.url, web.ctx.env['QUERY_STRING']))
         headers = str(y.info()).split('\n')
         for h in headers:
             if h.startswith("Content-Type:"):
                 a = h.split(':')
                 web.header(a[0], a[1].strip())
         ret = y.read()
         y.close()
         return ret
     except Exception, E:
         print web.internalerror()
         print "Some unexpected error occurred. Error text was:", E
Exemple #36
0
 def POST(self, params):
   result = None
   target_url = '/' +params 
   headers = self._get_headers()
   httpcon = httplib.HTTPConnection('twitter.com', 80)
   try:
     httpcon.request('POST', target_url, headers=headers, body=web.data())
     twitter_response = httpcon.getresponse()
     self.sendoutput(twitter_response)
   except Exception, inst:
     if result:
       logging.error("%s \n\n %s \n\n %s \n\n %s \n\n %s" % (target_url, str(inst), headers, web.data(), twitter_response.read()))
     else:
       logging.error("%s \n\n %s \n\n %s \n\n %s" % (target_url, str(inst), headers, web.data()))
     web.internalerror()
Exemple #37
0
    def GET(self):
        user_data = web.input(q="", dn="")

        # dn parameter:
        if user_data["dn"] != "":
            data = urllib.quote(user_data["dn"])
            path = "/dn-search?dn=" + data
            target = urlparse(config.iPA4uri + path)
            response, content = h.request(target.geturl(), method, body, config.headers)
            json_content = json.loads(content)
            if response.status != 200:
                web.internalerror()
                web.header("Content-Type", "text/xml")
                return view.error(json_content, home=web.ctx.home + web.ctx.path)

            web.header("Content-Type", "text/xml")
            return view.entry(json_content, home=web.ctx.home + web.ctx.path)

            # q parameter:
        if user_data["q"] != "":
            data = urllib.quote(user_data["q"])
            path = (
                "/advanced-search?description="
                + data
                + "&nomeResp="
                + data
                + "&cognomeResp="
                + data
                + "&descrizioneS="
                + data
                + "&nomeS="
                + data
            )
            target = urlparse(config.iPA4uri + path)
            response, content = h.request(target.geturl(), method, body, config.headers)
            json_content = json.loads(content)
            if response.status != 200:
                web.internalerror()
                web.header("Content-Type", "text/xml")
                return view.error(json_content, home=web.ctx.home + web.ctx.path)

            web.header("Content-Type", "text/xml")
            return view.searchResult(json_content, home=web.ctx.home + web.ctx.path)

            # no q or dn parameter: render search form
        else:
            web.header("Content-Type", "text/xml")
            return view.searchForm(web.ctx.home + web.ctx.path)
Exemple #38
0
def internalerror():
    msg = """
    An internal server error occurred. Please try your request again by
    hitting back on your web browser. You can also <a href="/"> go back
     to the main page.</a>
    """
    return web.internalerror(msg)
Exemple #39
0
 def GET(self):
     try:
         cf = confOpt.get_conf()
     except:
         print "------------ get conf error,"
         raise web.internalerror(message="get conf error,")
     return render.page(cf=cf)
Exemple #40
0
    def GET(self, owner, repoId):
        web.header('Content-Type', 'text/html')

        repoInfo = get_common_repo_info(owner, repoId)
        if repoInfo == None:
            return web.internalerror("Invalid repository")

        repo = Repo(os.path.join(web.config.reporoot, owner, repoId + ".git"))
        if 'master' not in repo.heads:
            return render.showRepoFiles(owner=owner,
                                        repoid=repoId,
                                        repoInfo=repoInfo,
                                        path="",
                                        filelist=[])

        tree = repo.heads.master.commit.tree
        curHashes = [entry.hexsha for entry in tree]
        changeinfo = gitHelper.get_last_updating_commit(
            repo, 'master', curHashes)
        filelist = [(entry, changeinfo[entry.hexsha]) for entry in tree]

        return render.showRepoFiles(owner=owner,
                                    repoid=repoId,
                                    repoInfo=repoInfo,
                                    path="",
                                    filelist=filelist)
Exemple #41
0
 def GET(self, catrel_name, arch_name, osrel_name, pkgname):
   """Get a srv4 reference by catalog ane pkgname."""
   configuration.SetUpSqlobjectConnection()
   sqo_osrel, sqo_arch, sqo_catrel = pkgdb.GetSqoTriad(
       osrel_name, arch_name, catrel_name)
   join = [
       sqlbuilder.INNERJOINOn(None,
         models.Srv4FileInCatalog,
         models.Srv4FileInCatalog.q.srv4file==models.Srv4FileStats.q.id),
       sqlbuilder.INNERJOINOn(None,
         models.Pkginst,
         models.Pkginst.q.id==models.Srv4FileStats.q.pkginst),
   ]
   res = models.Srv4FileStats.select(
       sqlobject.AND(
         models.Srv4FileInCatalog.q.osrel==sqo_osrel,
         models.Srv4FileInCatalog.q.arch==sqo_arch,
         models.Srv4FileInCatalog.q.catrel==sqo_catrel,
         models.Pkginst.q.pkgname==pkgname,
         models.Srv4FileStats.q.use_to_generate_catalogs==True),
       join=join,
   )
   try:
     srv4 = res.getOne()
     mimetype, data = srv4.GetRestRepr()
     web.header('Content-type', mimetype)
     web.header('Access-Control-Allow-Origin', '*')
     return cjson.encode(data)
   except sqlobject.main.SQLObjectNotFound:
     return cjson.encode(None)
   except sqlobject.dberrors.OperationalError, e:
     raise web.internalerror(e)
Exemple #42
0
    def POST(self):
        inputs = web.input(template=settings.TEMPLATE, )

        try:
            with tempfile.NamedTemporaryFile(suffix='.tex',
                                             delete=False) as temp:
                temp.write(inputs['template'].strip())
                temp.flush()

            outname = os.path.splitext(temp.name)[0] + '.pdf'
            dirname = os.path.dirname(temp.name)
            subprocess.check_call(settings.TEX + (temp.name, ), cwd=dirname)
            with open(outname, 'rb') as out:
                data = out.read()

            os.remove(temp.name)
            os.remove(outname)

            digest = settings.HASH(data).hexdigest()
            disposition = 'inline; filename={}.pdf'.format(digest)
            web.header('Content-Type', 'application/pdf')
            web.header('Content-Disposition', disposition)
            return data
        except:
            return web.internalerror(
                'Sorry, something went wrong with your request.')
Exemple #43
0
 def POST(self):
     if checkLogin():
         data = web.input()
         action = int(data.action)
         postId = data.pid
         userId = db['users'].find_one(
             {'username': web.ctx.session.get('username')})['_id']
         if postId:
             if action > 0:
                 # 点赞
                 # 如果已经点赞,不再操作
                 collected = db['actions'].find_one({
                     'userId': str(userId),
                     'action': action,
                     'postId': str(postId)
                 })
                 if not collected:
                     db['actions'].insert({
                         'userId': str(userId),
                         'action': action,
                         'postId': str(postId),
                         'actionTime': time.time()
                     })
             else:
                 # 删除对应的记录
                 db['actions'].remove({
                     'userId': str(userId),
                     'action': -action,
                     'postId': str(postId)
                 })
             return json.dumps({'code': 200, 'msg': '操作成功'})
         else:
             return json.dumps({'code': 500, 'msg': '文章id不存在'})
     else:
         return web.internalerror('非法操作')
Exemple #44
0
    def PUT(self, cluster_id):
        """:returns: JSONized Cluster attributes.
        :http: * 200 (OK)
               * 400 (wrong attributes data specified)
               * 404 (cluster not found in db)
               * 500 (cluster has no attributes)
        """
        cluster = self.get_object_or_404(
            Cluster,
            cluster_id,
            log_404=(
                "warning",
                "Error: there is no cluster "
                "with id '{0}' in DB.".format(cluster_id)
            )
        )

        if not cluster.attributes:
            logger.error('ClusterAttributesDefaultsHandler: no attributes'
                         ' found for cluster_id %s' % cluster_id)
            raise web.internalerror("No attributes found!")

        cluster.attributes.editable = cluster.release.attributes_metadata.get(
            "editable"
        )
        db().commit()
        cluster.add_pending_changes("attributes")

        logger.debug('ClusterAttributesDefaultsHandler:'
                     ' editable attributes for cluster_id %s were reset'
                     ' to default' % cluster_id)
        return {"editable": cluster.attributes.editable}
Exemple #45
0
    def PUT(self, cluster_id):
        """:returns: JSONized Cluster attributes.
        :http: * 200 (OK)
               * 400 (wrong attributes data specified)
               * 404 (cluster not found in db)
               * 500 (cluster has no attributes)
        """
        cluster = self.get_object_or_404(Cluster, cluster_id)
        if not cluster.attributes:
            raise web.internalerror("No attributes found!")

        data = self.checked_data()

        if cluster.is_locked:
            error = web.forbidden()
            error.data = "Environment attributes can't be changed " \
                         "after, or in deploy."
            raise error

        for key, value in data.iteritems():
            setattr(cluster.attributes, key, value)
        cluster.add_pending_changes("attributes")

        db().commit()
        return {"editable": cluster.attributes.editable}
Exemple #46
0
    def GET(self, owner, repoId):
        web.header('Content-Type', 'text/html')
        d = dict(o=owner, i=repoId, u=web.config.session.userid)
        repoInfo = web.config.db.select('repositories',
                                        d,
                                        where="id=$i and owner=$o",
                                        what="description,access,name").list()
        if len(repoInfo) != 1:
            return web.internalerror("Invalid repository")

        repoInfo = repoInfo[0]
        curUserRights = web.config.db.select(
            'repo_users',
            d,
            where="repoid=$i and repoowner=$o and userid=$u",
            what="access").list()
        if len(curUserRights) == 1 and curUserRights[0].access == "admin":
            repoInfo.userLevel = "admin"

        collaborators = web.config.db.select(
            'repo_users',
            d,
            where="repoid=$i and repoowner=$o",
            what="userid,access").list()
        cids = [c.userid for c in collaborators]
        users = web.config.db.select('users', what='id,name').list()
        users = [u for u in users if u.id not in cids]

        return render.showRepoSettings(owner=owner,
                                       repoid=repoId,
                                       repoInfo=repoInfo,
                                       collaborators=collaborators,
                                       users=users)
Exemple #47
0
	def fileCheck(self, pdfpath):
			
		try:
			# After we handle the file upload, we do the following:
			# I. Check the uploaded file's type -> proceed to next step
			# II. Extract the full text from the document, where if the file type is:
			#	PDF -> extract text using pdf2text -> proceed to next step
			#	PostScript -> extract text using ps2text -> proceed to next step
			#	Text File -> skip full text extraction, proceed to next step
			#	Type NOT from the above -> Value error & Display error message
			# III. Check if the document is an academic document and returns:
			#	"1" - Document is academic -> Proceed to next step
			#	"0" - Document is not academic -> Value error & Display error message
			#	"-1" - OS error
			# IV. Form and return XML response

			#new: checks file type and returns true if it is a PDF. Raises errors otherwise
			typeFilterStatus = utilities.typeFilter(pdfpath)
			web.debug(typeFilterStatus)
			if typeFilterStatus == "application/pdf":
				web.debug(pdfpath)
			else:
				typeFilterStatus = "falsetype"
				raise ValueError
		except OSError as ex:
			web.debug(ex)
			return web.internalerror()
		except ValueError as ex:
			web.debug(ex)
			if typeFilterStatus == "falsetype":
				return False, "Your document failed our academic document filter due to invalid file type. Supported types are PDF."
			elif acaFilterStatus == "0":
				return False, "Your document failed our academic document filter."
		return True, typeFilterStatus
Exemple #48
0
    def GET(self, autostackId, *args):  # pylint: disable=C0103,W0613
        """
      Get Metrics associated with autostack

      ::

          GET /_autostacks/{autostackId}/metrics

      NOTE: args is ignored.  Function signature for all method handlers must
      be compatible with the regexp pattern that matches.  POST optionally
      takes a second argument, DELETE requires it.
    """
        try:
            self.addStandardHeaders()
            engine = repository.engineFactory()
            metricRows = repository.getAutostackMetrics(
                engine, autostackId, getMetricDisplayFields(engine))
            metricsList = [
                convertMetricRowToMetricDict(metricRow)
                for metricRow in metricRows
            ]

            return utils.jsonEncode(metricsList)

        except ObjectNotFoundError:
            raise web.notfound("Autostack not found: Autostack ID: %s" %
                               autostackId)
        except web.HTTPError as ex:
            if bool(re.match(r"([45][0-9][0-9])\s?", web.ctx.status)):
                # Log 400-599 status codes as errors, ignoring 200-399
                log.error(str(ex) or repr(ex))
            raise
        except Exception as ex:
            raise web.internalerror(str(ex) or repr(ex))
Exemple #49
0
    def DELETE(self, autostackId):  # pylint: disable=C0103,R0201
        """
      Delete an Autostack

      ::

          DELETE /_autostacks/{autostackId}
    """
        try:
            with web.ctx.connFactory() as conn:
                modelIDs = tuple(
                    m.uid
                    for m in repository.getAutostackMetrics(conn, autostackId))

            with web.ctx.connFactory() as conn:
                repository.deleteAutostack(conn, autostackId)

            # Delete the corresponding Engine models, if any
            for modelID in modelIDs:
                model_swapper_utils.deleteHTMModel(modelID)
            raise web.HTTPError(status="204 No Content")
        except ObjectNotFoundError:
            raise web.notfound("Autostack not found: Autostack ID: %s" %
                               autostackId)
        except web.HTTPError as ex:
            if bool(re.match(r"([45][0-9][0-9])\s?", web.ctx.status)):
                # Log 400-599 status codes as errors, ignoring 200-399
                log.error(str(ex) or repr(ex))
            raise
        except Exception as ex:
            log.exception("DELETE Failed")
            raise web.internalerror(str(ex) or repr(ex))
Exemple #50
0
 def POST(self, api_key):
     if api_key in config.KEYS:
         newReport = json.loads(web.data())
         model.newReport(newReport["temp"], newReport["humidity"])
         return web.data()
     else:
         return web.internalerror('The server says: No soup for you!')
Exemple #51
0
 def GET(self, file, sig):
     sig = sig.decode('hex')
     real_sig = sha1hmac(HMAC_KEY, file)
     if insecure_compare(sig, real_sig):
         return 'ok'
     else:
         raise web.internalerror('bad signature, want ' + real_sig.encode('hex'))
Exemple #52
0
def placefinder_geocode(location_string):
    """
    Löst eine Straßen- und optional PLZ-Angabe zu einer Geo-Postion
    auf. Beispiel: "Straßenname (12345)"
    """
    postal = None
    street = location_string.encode('utf-8')
    postalre = re.compile(r'(.+)\s+\(([0-9]{5})\)')
    postal_matching = re.match(postalre, street)
    if postal_matching is not None:
        street = postal_matching.group(1)
        postal = postal_matching.group(2)
    yurl = 'http://where.yahooapis.com/geocode'
    params = {
        'flags': 'J',  # json
        'appid': config.PLACEFINDER_APP_ID,
        'locale': 'de_DE',
        'street': street,
        'postal': postal,
        'city': config.PLACEFINDER_DEFAULT_CITY,
        'country': config.PLACEFINDER_DEFAULT_COUNTRY
    }
    try:
        request = urllib2.urlopen(yurl + '?' + urllib.urlencode(params))
        response = request.read()
        try:
            obj = json.loads(response)
            return obj
        except:
            raise web.internalerror()
    except urllib2.HTTPError, e:
        print >> sys.stderr, "FEHLER in placefinder_geocode():", e.code
Exemple #53
0
    def POST(self):
        web.header('Content-Type', 'text/html')
        f = login_form()
        if not f.validates():
            raise web.seeother('/')

        authOptions = [am for am in web.config.auth.methods if am.can_handle_user(f.d.username)]
        if len(authOptions) == 0:
            raise web.internalerror("No appropriate login method available")

        for ao in authOptions:
            try:
                success, res = ao.login(f.d.username, f.d.password, web.config)
                if success == True:
                    web.config.session.loggedin = True
                    web.config.session.userid = res['userid']
                    web.config.session.userfullname = res['userfullname']
                    web.config.session.userrights = res['rights']
                    raise web.seeother("/")
            except RequireRegistrationException, info:
                web.config.session.showIdentifierRegistration = True
                web.config.session.userid = info.username
                web.config.session.userfullname = info.userfullname
                web.config.session.userrights = "none"
                raise web.seeother('/register')
Exemple #54
0
    def GET_group(self, owner):
        groupinfo = web.config.db.select("groups",
                                         dict(u=owner),
                                         where="id=$u").list()
        if len(groupinfo) != 1:
            return web.internalerror("Couldn't find user information")

        repos = queries.repos_for_owner(owner).list()
        for r in repos:
            repo = Repo(
                os.path.join(web.config.reporoot, r.owner, r.id + ".git"))
            r.lastUpdate = gitHelper.get_last_commit_time(repo)

        members = queries.members_for_group(owner).list()
        role = [
            m['role'] for m in members if m['id'] == web.config.session.userid
        ]

        if len(role) == 1:
            users = web.config.db.select('users', what='id,name').list()
            users = [
                u for u in users if u.id not in [m['id'] for m in members]
            ]
            return render.groupPageForMembers(group=groupinfo[0],
                                              repos=repos,
                                              members=members,
                                              role=role[0],
                                              users=users)
        else:
            return render.groupPageForVisitors(group=groupinfo[0],
                                               repos=repos,
                                               members=members)
Exemple #55
0
    def PUT(self, cluster_id):
        """:returns: JSONized Cluster attributes.
        :http: * 200 (OK)
               * 400 (wrong attributes data specified)
               * 404 (cluster not found in db)
               * 500 (cluster has no attributes)
        """
        cluster = self.get_object_or_404(
            Cluster,
            cluster_id,
            log_404=(
                "warning",
                "Error: there is no cluster "
                "with id '{0}' in DB.".format(cluster_id)
            )
        )

        if not cluster.attributes:
            logger.error('ClusterAttributesDefaultsHandler: no attributes'
                         ' found for cluster_id %s' % cluster_id)
            raise web.internalerror("No attributes found!")

        cluster.attributes.editable = cluster.release.attributes_metadata.get(
            "editable"
        )
        db().commit()
        cluster.add_pending_changes("attributes")

        logger.debug('ClusterAttributesDefaultsHandler:'
                     ' editable attributes for cluster_id %s were reset'
                     ' to default' % cluster_id)
        return {"editable": cluster.attributes.editable}
Exemple #56
0
def internalerror(e):

    message = html_header(
        "Error") + "Sorry, there was an error:<br>\n<pre>\n" + str(
            e) + "</pre>\n" + html_footer()

    return web.internalerror(message)