Exemplo n.º 1
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if not validates_watch(self):
            self.logger.debug("Set watch failed. Did not validate.")
            return web.badrequest(self.view.alert)

        plugin = self.input.watch_target
        plugin_instance = None
        type = None
        type_instance = None
        plugin_ds = None
        libvirt_host = None

        if plugin == COLLECTD_PLUGIN_CPU:
            #cpu method
            plugin_instance = string.atoi(self.input.logical_cpu_number) - 1
            type_instance = self.input.cpu_status
            type = COLLECTD_CPU_TYPE
            plugin_ds = COLLECTD_CPU_DS

        elif plugin == COLLECTD_PLUGIN_MEMORY:
            #memory method
            type_instance = self.input.memory_status
            type = COLLECTD_MEMORY_TYPE
            plugin_ds = COLLECTD_MEMORY_DS

        elif plugin == COLLECTD_PLUGIN_DF:
            #df method
            type = COLLECTD_DF_TYPE
            type_instance = self.input.df_target_fs
            type_instance = re.sub(r'^/dev/', '', type_instance)
            type_instance = re.sub(r'/', '_', type_instance)
            plugin_ds = self.input.df_disk_status

        elif plugin == COLLECTD_PLUGIN_INTERFACE:
            #interface method
            type = self.input.network_status
            type_instance = self.input.network_target_interface
            plugin_ds = self.input.network_direction

        elif plugin == COLLECTD_PLUGIN_LIBVIRT:
            #libvirt method
            libvirt_host = self.input.libvirt_target_machine
            if self.input.libvirt_target == "cpu":
                if self.input.libvirt_vcpu_target == "total":
                    type = COLLECTD_LIBVIRT_TYPE['CPU_TOTAL']
                else:
                    type = COLLECTD_LIBVIRT_TYPE['VCPU']
                    type_instance = self.input.libvirt_vcpu_target

                plugin_ds = COLLECTD_CPU_DS

            elif self.input.libvirt_target == "disk":
                type = COLLECTD_LIBVIRT_TYPE['DISK_OCTETS']
                type_instance = self.input.libvirt_disk_target
                plugin_ds = self.input.libvirt_disk_value_type

            elif self.input.libvirt_target == "network":
                type = "if_" + self.input.libvirt_network_status
                type_instance = self.input.libvirt_target_interface
                plugin_ds = self.input.libvirt_network_direction

        elif plugin == COLLECTD_PLUGIN_LOAD:
            #load method
            type = COLLECTD_LOAD_TYPE
            plugin_ds = self.input.load_term

        else:
            self.logger.debug("Set watch failed. Unknown plugin type.")
            return web.badrequest()

        plugin_selector = create_plugin_selector(plugin_instance, type, type_instance, plugin_ds, libvirt_host)

        ## text
        continuation_count = self.input.continuation_count
        prohibition_period = self.input.prohibition_period
        threshold_val1     = self.input.threshold_val1
        threshold_val2     = self.input.threshold_val2
        threshold_type     = self.input.threshold_type
        if is_param(self.input, 'warning_script'):
            warning_script = self.input.warning_script
        else:
            warning_script = ""
        if is_param(self.input, 'warning_mail_body'):
            warning_mail_body = self.input.warning_mail_body
        else:
            warning_mail_body = ""
        if is_param(self.input, 'failure_script'):
            failure_script = self.input.failure_script
        else:
            failure_script = ""
        if is_param(self.input, 'failure_mail_body'):
            failure_mail_body = self.input.failure_mail_body
        else:
            failure_mail_body = ""
        if is_param(self.input, 'okay_script'):
            okay_script = self.input.okay_script
        else:
            okay_script = ""
        if is_param(self.input, 'okay_mail_body'):
            okay_mail_body = self.input.okay_mail_body
        else:
            okay_mail_body = ""
        if is_param(self.input, 'notify_mail_to'):
            notify_mail_to = self.input.notify_mail_to
        else:
            notify_mail_to = ""
        if is_param(self.input, 'notify_mail_from'):
            notify_mail_from = self.input.notify_mail_from
        else:
            notify_mail_from = ""

        ## bool
        bool_input_key = ["use_percentage", "enable_warning_mail",
                          "enable_failure_mail", "enable_okay_mail",
                          "enable_warning_script", "enable_failure_script",
                          "enable_okay_script"]
        bool_values = {}
        for key in bool_input_key:
            if self.input.has_key(key):
                bool_values.update({key:True})
            else:
                bool_values.update({key:False})

        if threshold_type == "max":
            warning_value = create_threshold_value(min_value=None, max_value=threshold_val1)
            failure_value = create_threshold_value(min_value=None, max_value=threshold_val2)
        elif threshold_type == "min":
            warning_value = create_threshold_value(min_value=threshold_val2, max_value=None)
            failure_value = create_threshold_value(min_value=threshold_val1, max_value=None)
        else:
            self.logger.debug("Set watch failed. Unknown threshold type.")
            return web.badrequest()

        machine = m_findby1(self.orm, host_id)

        if w_is_uniq_duplication(self.orm, machine, plugin, plugin_selector) is True:
            self.logger.debug("Set watch failed. Duplicate watch DB.")
            return web.badrequest("Set watch failed. Duplication watch")

        _watch = w_new(created_user          = self.me,
                       modified_user         = self.me,
                       name                  = self.input.watch_name,
                       plugin                = plugin,
                       plugin_selector       = plugin_selector,
                       karesansui_version    = get_karesansui_version(),
                       collectd_version      = get_collectd_version(),
                       machine               = machine,
                       continuation_count    = continuation_count,
                       prohibition_period    = prohibition_period,
                       warning_value         = warning_value,
                       is_warning_percentage = bool_values.get("use_percentage"),
                       is_warning_script     = bool_values.get("enable_warning_script"),
                       warning_script        = warning_script,
                       is_warning_mail       = bool_values.get("enable_warning_mail"),
                       warning_mail_body     = warning_mail_body,
                       failure_value         = failure_value,
                       is_failure_percentage = bool_values.get("use_percentage"),
                       is_failure_script     = bool_values.get("enable_failure_script"),
                       failure_script        = failure_script,
                       is_failure_mail       = bool_values.get("enable_failure_mail"),
                       failure_mail_body     = failure_mail_body,
                       is_okay_script        = bool_values.get("enable_okay_script"),
                       okay_script           = okay_script,
                       is_okay_mail          = bool_values.get("enable_okay_mail"),
                       okay_mail_body        = okay_mail_body,
                       notify_mail_to        = notify_mail_to,
                       notify_mail_from      = notify_mail_from,
                       is_deleted            = False,
                       )
        w_save(self.orm, _watch)

        modules = ["collectdplugin"]

        host = m_findbyhost1(self.orm, host_id)
        extra_args = {'include':'^threshold_'}
        #extra_args = {}
        dop = read_conf(modules, webobj=self, machine=host, extra_args=extra_args)
        if dop is False:
            self.logger.debug("Set watch failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read Conf)')

        params = {}
        if threshold_type == "max":
            params['WarningMax'] = str(threshold_val1)
            params['FailureMax'] = str(threshold_val2)
        elif threshold_type == "min":
            params['WarningMin'] = str(threshold_val2)
            params['FailureMin'] = str(threshold_val1)

        params['Percentage'] = str(bool_values.get("use_percentage")).lower()
        params['Persist']    = "true"
        set_threshold(plugin,plugin_selector,params,dop=dop,webobj=self, host=host)

        extra_args = {}
        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("Set watch failed. Failed write conf.")
            return web.internalerror('Internal Server Error. (Write Conf)')

        return web.created(None)
Exemplo n.º 2
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

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

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

            export = []
            for pool_name in pools:
                pool = kvc.search_kvn_storage_pools(pool_name)
                path = pool[0].get_info()["target"]["path"]
                if os.path.exists(path):
                    for _afile in glob.glob("%s/*/info.dat" % (path, )):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error(
                                'Export corrupt data.(file not found) - path=%s'
                                % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]", "", title)
                        if title == "":
                            title = _('untitled')

                        created = e_param.get_created()
                        if created != "":
                            created_str = time.strftime("%Y/%m/%d %H:%M:%S", \
                                                        time.localtime(float(created)))
                        else:
                            created_str = _("N/A")

                        export.append({
                            "info": {
                                "dir": _dir,
                                "pool": pool_name,
                                "uuid": e_param.get_uuid(),
                                "name": e_param.get_domain(),
                                "created": int(created),
                                "created_str": created_str,
                                "title": title,
                                "database": {
                                    "name": e_param.database["name"],
                                    "tags": e_param.database["tags"],
                                    "attribute": e_param.database["attribute"],
                                    "notebook": {
                                        "title":
                                        e_param.database["notebook"]["title"],
                                        "value":
                                        e_param.database["notebook"]["value"],
                                    },
                                    "uniq_key": e_param.database["uniq_key"],
                                    "hypervisor":
                                    e_param.database["hypervisor"],
                                    "icon": e_param.database["icon"],
                                },
                            },
                            "xml": {
                                "on_reboot": param.get_behavior('on_reboot'),
                                "on_poweroff":
                                param.get_behavior('on_poweroff'),
                                "on_crash": param.get_behavior('on_crash'),
                                "boot_dev": param.get_boot_dev(),
                                #"bootloader" : param.get_bootloader(),
                                #"commandline" : param.get_commandline(),
                                #"current_snapshot" : param.get_current_snapshot(),
                                'disk': param.get_disk(),
                                "domain_name": param.get_domain_name(),
                                "domain_type": param.get_domain_type(),
                                "features_acpi": param.get_features_acpi(),
                                "features_apic": param.get_features_apic(),
                                "features_pae": param.get_features_pae(),
                                #"initrd" : param.get_initrd(),
                                "interface": param.get_interface(),
                                #"kernel" : param.get_kernel(),
                                "max_memory": param.get_max_memory(),
                                'max_vcpus': param.get_max_vcpus(),
                                "max_vcpus_limit": param.get_max_vcpus_limit(),
                                "memory": param.get_memory(),
                                "uuid": param.get_uuid(),
                                "vcpus": param.get_vcpus(),
                                "vcpus_limit": param.get_vcpus_limit(),
                                "graphics_autoport":
                                param.get_graphics_autoport(),
                                "keymap": param.get_graphics_keymap(),
                                "graphics_listen": param.get_graphics_listen(),
                                "graphics_passwd": param.get_graphics_passwd(),
                                "graphics_port": param.get_graphics_port(),
                            },
                            "pool": pool[0].get_info(),
                        })
            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" %
                                 self.view.uuid)
                return web.badrequest()
            else:
                export = export[0]
        finally:
            kvc.close()

        # Pool running?
        if export['pool']['is_active'] is False:
            return web.badrequest(
                "The destination, the storage pool is not running.")

        dest_domname = export['xml']['domain_name']
        dest_uniqkey = export['info']['database']['uniq_key']
        # Same guest OS is already running.
        if m_findby1uniquekey(self.orm, dest_uniqkey) is not None:
            self.logger.info(
                _("guest '%s' already exists. (DB) - %s") %
                (dest_domname, dest_uniqkey))
            return web.badrequest(
                _("guest '%s' already exists.") % dest_domname)

        dest_dir = "%s/%s" % (export['pool']['target']['path'],
                              export['xml']['domain_name'])
        if os.path.exists(dest_dir) is True:
            self.logger.info(
                _("guest '%s' already exists. (FS) - %s") %
                (dest_domname, dest_dir))
            return web.badrequest(
                _("guest '%s' already exists.") % dest_domname)

        # disk check
        try:
            src_disk = "%s/%s/images/%s.img" \
                       % (export["info"]["dir"], export["info"]["name"], export["info"]["name"])

            if os.path.exists(src_disk):
                s_size = os.path.getsize(src_disk) / (1024 * 1024
                                                      )  # a unit 'MB'
                if chk_create_disk(export["info"]["dir"], s_size) is False:
                    partition = get_partition_info(export["info"]["dir"],
                                                   header=False)
                    return web.badrequest(
                        _("No space available to create disk image in '%s' partition.") \
                        % partition[5][0])
        except:
            pass

        extra_uniq_key = string_from_uuid(generate_uuid())
        options = {}
        options["exportuuid"] = export["info"]["uuid"]
        options["destuuid"] = extra_uniq_key
        options["quiet"] = None

        # Database Notebook
        try:
            _notebook = n_new(
                export["info"]["database"]["notebook"]["title"],
                export["info"]["database"]["notebook"]["value"],
            )
        except:
            _notebook = None

        # Database Tag
        _tags = []
        try:
            tag_array = comma_split(export["info"]["database"]["tags"])
            tag_array = uniq_sort(tag_array)
            for x in tag_array:
                if t_count(self.orm, x) == 0:
                    _tags.append(t_new(x))
                else:
                    _tags.append(t_name(self.orm, x))
        except:
            _tags.append(t_new(""))

        parent = m_findby1(self.orm, host_id)
        dest_guest = m_new(
            created_user=self.me,
            modified_user=self.me,
            uniq_key=extra_uniq_key,
            name=export["info"]["database"]["name"],
            attribute=int(export["info"]["database"]["attribute"]),
            hypervisor=int(export["info"]["database"]["hypervisor"]),
            notebook=_notebook,
            tags=_tags,
            icon=export["info"]["database"]["icon"],
            is_deleted=False,
            parent=parent,
        )

        ret = regist_guest(
            self,
            _guest=dest_guest,
            icon_filename=export["info"]["database"]["icon"],
            cmd=VIRT_COMMAND_IMPORT_GUEST,
            options=options,
            cmdname=['Import Guest', 'Import Guest'],
            rollback_options={"name": export["xml"]["domain_name"]},
            is_create=False)

        if ret is True:
            return web.accepted()
        else:
            return False
