Example #1
0
 def _DELETE(self, key, forceful=False):
     if forceful:
         self.datastore.delete_in_all(str(key))
     else:
         self.datastore.delete(str(key))
     web.accepted()
     return {"message": "accepted"}
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.notfound()

        if validates_nw_status(self) is False:
            return web.badrequest(self.view.alert)

        status = int(self.input.status)

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            if status == NETWORK_INACTIVE:
                # Stop network
                network_start_stop_job(self, host_id, network_name, 'stop')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            elif status == NETWORK_ACTIVE:
                # Start network
                network_start_stop_job(self, host_id, network_name, 'start')
                return web.accepted("/host/%s/network/%s.%s" % (host_id, network_name, self.__template__['media']))
            else:
                return web.badrequest()
        finally:
            kvc.close()
Example #3
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        # TODO valid
        network_name = param[1]
        if not network_name:
            return web.notfound()

        if validates_nw_status(self) is False:
            return web.badrequest(self.view.alert)

        status = int(self.input.status)

        kvc = KaresansuiVirtConnection()
        try:
            kvn = kvc.search_kvn_networks(network_name)[0]
            if status == NETWORK_INACTIVE:
                # Stop network
                network_start_stop_job(self, host_id, network_name, 'stop')
                return web.accepted(
                    "/host/%s/network/%s.%s" %
                    (host_id, network_name, self.__template__['media']))
            elif status == NETWORK_ACTIVE:
                # Start network
                network_start_stop_job(self, host_id, network_name, 'start')
                return web.accepted(
                    "/host/%s/network/%s.%s" %
                    (host_id, network_name, self.__template__['media']))
            else:
                return web.badrequest()
        finally:
            kvc.close()
Example #4
0
    def _PUT(self, *param, **params):

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

        if is_int(param[2]) is False:
            return web.notfound()
        nic_id = int(param[2])

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

        model = findbyguest1(self.orm, guest_id)
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            old_mac = virt.get_interface_info()[nic_id]["mac"]["address"]
            nic_info = virt.get_interface_info()
        finally:
            kvc.close()

        new_mac = self.input.mac_address

        if old_mac != new_mac:
            f_chk = True
            for x in nic_info:
                if x["mac"]["address"] == new_mac:
                    f_chk = False
                    break
            if f_chk is False:
                return web.badrequest(_("Specified MAC address is already defined."))

            self.logger.debug(
                "spinning off change_mac_job dom=%s, from_mac=%s, to_mac=%s" % (domname, old_mac, new_mac)
            )
            if change_mac_job(self, model, domname, old_mac, new_mac) is True:
                return web.accepted(url=web.ctx.path)
            else:
                return False

        else:
            return web.accepted(url=web.ctx.path)
    def PUT(self, cluster_id):
        """:IMPORTANT: this method should be rewritten to be more RESTful

        :returns: JSONized Task object.
        :http: * 202 (network checking task failed)
               * 200 (network verification task started)
               * 404 (cluster not found in db)
        """
        cluster = self.get_object_or_404(Cluster, cluster_id)

        try:
            data = self.validator.validate_networks_update(web.data())
        except web.webapi.badrequest as exc:
            task = Task(name='check_networks', cluster=cluster)
            db().add(task)
            db().commit()
            TaskHelper.set_error(task.uuid, exc.data)
            logger.error(traceback.format_exc())

            json_task = build_json_response(TaskHandler.render(task))
            raise web.accepted(data=json_task)

        vlan_ids = [{
            'name': n['name'],
            'vlans': NetworkGroup.generate_vlan_ids_list(n)
        } for n in data['networks']]

        task_manager = VerifyNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data, vlan_ids)

        return TaskHandler.render(task)
Example #6
0
    def PUT(self, cluster_id):
        data = json.loads(web.data())
        if data.get("networks"):
            data["networks"] = [
                n for n in data["networks"] if n.get("name") != "fuelweb_admin"
            ]
        cluster = self.get_object_or_404(Cluster, cluster_id)

        check_if_network_configuration_locked(cluster)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':

            try:
                if 'networks' in data:
                    self.validator.validate_networks_update(json.dumps(data))

                if 'neutron_parameters' in data:
                    self.validator.validate_neutron_params(json.dumps(data))

                NeutronNetworkConfiguration.update(cluster, data)
            except Exception as exc:
                TaskHelper.set_error(task.uuid, exc)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            db().rollback()
        else:
            db().commit()
        raise web.accepted(data=data)
    def PUT(self, cluster_id):
        data = json.loads(web.data())
        cluster = self.get_object_or_404(Cluster, cluster_id)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':
            try:
                if 'networks' in data:
                    network_configuration = self.validator.\
                        validate_networks_update(json.dumps(data))

                NetworkConfiguration.update(cluster, data)
            except web.webapi.badrequest as exc:
                TaskHelper.set_error(task.uuid, exc.data)
                logger.error(traceback.format_exc())
            except Exception as exc:
                TaskHelper.set_error(task.uuid, exc)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            db().rollback()
        else:
            db().commit()
        raise web.accepted(data=data)
Example #8
0
    def POST(self, userid):
        data = web.input()
        item = data.item
        category = data.category
        rate = data.rate
        ratetype = data.ratetype

        db = getDB()
        r = list(
            db.select('item', {
                'imgpath': item,
                'category': category
            },
                      where='imgpath=$imgpath AND category=$category'))
        if len(r) == 0:
            raise web.notfound()

        # 尝试更新老的标记
        affected = db.update(
            'rating',
            vars=dict(item=r[0]['id'],
                      ratetype=int(ratetype),
                      usertoken=session.usertoken),
            where='usertoken=$usertoken and item=$item and ratetype=$ratetype',
            rate=int(rate))
        if affected == 0:
            db.insert('rating',
                      item=r[0]['id'],
                      rate=int(rate),
                      ratetype=int(ratetype),
                      usertoken=session.usertoken)
        raise web.accepted()
Example #9
0
    def launch_verify(self, cluster):
        try:
            data = self.validator.validate_networks_update(web.data())
        except web.webapi.badrequest as exc:
            task = Task(name='check_networks', cluster=cluster)
            db().add(task)
            db().commit()
            TaskHelper.set_error(task.uuid, exc.data)
            logger.error(traceback.format_exc())

            json_task = build_json_response(TaskHandler.render(task))
            raise web.accepted(data=json_task)

        data["networks"] = [
            n for n in data["networks"] if n.get("name") != "fuelweb_admin"
        ]

        vlan_ids = [{
                    'name': n['name'],
                    'vlans': cluster.network_manager.generate_vlan_ids_list(
                        data, cluster, n)
                    } for n in data['networks']]

        task_manager = VerifyNetworksTaskManager(cluster_id=cluster.id)
        try:
            task = task_manager.execute(data, vlan_ids)
        except errors.CantRemoveOldVerificationTask:
            raise web.badrequest("You cannot delete running task manually")
        return TaskHandler.render(task)
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

        cmdname = u"Delete Bonding Setting"
        cmd = BONDING_COMMAND_DELETE
        options = {}

        options['dev'] = device
        options["succession"] = None

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options)

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, _cmd)
        _jobgroup.jobs.append(_job)

        host = findbyhost1(self.orm, host_id)
        _machine2jobgroup = m2j_new(machine=host,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )

        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )
        return web.accepted()
Example #11
0
    def PUT(self, cluster_id):
        data = json.loads(web.data())
        cluster = self.get_object_or_404(Cluster, cluster_id)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':
            if 'networks' in data:
                network_configuration = self.validator.\
                    validate_networks_update(json.dumps(data))
            try:
                NetworkConfiguration.update(cluster, data)
            except Exception as exc:
                err = str(exc)
                TaskHelper.update_task_status(task.uuid,
                                              status="error",
                                              progress=100,
                                              msg=err)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            self.db.rollback()
        else:
            self.db.commit()
        raise web.accepted(data=data)
Example #12
0
    def POST(self, api_key):
        try:
            data = json.loads(web.data())
            if DEBUG: print(json.dumps(data))
        except ValueError as e:
            raise web.badrequest('Invalid JSON request data')

        if not validate_api_key(api_key, api_config, data):
            raise web.forbidden('Invalid API Key')

        try:
            headers = {'Content-type': 'application/json'}
            if SENSU_API_USER and SENSU_API_PASS:
                if DEBUG: print "AUTH: SENSU_API_USER, XXX"
                auth = (SENSU_API_USER, SENSU_API_PASS)
            else:
                auth = None
            r = requests.post(SENSU_API_URI,
                              json=data,
                              headers=headers,
                              auth=auth)
            r.raise_for_status()
            return web.accepted()
        except requests.exceptions.RequestException as e:
            print(e)
            raise web.internalerror('RequestException calling Sensu')
    def PUT(self, cluster_id):
        """:returns: JSONized Task object.
        :http: * 202 (network checking task created)
               * 404 (cluster not found in db)
        """
        data = json.loads(web.data())
        cluster = self.get_object_or_404(Cluster, cluster_id)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':
            try:
                if 'networks' in data:
                    self.validator.validate_networks_update(json.dumps(data))

                NetworkConfiguration.update(cluster, data)
            except web.webapi.badrequest as exc:
                TaskHelper.set_error(task.uuid, exc.data)
                logger.error(traceback.format_exc())
            except Exception as exc:
                TaskHelper.set_error(task.uuid, exc)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            db().rollback()
        else:
            db().commit()
        raise web.accepted(data=data)
Example #14
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()
Example #15
0
    def PUT(self, cluster_id):
        """
        :IMPORTANT: this method should be rewritten to be more RESTful

        :returns: JSONized Task object.
        :http: * 202 (network checking task failed)
               * 200 (network verification task started)
               * 404 (cluster not found in db)
        """
        cluster = self.get_object_or_404(Cluster, cluster_id)

        try:
            data = self.validator.validate_networks_update(web.data())
        except web.webapi.badrequest as exc:
            task = Task(name='check_networks', cluster=cluster)
            db().add(task)
            db().commit()
            TaskHelper.set_error(task.uuid, exc.data)
            logger.error(traceback.format_exc())

            json_task = build_json_response(TaskHandler.render(task))
            raise web.accepted(data=json_task)

        vlan_ids = [{
            'name': n['name'],
            'vlans': NetworkGroup.generate_vlan_ids_list(n)
        } for n in data['networks']]

        task_manager = VerifyNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data, vlan_ids)

        return TaskHandler.render(task)