Exemplo n.º 3
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        model = findbyhost1(self.orm, host_id)

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

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

            export = []
            for pool_name in pools:
                pool = kvc.search_kvn_storage_pools(pool_name)
                path = pool[0].get_info()["target"]["path"]
                if os.path.exists(path):
                    for _afile in glob.glob("%s/*/info.dat" % (path,)):
                        e_param = ExportConfigParam()
                        e_param.load_xml_config(_afile)

                        if e_param.get_uuid() != uuid:
                            continue

                        e_name = e_param.get_domain()
                        _dir = os.path.dirname(_afile)

                        param = ConfigParam(e_name)

                        path = "%s/%s.xml" % (_dir, e_name)
                        if os.path.isfile(path) is False:
                            self.logger.error('Export corrupt data.(file not found) - path=%s' % path)
                            return web.internalerror()

                        param.load_xml_config(path)

                        if e_name != param.get_domain_name():
                            self.logger.error('Export corrupt data.(The name does not match) - info=%s, xml=%s' \
                                              % (e_name, param.get_name()))
                            return web.internalerror()

                        _dir = os.path.dirname(_afile)

                        title = e_param.get_title()
                        if title != "":
                            title = re.sub("[\r\n]","",title)
                        if title == "":
                            title = _('untitled')

                        created = e_param.get_created()
                        if created != "":
                            created_str = time.strftime("%Y/%m/%d %H:%M:%S", \
                                                        time.localtime(float(created)))
                        else:
                            created_str = _("N/A")

                        export.append({"info" : {"dir" : _dir,
                                                 "pool" : pool_name,
                                                 "uuid" : e_param.get_uuid(),
                                                 "name" : e_param.get_domain(),
                                                 "created" : int(created),
                                                 "created_str" : created_str,
                                                 "title" : title,
                                                 "database" : {"name" : e_param.database["name"],
                                                               "tags" : e_param.database["tags"],
                                                               "attribute" : e_param.database["attribute"],
                                                               "notebook" : {"title" : e_param.database["notebook"]["title"],
                                                                             "value" : e_param.database["notebook"]["value"],
                                                                             },
                                                               "uniq_key" : e_param.database["uniq_key"],
                                                               "hypervisor" : e_param.database["hypervisor"],
                                                               "icon" : e_param.database["icon"],
                                                               },
                                                  },
                                       "xml" : {"on_reboot" : param.get_behavior('on_reboot'),
                                                "on_poweroff" : param.get_behavior('on_poweroff'),
                                                "on_crash" : param.get_behavior('on_crash'),
                                                "boot_dev" : param.get_boot_dev(),
                                                #"bootloader" : param.get_bootloader(),
                                                #"commandline" : param.get_commandline(),
                                                #"current_snapshot" : param.get_current_snapshot(),
                                                'disk' : param.get_disk(),
                                                "domain_name" : param.get_domain_name(),
                                                "domain_type" : param.get_domain_type(),
                                                "features_acpi" : param.get_features_acpi(),
                                                "features_apic" : param.get_features_apic(),
                                                "features_pae" : param.get_features_pae(),
                                                #"initrd" : param.get_initrd(),
                                                "interface" : param.get_interface(),
                                                #"kernel" : param.get_kernel(),
                                                "max_memory" : param.get_max_memory(),
                                                'max_vcpus' : param.get_max_vcpus(),
                                                "max_vcpus_limit" : param.get_max_vcpus_limit(),
                                                "memory" : param.get_memory(),
                                                "uuid" : param.get_uuid(),
                                                "vcpus" : param.get_vcpus(),
                                                "vcpus_limit" : param.get_vcpus_limit(),
                                                "vnc_autoport" : param.get_vnc_autoport(),
                                                "keymap" : param.get_vnc_keymap(),
                                                "vnc_listen" : param.get_vnc_listen(),
                                                "vnc_passwd" : param.get_vnc_passwd(),
                                                "vnc_port" : param.get_vnc_port(),
                                                },
                                       "pool" : pool[0].get_info(),
                                       })
            if len(export) != 1:
                self.logger.info("Export does not exist. - uuid=%s" % self.view.uuid)
                return web.badrequest()
            else:
                export = export[0]
        finally:
            kvc.close()

        # Pool running?
        if export['pool']['is_active'] is False:
            return web.badrequest("The destination, the storage pool is not running.")

        dest_domname = export['xml']['domain_name']
        dest_uniqkey = export['info']['database']['uniq_key']
        # Same guest OS is already running.
        if m_findby1uniquekey(self.orm, dest_uniqkey) is not None:
            self.logger.info(_("guest '%s' already exists. (DB) - %s") % (dest_domname, dest_uniqkey))
            return web.badrequest(_("guest '%s' already exists.") % dest_domname)

        dest_dir = "%s/%s" % (export['pool']['target']['path'], export['xml']['domain_name'])
        if os.path.exists(dest_dir) is True:
            self.logger.info(_("guest '%s' already exists. (FS) - %s") % (dest_domname, dest_dir))
            return  web.badrequest(_("guest '%s' already exists.") % dest_domname)

        # disk check
        try:
            src_disk = "%s/%s/images/%s.img" \
                       % (export["info"]["dir"], export["info"]["name"], export["info"]["name"])

            if os.path.exists(src_disk):
                s_size = os.path.getsize(src_disk) / (1024 * 1024) # a unit 'MB'
                if chk_create_disk(export["info"]["dir"], s_size) is False:
                    partition = get_partition_info(export["info"]["dir"], header=False)
                    return web.badrequest(
                        _("No space available to create disk image in '%s' partition.") \
                        % partition[5][0])
        except:
            pass

        extra_uniq_key = string_from_uuid(generate_uuid())
        options = {}
        options["exportuuid"] = export["info"]["uuid"]
        options["destuuid"] = extra_uniq_key
        options["quiet"] = None

        # Database Notebook
        try:
            _notebook = n_new(
                export["info"]["database"]["notebook"]["title"],
                export["info"]["database"]["notebook"]["value"],
                )
        except:
            _notebook = None

        # Database Tag
        _tags = []
        try:
            tag_array = comma_split(export["info"]["database"]["tags"])
            tag_array = uniq_sort(tag_array)
            for x in tag_array:
                if t_count(self.orm, x) == 0:
                    _tags.append(t_new(x))
                else:
                    _tags.append(t_name(self.orm, x))
        except:
            _tags.append(t_new(""))

        parent = m_findby1(self.orm, host_id)
        dest_guest = m_new(created_user=self.me,
                           modified_user=self.me,
                           uniq_key=extra_uniq_key,
                           name=export["info"]["database"]["name"],
                           attribute=int(export["info"]["database"]["attribute"]),
                           hypervisor=int(export["info"]["database"]["hypervisor"]),
                           notebook=_notebook,
                           tags=_tags,
                           icon=export["info"]["database"]["icon"],
                           is_deleted=False,
                           parent=parent,
                           )

        ret = regist_guest(self,
                           _guest=dest_guest,
                           icon_filename=export["info"]["database"]["icon"],
                           cmd=VIRT_COMMAND_IMPORT_GUEST,
                           options=options,
                           cmdname=['Import Guest', 'Import Guest'],
                           rollback_options={"name" : export["xml"]["domain_name"]},
                           is_create=False
                           )

        if ret is True:
            return web.accepted()
        else:
            return False