Example #16
0
    def _DELETE(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_int(param[2]) is False:
            return web.notfound()       

        nic_id = int(param[2])

        model = findbyguest1(self.orm, guest_id)
        
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            nic_info = virt.get_interface_info()[nic_id]
        finally:
            kvc.close()

        mac = nic_info["mac"]["address"]
        self.logger.debug('spinning off delete_nic_job dom=%s, mac=%s' % (domname, mac))
        if delete_nic_job(self,model,domname,mac) is True:
            return web.accepted()
        else:
            return False
Example #17
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        Japanese Comment
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None:
            return web.notfound()

        if is_param(self.input, "memory"):
            memory = int(self.input.memory)
        else:
            memory = None
        max_memory = int(self.input.max_memory)

        model = findbyguest1(self.orm, guest_id)

        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname:
                return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            info = virt.get_info()
            # maxMem = info["maxMem"]
            now_memory = info["memory"]
            mem_info = kvc.get_mem_info()
            nodeinfo = kvc.get_nodeinfo()
        finally:
            kvc.close()

        # valid
        # if (mem_info["host_free_mem"] + (now_memory / 1024)) < memory:
        #    return web.badrequest("Memory value is greater than the maximum memory value. - memory=%s" % self.input.memory)

        options = {}
        options["name"] = domname
        options["maxmem"] = max_memory
        if memory is None:
            options["memory"] = max_memory
        else:
            options["memory"] = memory
        _cmd = dict2command("%s/%s" % (karesansui.config["application.bin.dir"], VIRT_COMMAND_SET_MEMORY), options)
        cmdname = "Set memory"
        _jobgroup = JobGroup(cmdname, karesansui.sheconf["env.uniqkey"])
        _jobgroup.jobs.append(Job("%s command" % cmdname, 0, _cmd))
        _machine2jobgroup = m2j_new(
            machine=model,
            jobgroup_id=-1,
            uniq_key=karesansui.sheconf["env.uniqkey"],
            created_user=self.me,
            modified_user=self.me,
        )
        save_job_collaboration(self.orm, self.pysilhouette.orm, _machine2jobgroup, _jobgroup)
        return web.accepted(url=web.ctx.path)
Example #18
0
 def POST(self, db_name, id, _user=None):
   db_cnx = get_db_cnx(db_name)
   user_data = {'id':id}
   cur = db_cnx.cursor()
   cur.execute(self.query, user_data)
   cur.execute(self.subquery, user_data)
   db_cnx.commit()
   return web.accepted()
Example #19
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)
Example #20
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)
Example #22
0
    def _PUT(self, *param, **params):

        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if is_int(param[2]) is False:
            return web.notfound()       
        nic_id = int(param[2])


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

        model = findbyguest1(self.orm, guest_id)
        # virt
        kvc = KaresansuiVirtConnection()
        try:
            domname = kvc.uuid_to_domname(model.uniq_key)
            if not domname: return web.conflict(web.ctx.path)
            virt = kvc.search_kvg_guests(domname)[0]
            guest = MergeGuest(model, virt)
            old_mac = virt.get_interface_info()[nic_id]['mac']['address']
            nic_info = virt.get_interface_info()
        finally:
            kvc.close()

        new_mac = self.input.mac_address

        if old_mac != new_mac:
            f_chk = True
            for x in nic_info:
                if x['mac']['address'] == new_mac:
                    f_chk = False
                    break
            if f_chk is False:
                return web.badrequest(_('Specified MAC address is already defined.'))

            self.logger.debug('spinning off change_mac_job dom=%s, from_mac=%s, to_mac=%s' % (domname, old_mac, new_mac))
            if change_mac_job(self, model, domname, old_mac, new_mac) is True:
                return web.accepted(url=web.ctx.path)
            else:
                return False

        else:
            return web.accepted(url=web.ctx.path)
Example #23
0
 def DELETE(self, cluster_id):
     """:returns: {}
     :http: * 202 (orchestrator data deletion process launched)
            * 400 (failed to execute orchestrator data deletion process)
            * 404 (cluster not found in db)
     """
     cluster = self.get_object_or_404(Cluster, cluster_id)
     self.update_orchestrator_info(cluster, {})
     raise web.accepted(data="{}")
Example #24
0
 def DELETE(self, cluster_id):
     """:returns: {}
     :http: * 202 (orchestrator data deletion process launched)
            * 400 (failed to execute orchestrator data deletion process)
            * 404 (cluster not found in db)
     """
     cluster = self.get_object_or_404(Cluster, cluster_id)
     self.update_orchestrator_info(cluster, {})
     raise web.accepted(data="{}")
Example #25
0
    def _POST(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

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

        guest = findbyguest1(self.orm, guest_id)

        kvs = KaresansuiVirtSnapshot(readonly=False)
        try:
            domname = kvs.kvc.uuid_to_domname(guest.uniq_key)
            if not domname: return web.conflict(web.ctx.path)

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

        finally:
            kvs.finish()

        id = int(time.time())
        notebook = new_notebook(self.input.title, self.input.value)
        snapshot = new_snapshot(guest, id, self.me, self.me, notebook)
        save_snapshot(self.orm, snapshot)

        options = {}
        options['name'] = domname
        options['id'] = id

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       VIRT_COMMAND_TAKE_SNAPSHOT), options)

        cmdname = 'Take Snapshot'
        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('%s command' % cmdname, 0, _cmd))

        _machine2jobgroup = m2j_new(
            machine=guest,
            jobgroup_id=-1,
            uniq_key=karesansui.sheconf['env.uniqkey'],
            created_user=self.me,
            modified_user=self.me,
        )

        save_job_collaboration(
            self.orm,
            self.pysilhouette.orm,
            _machine2jobgroup,
            _jobgroup,
        )
        return web.accepted()
Example #26
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug(
                "Set storage pool status failed. Did not validate.")
            return web.badrequest(self.view.alert)

        model = findbyhost1(self.orm, host_id)

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

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                self.logger.debug(
                    "Set storage pool status failed. Target storage pool not found."
                )
                return web.notfound()

            status = int(self.input.status)
            if status == STORAGE_POOL_START:
                storagepool_start_stop_job(self, model, pools_obj[0], 'start')
            elif status == STORAGE_POOL_STOP:
                if kvc.is_used_storage_pool(
                        name=pools_obj[0].get_storage_name(),
                        active_only=True) is True:
                    self.logger.debug(
                        "Stop storage pool failed. Target storage pool is used by guest."
                    )
                    return web.badrequest(
                        "Target storage pool is used by guest.")
                else:
                    storagepool_start_stop_job(self, model, pools_obj[0],
                                               'stop')
            else:
                self.logger.debug(
                    "Set storage pool status failed. Unknown status type.")
                return web.badrequest()

            return web.accepted()
        finally:
            kvc.close()
Example #27
0
    def PUT(self):
        """Starts capacity data generation.

        :returns: JSONized Task object.
        :http: * 202 (setup task created and started)
        """
        manager = GenerateCapacityLogTaskManager()
        task = manager.execute()

        data = build_json_response(TaskHandler.render(task))
        raise web.accepted(data=data)
Example #28
0
 def POST(self, db_name, name, _user=None):
   if name in SETTING:
     user_input = web.input(data_string=None)
     user_data = {'name':name}
     d = load_formatted_data(_user["data_format"], user_input.data_string)
     d = validate(d, self.valid_data_format)
     user_data.update(d)
     db_cnx = get_db_cnx(db_name)
     cur = db_cnx.cursor()
     cur.execute(self.query, user_data)
     db_cnx.commit()
     return web.accepted()
Example #29
0
    def _POST(self, *param, **params):
        (host_id, guest_id) = self.chk_guestby1(param)
        if guest_id is None: return web.notfound()

        if not validates_snapshot(self): 
            return web.badrequest(self.view.alert)
        
        guest = findbyguest1(self.orm, guest_id)

        kvs = KaresansuiVirtSnapshot(readonly=False)
        try:
            domname = kvs.kvc.uuid_to_domname(guest.uniq_key)
            if not domname: return web.conflict(web.ctx.path)

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

        finally:
            kvs.finish()

        id = int(time.time())
        notebook = new_notebook(self.input.title, self.input.value)
        snapshot = new_snapshot(guest, id, self.me, self.me, notebook)
        save_snapshot(self.orm, snapshot)

        options = {}
        options['name'] = domname
        options['id'] = id

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], VIRT_COMMAND_TAKE_SNAPSHOT),
            options)

        cmdname = 'Take Snapshot'
        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('%s command' % cmdname, 0, _cmd))

        _machine2jobgroup = m2j_new(machine=guest,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )
        
        
        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )
        return web.accepted()
Example #30
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        target_regex = re.compile(
            r"^bonding_target_dev_select_(?P<dev>eth[0-9]+)")

        if not validates_bonding(self, target_regex):
            self.logger.debug("Add bonding failed. Did not validate.")
            return web.badrequest(self.view.alert)

        target_dev = []
        for input in self.input:
            m = target_regex.match(input)
            if m:
                target_dev.append(m.group('dev'))

        primary = self.input.bonding_target_dev_primary
        mode = self.input.bonding_mode

        cmdname = u"Add Bonding Setting"
        cmd = BONDING_COMMAND_ADD
        options = {}

        options['dev'] = ','.join(target_dev)
        options["primary"] = primary
        options["mode"] = mode

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options)

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, _cmd)
        _jobgroup.jobs.append(_job)

        host = findbyhost1(self.orm, host_id)
        _machine2jobgroup = m2j_new(
            machine=host,
            jobgroup_id=-1,
            uniq_key=karesansui.sheconf['env.uniqkey'],
            created_user=self.me,
            modified_user=self.me,
        )

        save_job_collaboration(
            self.orm,
            self.pysilhouette.orm,
            _machine2jobgroup,
            _jobgroup,
        )

        return web.accepted()
Example #31
0
    def POST(self):
        if not web.data():
            # No data. Return 500 - hangup error
            print("No data found in the request")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"hangup error\"}")
        else:
            data = json.loads(web.data())
            if not data:
                # No JSON. Return 500 - hangup error
                print("No JSON data found in the request")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"hangup error\"}")
            else:
                # Fetch uuid from JSON
                uuid = data["uuid"]
                if not uuid:
                    # UUID not found in request JSON. Return 500 - hangup error
                    print("UUID not found in JSON")
                    web.header('Content-Type', 'application/json','unique=True')
                    raise web.InternalError("{\"message\": \"hangup error\"}")

        con = ESL.ESLconnection('127.0.0.1', '8021', 'ClueCon')
        if not con.connected():
            # Unable to connect FreeSWITCH
            print("Unable to connect FreeSWITCH")
            web.header('Content-Type', 'application/json','unique=True')
            raise web.InternalError("{\"message\": \"call error\"}")

        # Check if mentioned call exists
        e = con.api(str("uuid_exists "+uuid))
        if (e.getBody() != 'true'):
            # Call does not exists. Return 404 - call not found
            print("Call not found for call uuid:"+uuid)
            web.header('Content-Type', 'application/json','unique=True')
            raise web.notfound("{\"message\": \"call not found\"}")
        else:
            # Call found. Sending command for hangup to FreeSWITCH
            print("Call found. Hanging up..")
            e = con.api(str("uuid_kill "+uuid))

            if (e.getBody().find("OK") != -1):
                # Call hangup Successfully. Return 202 - ok
                print("Call hangup sucessfully. Call UUID:"+uuid)
                web.header('Content-Type', 'application/json','unique=True')
                raise web.accepted("{\"message\": \"ok\"}")
            else:
                # Call hangup failed
                print("Call hangup failed")
                web.header('Content-Type', 'application/json','unique=True')
                raise web.InternalError("{\"message\": \"hangup error\"}")