Exemplo n.º 4
0
    def _POST(self, *param, **params):
        host_id = self.chk_hostby1(param)
        if host_id is None: return web.notfound()

        if not validates_watch(self):
            self.logger.debug("Set watch failed. Did not validate.")
            return web.badrequest(self.view.alert)

        plugin = self.input.watch_target
        plugin_instance = None
        type = None
        type_instance = None
        plugin_ds = None
        libvirt_host = None

        if plugin == COLLECTD_PLUGIN_CPU:
            #cpu method
            plugin_instance = string.atoi(self.input.logical_cpu_number) - 1
            type_instance = self.input.cpu_status
            type = COLLECTD_CPU_TYPE
            plugin_ds = COLLECTD_CPU_DS

        elif plugin == COLLECTD_PLUGIN_MEMORY:
            #memory method
            type_instance = self.input.memory_status
            type = COLLECTD_MEMORY_TYPE
            plugin_ds = COLLECTD_MEMORY_DS

        elif plugin == COLLECTD_PLUGIN_DF:
            #df method
            type = COLLECTD_DF_TYPE
            type_instance = self.input.df_target_fs
            type_instance = re.sub(r'^/dev/', '', type_instance)
            type_instance = re.sub(r'/', '_', type_instance)
            plugin_ds = self.input.df_disk_status

        elif plugin == COLLECTD_PLUGIN_INTERFACE:
            #interface method
            type = self.input.network_status
            type_instance = self.input.network_target_interface
            plugin_ds = self.input.network_direction

        elif plugin == COLLECTD_PLUGIN_LIBVIRT:
            #libvirt method
            libvirt_host = self.input.libvirt_target_machine
            if self.input.libvirt_target == "cpu":
                if self.input.libvirt_vcpu_target == "total":
                    type = COLLECTD_LIBVIRT_TYPE['CPU_TOTAL']
                else:
                    type = COLLECTD_LIBVIRT_TYPE['VCPU']
                    type_instance = self.input.libvirt_vcpu_target

                plugin_ds = COLLECTD_CPU_DS

            elif self.input.libvirt_target == "disk":
                type = COLLECTD_LIBVIRT_TYPE['DISK_OCTETS']
                type_instance = self.input.libvirt_disk_target
                plugin_ds = self.input.libvirt_disk_value_type

            elif self.input.libvirt_target == "network":
                type = "if_" + self.input.libvirt_network_status
                type_instance = self.input.libvirt_target_interface
                plugin_ds = self.input.libvirt_network_direction

        elif plugin == COLLECTD_PLUGIN_LOAD:
            #load method
            type = COLLECTD_LOAD_TYPE
            plugin_ds = self.input.load_term

        else:
            self.logger.debug("Set watch failed. Unknown plugin type.")
            return web.badrequest()

        plugin_selector = create_plugin_selector(plugin_instance, type,
                                                 type_instance, plugin_ds,
                                                 libvirt_host)

        ## text
        continuation_count = self.input.continuation_count
        prohibition_period = self.input.prohibition_period
        threshold_val1 = self.input.threshold_val1
        threshold_val2 = self.input.threshold_val2
        threshold_type = self.input.threshold_type
        if is_param(self.input, 'warning_script'):
            warning_script = self.input.warning_script
        else:
            warning_script = ""
        if is_param(self.input, 'warning_mail_body'):
            warning_mail_body = self.input.warning_mail_body
        else:
            warning_mail_body = ""
        if is_param(self.input, 'failure_script'):
            failure_script = self.input.failure_script
        else:
            failure_script = ""
        if is_param(self.input, 'failure_mail_body'):
            failure_mail_body = self.input.failure_mail_body
        else:
            failure_mail_body = ""
        if is_param(self.input, 'okay_script'):
            okay_script = self.input.okay_script
        else:
            okay_script = ""
        if is_param(self.input, 'okay_mail_body'):
            okay_mail_body = self.input.okay_mail_body
        else:
            okay_mail_body = ""
        if is_param(self.input, 'notify_mail_to'):
            notify_mail_to = self.input.notify_mail_to
        else:
            notify_mail_to = ""
        if is_param(self.input, 'notify_mail_from'):
            notify_mail_from = self.input.notify_mail_from
        else:
            notify_mail_from = ""

        ## bool
        bool_input_key = [
            "use_percentage", "enable_warning_mail", "enable_failure_mail",
            "enable_okay_mail", "enable_warning_script",
            "enable_failure_script", "enable_okay_script"
        ]
        bool_values = {}
        for key in bool_input_key:
            if self.input.has_key(key):
                bool_values.update({key: True})
            else:
                bool_values.update({key: False})

        if threshold_type == "max":
            warning_value = create_threshold_value(min_value=None,
                                                   max_value=threshold_val1)
            failure_value = create_threshold_value(min_value=None,
                                                   max_value=threshold_val2)
        elif threshold_type == "min":
            warning_value = create_threshold_value(min_value=threshold_val2,
                                                   max_value=None)
            failure_value = create_threshold_value(min_value=threshold_val1,
                                                   max_value=None)
        else:
            self.logger.debug("Set watch failed. Unknown threshold type.")
            return web.badrequest()

        machine = m_findby1(self.orm, host_id)

        if w_is_uniq_duplication(self.orm, machine, plugin,
                                 plugin_selector) is True:
            self.logger.debug("Set watch failed. Duplicate watch DB.")
            return web.badrequest("Set watch failed. Duplication watch")

        _watch = w_new(
            created_user=self.me,
            modified_user=self.me,
            name=self.input.watch_name,
            plugin=plugin,
            plugin_selector=plugin_selector,
            karesansui_version=get_karesansui_version(),
            collectd_version=get_collectd_version(),
            machine=machine,
            continuation_count=continuation_count,
            prohibition_period=prohibition_period,
            warning_value=warning_value,
            is_warning_percentage=bool_values.get("use_percentage"),
            is_warning_script=bool_values.get("enable_warning_script"),
            warning_script=warning_script,
            is_warning_mail=bool_values.get("enable_warning_mail"),
            warning_mail_body=warning_mail_body,
            failure_value=failure_value,
            is_failure_percentage=bool_values.get("use_percentage"),
            is_failure_script=bool_values.get("enable_failure_script"),
            failure_script=failure_script,
            is_failure_mail=bool_values.get("enable_failure_mail"),
            failure_mail_body=failure_mail_body,
            is_okay_script=bool_values.get("enable_okay_script"),
            okay_script=okay_script,
            is_okay_mail=bool_values.get("enable_okay_mail"),
            okay_mail_body=okay_mail_body,
            notify_mail_to=notify_mail_to,
            notify_mail_from=notify_mail_from,
            is_deleted=False,
        )
        w_save(self.orm, _watch)

        modules = ["collectdplugin"]

        host = m_findbyhost1(self.orm, host_id)
        extra_args = {'include': '^threshold_'}
        #extra_args = {}
        dop = read_conf(modules,
                        webobj=self,
                        machine=host,
                        extra_args=extra_args)
        if dop is False:
            self.logger.debug("Set watch failed. Failed read conf.")
            return web.internalerror('Internal Server Error. (Read Conf)')

        params = {}
        if threshold_type == "max":
            params['WarningMax'] = str(threshold_val1)
            params['FailureMax'] = str(threshold_val2)
        elif threshold_type == "min":
            params['WarningMin'] = str(threshold_val2)
            params['FailureMin'] = str(threshold_val1)

        params['Percentage'] = str(bool_values.get("use_percentage")).lower()
        params['Persist'] = "true"
        set_threshold(plugin,
                      plugin_selector,
                      params,
                      dop=dop,
                      webobj=self,
                      host=host)

        extra_args = {}
        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("Set watch failed. Failed write conf.")
            return web.internalerror('Internal Server Error. (Write Conf)')

        return web.created(None)