Example #32
0
    def POST(self, id, action):
        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

        args = [id]
        kwargs = {}
        jobIDs = []

        if action == 'start':
            method = 'startVM'
        elif action == 'stop':
            method = 'stopVM'
        elif action == 'kill':
            method = 'killVM'
        elif action == 'rebuild':
            # TODO in the long term we would like to keep 'data'...
            jobIDs.append(web.ctx.postBackendJob('removeDiskImages', id))
            jobIDs.append(web.ctx.postBackendJob('createDiskImages', id))

            method = 'prepareDiskImages'
            args.append(['root', 'swap', 'data'])
        else:
            web.notfound()
            return None

        jobIDs.append(web.ctx.postBackendJob(method, *args, **kwargs))
        addJobIDsHeader(jobIDs)

        web.accepted()
        return None
Example #33
0
    def POST(self, id, action):
        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

        args = [id]
        kwargs = {}
        jobIDs = []

        if action == 'start':
            method = 'startVM'
        elif action == 'stop':
            method = 'stopVM'
        elif action == 'kill':
            method = 'killVM'
        elif action == 'rebuild':
            # TODO in the long term we would like to keep 'data'...
            jobIDs.append(web.ctx.postBackendJob('removeDiskImages', id))
            jobIDs.append(web.ctx.postBackendJob('createDiskImages', id))

            method = 'prepareDiskImages'
            args.append(['root', 'swap', 'data'])
        else:
            web.notfound()
            return None

        jobIDs.append(web.ctx.postBackendJob(method, *args, **kwargs))
        addJobIDsHeader(jobIDs)

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

        target_regex = re.compile(r"^bonding_target_dev_select_(?P<dev>eth[0-9]+)")

        if not validates_bonding(self, target_regex):
            self.logger.debug("Add bonding failed. Did not validate.")
            return web.badrequest(self.view.alert)

        target_dev = []
        for input in self.input:
            m = target_regex.match(input)
            if m:
                target_dev.append(m.group('dev'))

        primary = self.input.bonding_target_dev_primary
        mode    = self.input.bonding_mode

        cmdname = u"Add Bonding Setting"
        cmd = BONDING_COMMAND_ADD
        options = {}

        options['dev'] = ','.join(target_dev)
        options["primary"] = primary
        options["mode"] = mode

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options)

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, _cmd)
        _jobgroup.jobs.append(_job)

        host = findbyhost1(self.orm, host_id)
        _machine2jobgroup = m2j_new(machine=host,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )

        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )

        return web.accepted()
Example #35
0
    def POST(self, id):
        """Changes the avatar of the user identified by ``id``.

        The 'HTTP_ACCEPT' header is required to allow the controller to specify
        the acceptable media type for the response.

        There should be a logged-in user behind this request.

        The specified ``id`` should match the one of the logged-in user.

        If all these prerequisites hold true then the controller will check for 
        the existence of the field ``avatar`` containing an uploaded file.

        On success the controller will spawn an asynchronous task (in charge of
        processing the image) and will return '202 Accepted'.  Note that the
        'Location' header will be filled with the URI handy to check the status
        of the asynchronous task.

        On error an object of the specified media format containing error
        descriptions will be sent back to the caller:
        {
            "success": false,
            "errors":
            {
                "avatar": "Required"
            }
        }
        """
        # The dictionary used as default is needed by the framework to convert
        # the uploaded file, if any, to a FieldStorage object.  If 'avatar' is
        # present and it is actually a file then a FieldStorage is created;  if
        # 'avatar' is present but it is empty (i.e. form submitted without
        # specifying a file) then an emtpy string is returned.  Finally (i.e.
        # the field has not been set) an emtpy dictionary is returned.
        file = web.input(avatar={}).avatar
        webavatardir = os.path.join(web.ctx.home, app.config.AVATAR_DIR)
        ok, arg = workflows.change_avatar(web.ctx.logger, file,
                                          fs.FileSystemAdapter(),
                                          tasks.UsersAvatarChangeTask,
                                          app.config.AVATAR_DIR, webavatardir,
                                          id)
        if not ok:
            return jsonify(**arg)
        else:
            location = '/v1/users/%(userid)s/avatar/change/status/%(taskid)s'
            location = location % dict(userid=id, taskid=arg)
            web.header('Location', location)
            raise web.accepted()
Example #36
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        network_name = param[1]
        if not network_name:
            self.logger.debug("Network delete failed. Network not found.")
            return web.notfound("Network not found.")

        if network_name == 'default':
            self.logger.debug(
                'Network delete failed. Target network is "default".')
            return web.badrequest('Target network "default" can not deleted.')

        host = findbyhost1(self.orm, host_id)

        options = {}
        options['name'] = network_name
        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'],
                       VIRT_COMMAND_DELETE_NETWORK), options)

        # Job Registration
        _jobgroup = JobGroup('Delete network: %s' % network_name,
                             karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('Delete network', 0, _cmd))

        _machine2jobgroup = m2j_new(
            machine=host,
            jobgroup_id=-1,
            uniq_key=karesansui.sheconf['env.uniqkey'],
            created_user=self.me,
            modified_user=self.me,
        )

        save_job_collaboration(
            self.orm,
            self.pysilhouette.orm,
            _machine2jobgroup,
            _jobgroup,
        )

        self.logger.debug('(Delete network) Job group id==%s', _jobgroup.id)
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

        return web.accepted()
Example #37
0
    def _PUT(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_iptables_save(self, host):
            return web.badrequest(self.view.alert)

        from karesansui.lib.dict_op import DictOp
        dop = DictOp()
        dop.addconf("iptables", {})
        dop.set("iptables",["config"],self.input.iptables_save.split("\r\n"))
        retval = write_conf(dop, self, host)
        if retval is False:
            return web.internalerror('Internal Server Error. (Adding Task)')

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

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug("Delete storage pool failed. Did not validate.")
            return web.badrequest(self.view.alert)

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

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                return web.notfound()

            if kvc.is_used_storage_pool(
                    pools_obj[0].get_storage_name()) is True:
                self.logger.debug(
                    "Delete storage pool failed. Target storage pool is used by guest."
                )
                return web.badrequest("Target storage pool is used by guest.")
        finally:
            kvc.close()

        model = findbyhost1(self.orm, host_id)

        if delete_storage_pool_job(self, model,
                                   pools_obj[0].get_storage_name()) is True:
            self.logger.debug("Delete storage pool success. name=%s" %
                              (pools_obj[0].get_storage_name()))
            return web.accepted()
        else:
            self.logger.debug("Failed delete storage pool. name=%s" %
                              (pools_obj[0].get_storage_name()))
            return False
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug("Set storage pool status failed. Did not validate.")
            return web.badrequest(self.view.alert)

        model = findbyhost1(self.orm, host_id)

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

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                self.logger.debug("Set storage pool status failed. Target storage pool not found.")
                return web.notfound()

            status = int(self.input.status)
            if status == STORAGE_POOL_START:
                storagepool_start_stop_job(self, model, pools_obj[0], 'start')
            elif status == STORAGE_POOL_STOP:
                if kvc.is_used_storage_pool(name=pools_obj[0].get_storage_name(),
                                            active_only=True) is True:
                    self.logger.debug("Stop storage pool failed. Target storage pool is used by guest.")
                    return web.badrequest("Target storage pool is used by guest.")
                else:
                    storagepool_start_stop_job(self, model, pools_obj[0], 'stop')
            else:
                self.logger.debug("Set storage pool status failed. Unknown status type.")
                return web.badrequest()

            return web.accepted()
        finally:
            kvc.close()
Example #40
0
    def POST(self):
        """
        Starts Red Hat setup and download process

        :returns: JSONized Task object.
        :http: * 202 (setup task created and started)
               * 400 (invalid account data specified)
               * 404 (release not found in db)
        """
        data = self.checked_data()

        license_type = data.get("license_type")
        if license_type == 'rhsm':
            data["satellite"] = ""
            data["activation_key"] = ""

        release_data = {'release_id': data['release_id']}
        release_id = data.pop('release_id')
        release_db = db().query(Release).get(release_id)
        if not release_db:
            raise web.notfound(
                "No release with ID={0} found".format(release_id)
            )
        release_data['redhat'] = data
        release_data['release_name'] = release_db.name

        account = db().query(RedHatAccount).first()
        if account:
            db().query(RedHatAccount).update(data)
        else:
            account = RedHatAccount(**data)
            db().add(account)
        db().commit()

        task_manager = RedHatSetupTaskManager(release_data)
        try:
            task = task_manager.execute()
        except Exception as exc:
            logger.error(u'RedHatAccountHandler: error while execution'
                         ' Red Hat validation task: {0}'.format(str(exc)))
            logger.error(traceback.format_exc())
            raise web.badrequest(str(exc))

        data = build_json_response(TaskHandler.render(task))
        raise web.accepted(data=data)
Example #41
0
    def PUT(self, cluster_id):
        """:returns: JSONized Task object.
        :http: * 202 (network checking task created)
               * 404 (cluster not found in db)
        """
        data = json.loads(web.data())
        if data.get("networks"):
            data["networks"] = [
                n for n in data["networks"] if n.get("name") != "fuelweb_admin"
            ]

        cluster = self.get_object_or_404(Cluster, cluster_id)
        self.check_net_provider(cluster)

        self.check_if_network_configuration_locked(cluster)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':
            try:
                if 'networks' in data:
                    self.validator.validate_networks_update(
                        json.dumps(data)
                    )

                if 'dns_nameservers' in data:
                    self.validator.validate_dns_servers_update(
                        json.dumps(data)
                    )

                NovaNetworkManager.update(cluster, data)
            except web.webapi.badrequest as exc:
                TaskHelper.set_error(task.uuid, exc.data)
                logger.error(traceback.format_exc())
            except Exception as exc:
                TaskHelper.set_error(task.uuid, exc)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            db().rollback()
        else:
            db().commit()
        raise web.accepted(data=data)
Example #42
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        ステータス更新
         - param
           - read = 0
           - start = 1
           - stop = 2
           - restart = 3
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

        status = int(self.input.status)

        kit = KaresansuiIpTables()

        model = findbyhost1(self.orm, host_id)

        ret = False
        if status == FIREWALL_ACTION_INIT:
            ret = firewall_save(self, model)
        elif status & FIREWALL_ACTION_STOP and status & FIREWALL_ACTION_START:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'restart')

        elif status & FIREWALL_ACTION_STOP:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'stop')

        elif status & FIREWALL_ACTION_START:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'start')

        if ret is True:
            return web.accepted(url=web.ctx.path)
        else:
            return False
Example #43
0
    def POST(self):
        """Starts Red Hat setup and download process

        :returns: JSONized Task object.
        :http: * 202 (setup task created and started)
               * 400 (invalid account data specified)
               * 404 (release not found in db)
        """
        data = self.checked_data()

        license_type = data.get("license_type")
        if license_type == 'rhsm':
            data["satellite"] = ""
            data["activation_key"] = ""

        release_data = {'release_id': data['release_id']}
        release_id = data.pop('release_id')
        release_db = db().query(Release).get(release_id)
        if not release_db:
            raise web.notfound(
                "No release with ID={0} found".format(release_id)
            )
        release_data['redhat'] = data
        release_data['release_name'] = release_db.name

        account = db().query(RedHatAccount).first()
        if account:
            db().query(RedHatAccount).update(data)
        else:
            account = RedHatAccount(**data)
            db().add(account)
        db().commit()

        task_manager = RedHatSetupTaskManager(release_data)
        try:
            task = task_manager.execute()
        except Exception as exc:
            logger.error(u'RedHatAccountHandler: error while execution'
                         ' Red Hat validation task: {0}'.format(str(exc)))
            logger.error(traceback.format_exc())
            raise web.badrequest(str(exc))

        data = build_json_response(TaskHandler.render(task))
        raise web.accepted(data=data)
Example #44
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()
Example #45
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        ステータス更新
         - param
           - read = 0
           - start = 1
           - stop = 2
           - restart = 3
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

        status = int(self.input.status)

        kit = KaresansuiIpTables()

        model = findbyhost1(self.orm, host_id)

        ret = False
        if status == FIREWALL_ACTION_INIT:
            ret = firewall_save(self, model)
        elif status & FIREWALL_ACTION_STOP and status & FIREWALL_ACTION_START:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'restart')

        elif status & FIREWALL_ACTION_STOP:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'stop')

        elif status & FIREWALL_ACTION_START:
            kit.firewall_xml = kit.read_firewall_xml()
            ret = firewall_restore(self, model, 'start')

        if ret is True:
            return web.accepted(url=web.ctx.path)
        else:
            return False
Example #46
0
 def POST(self, db_name, account_id, _user=None):
   db_cnx = get_db_cnx(db_name)
   cur = db_cnx.cursor()
   query = """
     select * from Account left outer join (
       select account as id, total(total) as transaction_total from (
         select * from FinancialTransaction join (
           select total(amount) as total, financial_transaction as id from TransactionItem group by id
         ) using (id) where status = 4 or status = 5 or status = 0
       ) group by id
     ) using (id) where id = :id;"""
   data = normalize(cur.execute(query, {'id':account_id}).fetchall(), cur.description)
   data = data[0]
   if float(mf(Decimal(str(data['balance'])))) == float(mf(Decimal(str(data['transaction_total'])))): # .00 != -.00
     cur.execute("update FinancialTransaction set status = 5 where account = :id and status = 4;", {'id':int(account_id)})
     db_cnx.commit()
   else:
     print "balance %s != transaction total %s" % (data['balance'], data['transaction_total'])
   return web.accepted()
Example #47
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        network_name = param[1]
        if not network_name:
            self.logger.debug("Network delete failed. Network not found.")
            return web.notfound("Network not found.")

        if network_name == 'default':
            self.logger.debug('Network delete failed. Target network is "default".')
            return web.badrequest('Target network "default" can not deleted.')

        host = findbyhost1(self.orm, host_id)

        options = {}
        options['name'] = network_name
        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], VIRT_COMMAND_DELETE_NETWORK), options)

        # Job Registration
        _jobgroup = JobGroup('Delete network: %s' % network_name, karesansui.sheconf['env.uniqkey'])
        _jobgroup.jobs.append(Job('Delete network', 0, _cmd))

        _machine2jobgroup = m2j_new(machine=host,
                                    jobgroup_id=-1,
                                    uniq_key=karesansui.sheconf['env.uniqkey'],
                                    created_user=self.me,
                                    modified_user=self.me,
                                    )

        save_job_collaboration(self.orm,
                               self.pysilhouette.orm,
                               _machine2jobgroup,
                               _jobgroup,
                               )

        self.logger.debug('(Delete network) Job group id==%s', _jobgroup.id)
        url = '%s/job/%s.part' % (web.ctx.home, _jobgroup.id)
        self.logger.debug('Returning Location: %s' % url)

        return web.accepted()
Example #48
0
    def POST(self, userid):
        data = web.input()
        item = data.item
        category = data.category
        rate = data.rate
        ratetype = data.ratetype

        db = getDB()
        r = list(db.select('item', {'imgpath': item, 'category': category}, where='imgpath=$imgpath AND category=$category'))
        if len(r) == 0:
            raise web.notfound()

        # 尝试更新老的标记
        affected = db.update('rating', 
                  vars=dict(item=r[0]['id'], ratetype=int(ratetype), usertoken=session.usertoken), 
                  where='usertoken=$usertoken and item=$item and ratetype=$ratetype', 
                  rate=int(rate))
        if affected == 0:
            db.insert('rating', item=r[0]['id'], rate=int(rate), ratetype=int(ratetype), usertoken=session.usertoken)
        raise web.accepted()
Example #49
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()
        
        b64name = param[1]
        if not (b64name and host_id):
            return web.badrequest()

        host = findbyhost1(self.orm, host_id)

        name = base64_decode(str(b64name))

        (target, device) = name.split("@")

        net = NetworkAddress(target)
        ipaddr  = net.ipaddr
        netmask = net.netmask
        netlen  = net.netlen
        target = "%s/%s" % (ipaddr,netlen,)

        modules = ["staticroute"]

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

        dop.delete("staticroute", [device,target])

        from karesansui.lib.parser.staticroute import PARSER_COMMAND_ROUTE
        if net.netlen == 32:
            command = "%s del -host %s dev %s" % (PARSER_COMMAND_ROUTE,ipaddr,device,)
        else:
            command = "%s del -net %s netmask %s dev %s" % (PARSER_COMMAND_ROUTE,ipaddr,netmask,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()
Example #50
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id

        host = findbyhost1(self.orm, host_id)

        status = int(self.input.status)
        if status != NETWORK_RESTART:
            return web.badrequest()

        cmdname = u"Restart Network"
        cmd = NETWORK_COMMAND_RESTART
        options = {}

        _cmd = dict2command(
            "%s/%s" % (karesansui.config['application.bin.dir'], cmd), options)

        _jobgroup = JobGroup(cmdname, karesansui.sheconf['env.uniqkey'])
        _job = Job('%s command' % cmdname, 0, _cmd)
        _jobgroup.jobs.append(_job)

        host = findbyhost1(self.orm, host_id)
        _machine2jobgroup = m2j_new(
            machine=host,
            jobgroup_id=-1,
            uniq_key=karesansui.sheconf['env.uniqkey'],
            created_user=self.me,
            modified_user=self.me,
        )

        save_job_collaboration(
            self.orm,
            self.pysilhouette.orm,
            _machine2jobgroup,
            _jobgroup,
        )

        return web.accepted()
Example #51
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)
Example #52
0
    def _DELETE(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id
        uuid = param[1]

        if not validates_storage_pool(self, uuid):
            self.logger.debug("Delete storage pool failed. Did not validate.")
            return web.badrequest(self.view.alert)

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

            self.view.pools = pools

            pools_obj = kvc.get_storage_pool_UUIDString2kvn_storage_pool(uuid)
            if len(pools_obj) <= 0:
                return web.notfound()

            if kvc.is_used_storage_pool(pools_obj[0].get_storage_name()) is True:
                self.logger.debug("Delete storage pool failed. Target storage pool is used by guest.")
                return web.badrequest("Target storage pool is used by guest.")
        finally:
            kvc.close()

        model = findbyhost1(self.orm, host_id)

        if delete_storage_pool_job(self,model,pools_obj[0].get_storage_name()) is True:
            self.logger.debug("Delete storage pool success. name=%s" % (pools_obj[0].get_storage_name()))
            return web.accepted()
        else:
            self.logger.debug("Failed delete storage pool. name=%s" % (pools_obj[0].get_storage_name()))
            return False
Example #53
0
    def PUT(self, cluster_id):
        data = json.loads(web.data())
        if data.get("networks"):
            data["networks"] = [
                n for n in data["networks"] if n.get("name") != "fuelweb_admin"
            ]
        cluster = self.get_object_or_404(Cluster, cluster_id)
        self.check_net_provider(cluster)

        self.check_if_network_configuration_locked(cluster)

        task_manager = CheckNetworksTaskManager(cluster_id=cluster.id)
        task = task_manager.execute(data)

        if task.status != 'error':

            try:
                if 'networks' in data:
                    self.validator.validate_networks_update(
                        json.dumps(data)
                    )

                if 'neutron_parameters' in data:
                    self.validator.validate_neutron_params(
                        json.dumps(data),
                        cluster_id=cluster_id
                    )

                NeutronManager.update(cluster, data)
            except Exception as exc:
                TaskHelper.set_error(task.uuid, exc)
                logger.error(traceback.format_exc())

        data = build_json_response(TaskHandler.render(task))
        if task.status == 'error':
            db().rollback()
        else:
            db().commit()
        raise web.accepted(data=data)
Example #54
0
    def _PUT(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        self.view.host_id = host_id

        host = findbyhost1(self.orm, host_id)

        name = param[1]
        config = ServiceConfigParam(SERVICE_XML_FILE)
        config.load_xml_config()
        service = config.findby1service(name)
        if not service:
            self.logger.debug("Set service status failed. Service not found.")
            return web.notfound("Service not found")

        if not is_param(self.input, 'status'):
            self.logger.error(
                "Set service status failed. Missing request param.")
            return web.badrequest("Missing request param.")

        status = int(self.input.status)
        if status == SERVICE_START:
            service_job(self, host, name, "start")
        elif status == SERVICE_STOP:
            service_job(self, host, name, "stop")
        elif status == SERVICE_RESTART:
            service_job(self, host, name, "restart")
        elif status == SERVICE_ENABLE:
            service_job(self, host, name, "enable")
        elif status == SERVICE_DISABLE:
            service_job(self, host, name, "disable")
        else:
            self.logger.error(
                "Set service status failed. Invalid request param.")
            return web.badrequest("Invalid request param")

        return web.accepted()
Example #55
0
    def _PUT(self, *param, **params):
        """<comment-ja>
        ステータス更新
         - param
           - read = 0
           - start = 1
           - stop = 2
           - restart = 3
        </comment-ja>
        <comment-en>
        TODO: English Comment
        </comment-en>
        """
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

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

        status = int(self.input.status)

        model = findbyhost1(self.orm, host_id)

        ret = False
        if status & IPTABLES_ACTION_STOP and status & IPTABLES_ACTION_START:
            ret = iptables_control(self, model, 'restart')

        elif status & IPTABLES_ACTION_STOP:
            ret = iptables_control(self, model, 'stop')

        elif status & IPTABLES_ACTION_START:
            ret = iptables_control(self, model, 'start')

        if ret is True:
            return web.accepted(url=web.ctx.path)
        else:
            return False