[libvirt] [PATCH 00/11] Split virsh

This splits virsh.c by the command groups, except 'virsh itself' group, each group will have a separate .c, filled with the its commands, a few helpers, and command group definition moved from virsh.c. and virsh.c simply include those new .c files. It still could be optimized, but this set could set up the skelton, and further optimization could be later patches. Osier Yang (11): virsh: Move definition of cmds and cmd groups right at the top of main virsh: Split cmds for domain and domain monitoring from virsh.c virsh: Split cmds for storage pool and storage volume from virsh.c virsh: Split cmds to manage network from virsh.c virsh: Split cmds to manage host interface from virsh.c virsh: Split cmds to manage network filter from virsh.c virsh: Split cmds to manage secret from virsh.c virsh: Split cmds to manage domain snapshot from virsh.c virsh: Split cmds in host group from virsh.c virsh: Split cmds in node device group from virsh.c virsh: Move command group definition into its own file tools/virsh-domain-monitor.c | 1701 ++++ tools/virsh-domain.c | 8139 +++++++++++++++++++ tools/virsh-host.c | 839 ++ tools/virsh-interface.c | 1032 +++ tools/virsh-network.c | 710 ++ tools/virsh-nodedev.c | 402 + tools/virsh-nwfilter.c | 324 + tools/virsh-pool.c | 1442 ++++ tools/virsh-secret.c | 373 + tools/virsh-snapshot.c | 1628 ++++ tools/virsh-volume.c | 1462 ++++ tools/virsh.c |18474 +----------------------------------------- 12 files changed, 18361 insertions(+), 18165 deletions(-) create mode 100644 tools/virsh-domain-monitor.c create mode 100644 tools/virsh-domain.c create mode 100644 tools/virsh-host.c create mode 100644 tools/virsh-interface.c create mode 100644 tools/virsh-network.c create mode 100644 tools/virsh-nodedev.c create mode 100644 tools/virsh-nwfilter.c create mode 100644 tools/virsh-pool.c create mode 100644 tools/virsh-secret.c create mode 100644 tools/virsh-snapshot.c create mode 100644 tools/virsh-volume.c Regards, Osier

This will avoid many conflicts if moving the codes for each command group into separate files in later patches. --- tools/virsh.c | 967 ++++++++++++++++++++++++++++----------------------------- 1 files changed, 483 insertions(+), 484 deletions(-) diff --git a/tools/virsh.c b/tools/virsh.c index 6bb0fc8..81976a0 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -18183,371 +18183,38 @@ cleanup: return ret; } -static const vshCmdDef domManagementCmds[] = { - {"attach-device", cmdAttachDevice, opts_attach_device, - info_attach_device, 0}, - {"attach-disk", cmdAttachDisk, opts_attach_disk, - info_attach_disk, 0}, - {"attach-interface", cmdAttachInterface, opts_attach_interface, - info_attach_interface, 0}, - {"autostart", cmdAutostart, opts_autostart, info_autostart, 0}, - {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0}, - {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0}, - {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0}, - {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0}, - {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0}, - {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0}, - {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0}, -#ifndef WIN32 - {"console", cmdConsole, opts_console, info_console, 0}, -#endif - {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0}, - {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0}, - {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0}, - {"create", cmdCreate, opts_create, info_create, 0}, - {"define", cmdDefine, opts_define, info_define, 0}, - {"desc", cmdDesc, opts_desc, info_desc, 0}, - {"destroy", cmdDestroy, opts_destroy, info_destroy, 0}, - {"detach-device", cmdDetachDevice, opts_detach_device, - info_detach_device, 0}, - {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0}, - {"detach-interface", cmdDetachInterface, opts_detach_interface, - info_detach_interface, 0}, - {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0}, - {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0}, - {"domid", cmdDomid, opts_domid, info_domid, 0}, - {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0}, - {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0}, - {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0}, - {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0}, - {"domname", cmdDomname, opts_domname, info_domname, 0}, - {"dompmsuspend", cmdDomPMSuspend, - opts_dom_pm_suspend, info_dom_pm_suspend, 0}, - {"dompmwakeup", cmdDomPMWakeup, - opts_dom_pm_wakeup, info_dom_pm_wakeup, 0}, - {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0}, - {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative, - info_domxmlfromnative, 0}, - {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative, - info_domxmltonative, 0}, - {"dump", cmdDump, opts_dump, info_dump, 0}, - {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0}, - {"edit", cmdEdit, opts_edit, info_edit, 0}, - {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0}, - {"send-key", cmdSendKey, opts_send_key, info_send_key, 0}, - {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0}, - {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove, - info_managedsaveremove, 0}, - {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0}, - {"memtune", cmdMemtune, opts_memtune, info_memtune, 0}, - {"migrate", cmdMigrate, opts_migrate, info_migrate, 0}, - {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime, - opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0}, - {"migrate-setspeed", cmdMigrateSetMaxSpeed, - opts_migrate_setspeed, info_migrate_setspeed, 0}, - {"migrate-getspeed", cmdMigrateGetMaxSpeed, - opts_migrate_getspeed, info_migrate_getspeed, 0}, - {"numatune", cmdNumatune, opts_numatune, info_numatune, 0}, - {"reboot", cmdReboot, opts_reboot, info_reboot, 0}, - {"reset", cmdReset, opts_reset, info_reset, 0}, - {"restore", cmdRestore, opts_restore, info_restore, 0}, - {"resume", cmdResume, opts_resume, info_resume, 0}, - {"save", cmdSave, opts_save, info_save, 0}, - {"save-image-define", cmdSaveImageDefine, opts_save_image_define, - info_save_image_define, 0}, - {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml, - info_save_image_dumpxml, 0}, - {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit, - info_save_image_edit, 0}, - {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0}, - {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0}, - {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0}, - {"setmem", cmdSetmem, opts_setmem, info_setmem, 0}, - {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0}, - {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0}, - {"start", cmdStart, opts_start, info_start, 0}, - {"suspend", cmdSuspend, opts_suspend, info_suspend, 0}, - {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0}, - {"undefine", cmdUndefine, opts_undefine, info_undefine, 0}, - {"update-device", cmdUpdateDevice, opts_update_device, - info_update_device, 0}, - {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0}, - {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0}, - {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0}, - {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef domMonitoringCmds[] = { - {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0}, - {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0}, - {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0}, - {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0}, - {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0}, - {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0}, - {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0}, - {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0}, - {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0}, - {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0}, - {"domstate", cmdDomstate, opts_domstate, info_domstate, 0}, - {"list", cmdList, opts_list, info_list, 0}, - {NULL, NULL, NULL, NULL, 0} -}; +/* --------------- + * Utils for work with command definition + * --------------- + */ +static const char * +vshCmddefGetInfo(const vshCmdDef * cmd, const char *name) +{ + const vshCmdInfo *info; -static const vshCmdDef storagePoolCmds[] = { - {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs, - opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0}, - {"find-storage-pool-sources", cmdPoolDiscoverSources, - opts_find_storage_pool_sources, info_find_storage_pool_sources, 0}, - {"pool-autostart", cmdPoolAutostart, opts_pool_autostart, - info_pool_autostart, 0}, - {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0}, - {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0}, - {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0}, - {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0}, - {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0}, - {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0}, - {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0}, - {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0}, - {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0}, - {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0}, - {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0}, - {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0}, - {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0}, - {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0}, - {"pool-undefine", cmdPoolUndefine, opts_pool_undefine, - info_pool_undefine, 0}, - {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0}, - {NULL, NULL, NULL, NULL, 0} -}; + for (info = cmd->info; info && info->name; info++) { + if (STREQ(info->name, name)) + return info->data; + } + return NULL; +} -static const vshCmdDef storageVolCmds[] = { - {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0}, - {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, - info_vol_create_as, 0}, - {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0}, - {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from, - info_vol_create_from, 0}, - {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0}, - {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0}, - {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0}, - {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0}, - {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0}, - {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0}, - {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0}, - {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0}, - {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0}, - {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0}, - {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0}, - {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0}, - {NULL, NULL, NULL, NULL, 0} -}; +/* Validate that the options associated with cmd can be parsed. */ +static int +vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg, + uint32_t *opts_required) +{ + int i; + bool optional = false; -static const vshCmdDef networkCmds[] = { - {"net-autostart", cmdNetworkAutostart, opts_network_autostart, - info_network_autostart, 0}, - {"net-create", cmdNetworkCreate, opts_network_create, - info_network_create, 0}, - {"net-define", cmdNetworkDefine, opts_network_define, - info_network_define, 0}, - {"net-destroy", cmdNetworkDestroy, opts_network_destroy, - info_network_destroy, 0}, - {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, - info_network_dumpxml, 0}, - {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0}, - {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0}, - {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0}, - {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0}, - {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0}, - {"net-undefine", cmdNetworkUndefine, opts_network_undefine, - info_network_undefine, 0}, - {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0}, - {NULL, NULL, NULL, NULL, 0} -}; + *opts_need_arg = 0; + *opts_required = 0; -static const vshCmdDef nodedevCmds[] = { - {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create, - info_node_device_create, 0}, - {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy, - info_node_device_destroy, 0}, - {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach, - info_node_device_detach, 0}, - {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach, - info_node_device_detach, VSH_CMD_FLAG_ALIAS}, - {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml, - info_node_device_dumpxml, 0}, - {"nodedev-list", cmdNodeListDevices, opts_node_list_devices, - info_node_list_devices, 0}, - {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach, - info_node_device_reattach, 0}, - {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset, - info_node_device_reset, 0}, - {NULL, NULL, NULL, NULL, 0} -}; + if (!cmd->opts) + return 0; -static const vshCmdDef ifaceCmds[] = { - {"iface-begin", cmdInterfaceBegin, opts_interface_begin, - info_interface_begin, 0}, - {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge, - info_interface_bridge, 0}, - {"iface-commit", cmdInterfaceCommit, opts_interface_commit, - info_interface_commit, 0}, - {"iface-define", cmdInterfaceDefine, opts_interface_define, - info_interface_define, 0}, - {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy, - info_interface_destroy, 0}, - {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml, - info_interface_dumpxml, 0}, - {"iface-edit", cmdInterfaceEdit, opts_interface_edit, - info_interface_edit, 0}, - {"iface-list", cmdInterfaceList, opts_interface_list, - info_interface_list, 0}, - {"iface-mac", cmdInterfaceMAC, opts_interface_mac, - info_interface_mac, 0}, - {"iface-name", cmdInterfaceName, opts_interface_name, - info_interface_name, 0}, - {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback, - info_interface_rollback, 0}, - {"iface-start", cmdInterfaceStart, opts_interface_start, - info_interface_start, 0}, - {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge, - info_interface_unbridge, 0}, - {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine, - info_interface_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef nwfilterCmds[] = { - {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define, - info_nwfilter_define, 0}, - {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml, - info_nwfilter_dumpxml, 0}, - {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit, - info_nwfilter_edit, 0}, - {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list, - info_nwfilter_list, 0}, - {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine, - info_nwfilter_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef secretCmds[] = { - {"secret-define", cmdSecretDefine, opts_secret_define, - info_secret_define, 0}, - {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml, - info_secret_dumpxml, 0}, - {"secret-get-value", cmdSecretGetValue, opts_secret_get_value, - info_secret_get_value, 0}, - {"secret-list", cmdSecretList, NULL, info_secret_list, 0}, - {"secret-set-value", cmdSecretSetValue, opts_secret_set_value, - info_secret_set_value, 0}, - {"secret-undefine", cmdSecretUndefine, opts_secret_undefine, - info_secret_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef virshCmds[] = { - {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT}, - {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT}, - {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT}, - {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT}, - {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT}, - {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef snapshotCmds[] = { - {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create, - info_snapshot_create, 0}, - {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as, - info_snapshot_create_as, 0}, - {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current, - info_snapshot_current, 0}, - {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete, - info_snapshot_delete, 0}, - {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml, - info_snapshot_dumpxml, 0}, - {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit, - info_snapshot_edit, 0}, - {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info, - info_snapshot_info, 0}, - {"snapshot-list", cmdSnapshotList, opts_snapshot_list, - info_snapshot_list, 0}, - {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent, - info_snapshot_parent, 0}, - {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert, - info_snapshot_revert, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdDef hostAndHypervisorCmds[] = { - {"capabilities", cmdCapabilities, NULL, info_capabilities, 0}, - {"connect", cmdConnect, opts_connect, info_connect, - VSH_CMD_FLAG_NOCONNECT}, - {"freecell", cmdFreecell, opts_freecell, info_freecell, 0}, - {"hostname", cmdHostname, NULL, info_hostname, 0}, - {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0}, - {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0}, - {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0}, - {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0}, - {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0}, - {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command, - info_qemu_monitor_command, 0}, - {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0}, - {"uri", cmdURI, NULL, info_uri, 0}, - {"version", cmdVersion, opts_version, info_version, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -static const vshCmdGrp cmdGroups[] = { - {VSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds}, - {VSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds}, - {VSH_CMD_GRP_HOST_AND_HV, "host", hostAndHypervisorCmds}, - {VSH_CMD_GRP_IFACE, "interface", ifaceCmds}, - {VSH_CMD_GRP_NWFILTER, "filter", nwfilterCmds}, - {VSH_CMD_GRP_NETWORK, "network", networkCmds}, - {VSH_CMD_GRP_NODEDEV, "nodedev", nodedevCmds}, - {VSH_CMD_GRP_SECRET, "secret", secretCmds}, - {VSH_CMD_GRP_SNAPSHOT, "snapshot", snapshotCmds}, - {VSH_CMD_GRP_STORAGE_POOL, "pool", storagePoolCmds}, - {VSH_CMD_GRP_STORAGE_VOL, "volume", storageVolCmds}, - {VSH_CMD_GRP_VIRSH, "virsh", virshCmds}, - {NULL, NULL, NULL} -}; - - -/* --------------- - * Utils for work with command definition - * --------------- - */ -static const char * -vshCmddefGetInfo(const vshCmdDef * cmd, const char *name) -{ - const vshCmdInfo *info; - - for (info = cmd->info; info && info->name; info++) { - if (STREQ(info->name, name)) - return info->data; - } - return NULL; -} - -/* Validate that the options associated with cmd can be parsed. */ -static int -vshCmddefOptParse(const vshCmdDef *cmd, uint32_t *opts_need_arg, - uint32_t *opts_required) -{ - int i; - bool optional = false; - - *opts_need_arg = 0; - *opts_required = 0; - - if (!cmd->opts) - return 0; - - for (i = 0; cmd->opts[i].name; i++) { - const vshCmdOptDef *opt = &cmd->opts[i]; + for (i = 0; cmd->opts[i].name; i++) { + const vshCmdOptDef *opt = &cmd->opts[i]; if (i > 31) return -1; /* too many options */ @@ -20923,135 +20590,467 @@ vshShowVersion(vshControl *ctl ATTRIBUTE_UNUSED) #endif vshPrint(ctl, "\n"); - vshPrint(ctl, "%s", _(" Miscellaneous:")); -#ifdef WITH_NODE_DEVICES - vshPrint(ctl, " Nodedev"); -#endif -#ifdef WITH_SECDRIVER_APPARMOR - vshPrint(ctl, " AppArmor"); -#endif -#ifdef WITH_SECDRIVER_SELINUX - vshPrint(ctl, " SELinux"); -#endif -#ifdef WITH_SECRETS - vshPrint(ctl, " Secrets"); -#endif -#ifdef ENABLE_DEBUG - vshPrint(ctl, " Debug"); -#endif -#ifdef WITH_DTRACE_PROBES - vshPrint(ctl, " DTrace"); -#endif -#ifdef USE_READLINE - vshPrint(ctl, " Readline"); -#endif -#ifdef WITH_DRIVER_MODULES - vshPrint(ctl, " Modular"); -#endif - vshPrint(ctl, "\n"); -} + vshPrint(ctl, "%s", _(" Miscellaneous:")); +#ifdef WITH_NODE_DEVICES + vshPrint(ctl, " Nodedev"); +#endif +#ifdef WITH_SECDRIVER_APPARMOR + vshPrint(ctl, " AppArmor"); +#endif +#ifdef WITH_SECDRIVER_SELINUX + vshPrint(ctl, " SELinux"); +#endif +#ifdef WITH_SECRETS + vshPrint(ctl, " Secrets"); +#endif +#ifdef ENABLE_DEBUG + vshPrint(ctl, " Debug"); +#endif +#ifdef WITH_DTRACE_PROBES + vshPrint(ctl, " DTrace"); +#endif +#ifdef USE_READLINE + vshPrint(ctl, " Readline"); +#endif +#ifdef WITH_DRIVER_MODULES + vshPrint(ctl, " Modular"); +#endif + vshPrint(ctl, "\n"); +} + +static bool +vshAllowedEscapeChar(char c) +{ + /* Allowed escape characters: + * a-z A-Z @ [ \ ] ^ _ + */ + return ('a' <= c && c <= 'z') || + ('@' <= c && c <= '_'); +} + +/* + * argv[]: virsh [options] [command] + * + */ +static bool +vshParseArgv(vshControl *ctl, int argc, char **argv) +{ + int arg, len; + struct option opt[] = { + {"debug", required_argument, NULL, 'd'}, + {"help", no_argument, NULL, 'h'}, + {"quiet", no_argument, NULL, 'q'}, + {"timing", no_argument, NULL, 't'}, + {"version", optional_argument, NULL, 'v'}, + {"connect", required_argument, NULL, 'c'}, + {"readonly", no_argument, NULL, 'r'}, + {"log", required_argument, NULL, 'l'}, + {"escape", required_argument, NULL, 'e'}, + {NULL, 0, NULL, 0} + }; + + /* Standard (non-command) options. The leading + ensures that no + * argument reordering takes place, so that command options are + * not confused with top-level virsh options. */ + while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) { + switch (arg) { + case 'd': + if (virStrToLong_i(optarg, NULL, 10, &ctl->debug) < 0) { + vshError(ctl, "%s", _("option -d takes a numeric argument")); + exit(EXIT_FAILURE); + } + break; + case 'h': + vshUsage(); + exit(EXIT_SUCCESS); + break; + case 'q': + ctl->quiet = true; + break; + case 't': + ctl->timing = true; + break; + case 'c': + ctl->name = vshStrdup(ctl, optarg); + break; + case 'v': + if (STRNEQ_NULLABLE(optarg, "long")) { + puts(VERSION); + exit(EXIT_SUCCESS); + } + /* fall through */ + case 'V': + vshShowVersion(ctl); + exit(EXIT_SUCCESS); + case 'r': + ctl->readonly = true; + break; + case 'l': + ctl->logfile = vshStrdup(ctl, optarg); + break; + case 'e': + len = strlen(optarg); + + if ((len == 2 && *optarg == '^' && + vshAllowedEscapeChar(optarg[1])) || + (len == 1 && *optarg != '^')) { + ctl->escapeChar = optarg; + } else { + vshError(ctl, _("Invalid string '%s' for escape sequence"), + optarg); + exit(EXIT_FAILURE); + } + break; + default: + vshError(ctl, _("unsupported option '-%c'. See --help."), arg); + exit(EXIT_FAILURE); + } + } + + if (argc > optind) { + /* parse command */ + ctl->imode = false; + if (argc - optind == 1) { + vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]); + return vshCommandStringParse(ctl, argv[optind]); + } else { + return vshCommandArgvParse(ctl, argc - optind, argv + optind); + } + } + return true; +} + +static const vshCmdDef domManagementCmds[] = { + {"attach-device", cmdAttachDevice, opts_attach_device, + info_attach_device, 0}, + {"attach-disk", cmdAttachDisk, opts_attach_disk, + info_attach_disk, 0}, + {"attach-interface", cmdAttachInterface, opts_attach_interface, + info_attach_interface, 0}, + {"autostart", cmdAutostart, opts_autostart, info_autostart, 0}, + {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0}, + {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0}, + {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0}, + {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0}, + {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0}, + {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0}, + {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0}, +#ifndef WIN32 + {"console", cmdConsole, opts_console, info_console, 0}, +#endif + {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0}, + {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0}, + {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0}, + {"create", cmdCreate, opts_create, info_create, 0}, + {"define", cmdDefine, opts_define, info_define, 0}, + {"desc", cmdDesc, opts_desc, info_desc, 0}, + {"destroy", cmdDestroy, opts_destroy, info_destroy, 0}, + {"detach-device", cmdDetachDevice, opts_detach_device, + info_detach_device, 0}, + {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0}, + {"detach-interface", cmdDetachInterface, opts_detach_interface, + info_detach_interface, 0}, + {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0}, + {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0}, + {"domid", cmdDomid, opts_domid, info_domid, 0}, + {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0}, + {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0}, + {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0}, + {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0}, + {"domname", cmdDomname, opts_domname, info_domname, 0}, + {"dompmsuspend", cmdDomPMSuspend, + opts_dom_pm_suspend, info_dom_pm_suspend, 0}, + {"dompmwakeup", cmdDomPMWakeup, + opts_dom_pm_wakeup, info_dom_pm_wakeup, 0}, + {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0}, + {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative, + info_domxmlfromnative, 0}, + {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative, + info_domxmltonative, 0}, + {"dump", cmdDump, opts_dump, info_dump, 0}, + {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0}, + {"edit", cmdEdit, opts_edit, info_edit, 0}, + {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0}, + {"send-key", cmdSendKey, opts_send_key, info_send_key, 0}, + {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0}, + {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove, + info_managedsaveremove, 0}, + {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0}, + {"memtune", cmdMemtune, opts_memtune, info_memtune, 0}, + {"migrate", cmdMigrate, opts_migrate, info_migrate, 0}, + {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime, + opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0}, + {"migrate-setspeed", cmdMigrateSetMaxSpeed, + opts_migrate_setspeed, info_migrate_setspeed, 0}, + {"migrate-getspeed", cmdMigrateGetMaxSpeed, + opts_migrate_getspeed, info_migrate_getspeed, 0}, + {"numatune", cmdNumatune, opts_numatune, info_numatune, 0}, + {"reboot", cmdReboot, opts_reboot, info_reboot, 0}, + {"reset", cmdReset, opts_reset, info_reset, 0}, + {"restore", cmdRestore, opts_restore, info_restore, 0}, + {"resume", cmdResume, opts_resume, info_resume, 0}, + {"save", cmdSave, opts_save, info_save, 0}, + {"save-image-define", cmdSaveImageDefine, opts_save_image_define, + info_save_image_define, 0}, + {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml, + info_save_image_dumpxml, 0}, + {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit, + info_save_image_edit, 0}, + {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0}, + {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0}, + {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0}, + {"setmem", cmdSetmem, opts_setmem, info_setmem, 0}, + {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0}, + {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0}, + {"start", cmdStart, opts_start, info_start, 0}, + {"suspend", cmdSuspend, opts_suspend, info_suspend, 0}, + {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0}, + {"undefine", cmdUndefine, opts_undefine, info_undefine, 0}, + {"update-device", cmdUpdateDevice, opts_update_device, + info_update_device, 0}, + {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0}, + {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0}, + {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0}, + {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef domMonitoringCmds[] = { + {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0}, + {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0}, + {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0}, + {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0}, + {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0}, + {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0}, + {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0}, + {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0}, + {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0}, + {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0}, + {"domstate", cmdDomstate, opts_domstate, info_domstate, 0}, + {"list", cmdList, opts_list, info_list, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef storagePoolCmds[] = { + {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs, + opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0}, + {"find-storage-pool-sources", cmdPoolDiscoverSources, + opts_find_storage_pool_sources, info_find_storage_pool_sources, 0}, + {"pool-autostart", cmdPoolAutostart, opts_pool_autostart, + info_pool_autostart, 0}, + {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0}, + {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0}, + {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0}, + {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0}, + {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0}, + {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0}, + {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0}, + {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0}, + {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0}, + {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0}, + {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0}, + {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0}, + {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0}, + {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0}, + {"pool-undefine", cmdPoolUndefine, opts_pool_undefine, + info_pool_undefine, 0}, + {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef storageVolCmds[] = { + {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0}, + {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, + info_vol_create_as, 0}, + {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0}, + {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from, + info_vol_create_from, 0}, + {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0}, + {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0}, + {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0}, + {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0}, + {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0}, + {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0}, + {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0}, + {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0}, + {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0}, + {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0}, + {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0}, + {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef networkCmds[] = { + {"net-autostart", cmdNetworkAutostart, opts_network_autostart, + info_network_autostart, 0}, + {"net-create", cmdNetworkCreate, opts_network_create, + info_network_create, 0}, + {"net-define", cmdNetworkDefine, opts_network_define, + info_network_define, 0}, + {"net-destroy", cmdNetworkDestroy, opts_network_destroy, + info_network_destroy, 0}, + {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, + info_network_dumpxml, 0}, + {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0}, + {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0}, + {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0}, + {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0}, + {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0}, + {"net-undefine", cmdNetworkUndefine, opts_network_undefine, + info_network_undefine, 0}, + {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef nodedevCmds[] = { + {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create, + info_node_device_create, 0}, + {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy, + info_node_device_destroy, 0}, + {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach, + info_node_device_detach, 0}, + {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach, + info_node_device_detach, VSH_CMD_FLAG_ALIAS}, + {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml, + info_node_device_dumpxml, 0}, + {"nodedev-list", cmdNodeListDevices, opts_node_list_devices, + info_node_list_devices, 0}, + {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach, + info_node_device_reattach, 0}, + {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset, + info_node_device_reset, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdDef ifaceCmds[] = { + {"iface-begin", cmdInterfaceBegin, opts_interface_begin, + info_interface_begin, 0}, + {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge, + info_interface_bridge, 0}, + {"iface-commit", cmdInterfaceCommit, opts_interface_commit, + info_interface_commit, 0}, + {"iface-define", cmdInterfaceDefine, opts_interface_define, + info_interface_define, 0}, + {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy, + info_interface_destroy, 0}, + {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml, + info_interface_dumpxml, 0}, + {"iface-edit", cmdInterfaceEdit, opts_interface_edit, + info_interface_edit, 0}, + {"iface-list", cmdInterfaceList, opts_interface_list, + info_interface_list, 0}, + {"iface-mac", cmdInterfaceMAC, opts_interface_mac, + info_interface_mac, 0}, + {"iface-name", cmdInterfaceName, opts_interface_name, + info_interface_name, 0}, + {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback, + info_interface_rollback, 0}, + {"iface-start", cmdInterfaceStart, opts_interface_start, + info_interface_start, 0}, + {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge, + info_interface_unbridge, 0}, + {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine, + info_interface_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; -static bool -vshAllowedEscapeChar(char c) -{ - /* Allowed escape characters: - * a-z A-Z @ [ \ ] ^ _ - */ - return ('a' <= c && c <= 'z') || - ('@' <= c && c <= '_'); -} +static const vshCmdDef nwfilterCmds[] = { + {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define, + info_nwfilter_define, 0}, + {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml, + info_nwfilter_dumpxml, 0}, + {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit, + info_nwfilter_edit, 0}, + {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list, + info_nwfilter_list, 0}, + {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine, + info_nwfilter_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; -/* - * argv[]: virsh [options] [command] - * - */ -static bool -vshParseArgv(vshControl *ctl, int argc, char **argv) -{ - int arg, len; - struct option opt[] = { - {"debug", required_argument, NULL, 'd'}, - {"help", no_argument, NULL, 'h'}, - {"quiet", no_argument, NULL, 'q'}, - {"timing", no_argument, NULL, 't'}, - {"version", optional_argument, NULL, 'v'}, - {"connect", required_argument, NULL, 'c'}, - {"readonly", no_argument, NULL, 'r'}, - {"log", required_argument, NULL, 'l'}, - {"escape", required_argument, NULL, 'e'}, - {NULL, 0, NULL, 0} - }; +static const vshCmdDef secretCmds[] = { + {"secret-define", cmdSecretDefine, opts_secret_define, + info_secret_define, 0}, + {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml, + info_secret_dumpxml, 0}, + {"secret-get-value", cmdSecretGetValue, opts_secret_get_value, + info_secret_get_value, 0}, + {"secret-list", cmdSecretList, NULL, info_secret_list, 0}, + {"secret-set-value", cmdSecretSetValue, opts_secret_set_value, + info_secret_set_value, 0}, + {"secret-undefine", cmdSecretUndefine, opts_secret_undefine, + info_secret_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; - /* Standard (non-command) options. The leading + ensures that no - * argument reordering takes place, so that command options are - * not confused with top-level virsh options. */ - while ((arg = getopt_long(argc, argv, "+d:hqtc:vVrl:e:", opt, NULL)) != -1) { - switch (arg) { - case 'd': - if (virStrToLong_i(optarg, NULL, 10, &ctl->debug) < 0) { - vshError(ctl, "%s", _("option -d takes a numeric argument")); - exit(EXIT_FAILURE); - } - break; - case 'h': - vshUsage(); - exit(EXIT_SUCCESS); - break; - case 'q': - ctl->quiet = true; - break; - case 't': - ctl->timing = true; - break; - case 'c': - ctl->name = vshStrdup(ctl, optarg); - break; - case 'v': - if (STRNEQ_NULLABLE(optarg, "long")) { - puts(VERSION); - exit(EXIT_SUCCESS); - } - /* fall through */ - case 'V': - vshShowVersion(ctl); - exit(EXIT_SUCCESS); - case 'r': - ctl->readonly = true; - break; - case 'l': - ctl->logfile = vshStrdup(ctl, optarg); - break; - case 'e': - len = strlen(optarg); +static const vshCmdDef virshCmds[] = { + {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT}, + {"echo", cmdEcho, opts_echo, info_echo, VSH_CMD_FLAG_NOCONNECT}, + {"exit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT}, + {"help", cmdHelp, opts_help, info_help, VSH_CMD_FLAG_NOCONNECT}, + {"pwd", cmdPwd, NULL, info_pwd, VSH_CMD_FLAG_NOCONNECT}, + {"quit", cmdQuit, NULL, info_quit, VSH_CMD_FLAG_NOCONNECT}, + {NULL, NULL, NULL, NULL, 0} +}; - if ((len == 2 && *optarg == '^' && - vshAllowedEscapeChar(optarg[1])) || - (len == 1 && *optarg != '^')) { - ctl->escapeChar = optarg; - } else { - vshError(ctl, _("Invalid string '%s' for escape sequence"), - optarg); - exit(EXIT_FAILURE); - } - break; - default: - vshError(ctl, _("unsupported option '-%c'. See --help."), arg); - exit(EXIT_FAILURE); - } - } +static const vshCmdDef snapshotCmds[] = { + {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create, + info_snapshot_create, 0}, + {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as, + info_snapshot_create_as, 0}, + {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current, + info_snapshot_current, 0}, + {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete, + info_snapshot_delete, 0}, + {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml, + info_snapshot_dumpxml, 0}, + {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit, + info_snapshot_edit, 0}, + {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info, + info_snapshot_info, 0}, + {"snapshot-list", cmdSnapshotList, opts_snapshot_list, + info_snapshot_list, 0}, + {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent, + info_snapshot_parent, 0}, + {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert, + info_snapshot_revert, 0}, + {NULL, NULL, NULL, NULL, 0} +}; - if (argc > optind) { - /* parse command */ - ctl->imode = false; - if (argc - optind == 1) { - vshDebug(ctl, VSH_ERR_INFO, "commands: \"%s\"\n", argv[optind]); - return vshCommandStringParse(ctl, argv[optind]); - } else { - return vshCommandArgvParse(ctl, argc - optind, argv + optind); - } - } - return true; -} +static const vshCmdDef hostAndHypervisorCmds[] = { + {"capabilities", cmdCapabilities, NULL, info_capabilities, 0}, + {"connect", cmdConnect, opts_connect, info_connect, + VSH_CMD_FLAG_NOCONNECT}, + {"freecell", cmdFreecell, opts_freecell, info_freecell, 0}, + {"hostname", cmdHostname, NULL, info_hostname, 0}, + {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0}, + {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0}, + {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0}, + {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0}, + {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0}, + {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command, + info_qemu_monitor_command, 0}, + {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0}, + {"uri", cmdURI, NULL, info_uri, 0}, + {"version", cmdVersion, opts_version, info_version, 0}, + {NULL, NULL, NULL, NULL, 0} +}; + +static const vshCmdGrp cmdGroups[] = { + {VSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds}, + {VSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds}, + {VSH_CMD_GRP_HOST_AND_HV, "host", hostAndHypervisorCmds}, + {VSH_CMD_GRP_IFACE, "interface", ifaceCmds}, + {VSH_CMD_GRP_NWFILTER, "filter", nwfilterCmds}, + {VSH_CMD_GRP_NETWORK, "network", networkCmds}, + {VSH_CMD_GRP_NODEDEV, "nodedev", nodedevCmds}, + {VSH_CMD_GRP_SECRET, "secret", secretCmds}, + {VSH_CMD_GRP_SNAPSHOT, "snapshot", snapshotCmds}, + {VSH_CMD_GRP_STORAGE_POOL, "pool", storagePoolCmds}, + {VSH_CMD_GRP_STORAGE_VOL, "volume", storageVolCmds}, + {VSH_CMD_GRP_VIRSH, "virsh", virshCmds}, + {NULL, NULL, NULL} +}; int main(int argc, char **argv) -- 1.7.7.3

On 07/23/2012 01:29 AM, Osier Yang wrote:
This will avoid many conflicts if moving the codes for each command group into separate files in later patches. --- tools/virsh.c | 967 ++++++++++++++++++++++++++++----------------------------- 1 files changed, 483 insertions(+), 484 deletions(-)
ACK; mechanical code motion. -- Eric Blake eblake@redhat.com +1-919-301-3266 Libvirt virtualization library http://libvirt.org

Commands to manage network are moved from virsh.c to virsh-network.c, with a few helpers for network command use. * virsh.c: Remove network commands and a few helpers. * virsh-network.c: New file, filled with network commands its helpers. --- tools/virsh-network.c | 688 +++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 678 +------------------------------------------------ 2 files changed, 690 insertions(+), 676 deletions(-) create mode 100644 tools/virsh-network.c diff --git a/tools/virsh-network.c b/tools/virsh-network.c new file mode 100644 index 0000000..459ccfe --- /dev/null +++ b/tools/virsh-network.c @@ -0,0 +1,688 @@ +/* + * virsh-network.c: Commands to manage network + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* default is lookup by Name and UUID */ +#define vshCommandOptNetwork(_ctl, _cmd, _name) \ + vshCommandOptNetworkBy(_ctl, _cmd, _name, \ + VSH_BYUUID|VSH_BYNAME) + +static virNetworkPtr +vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd, + const char **name, int flag) +{ + virNetworkPtr network = NULL; + const char *n = NULL; + const char *optname = "network"; + if (!cmd_has_option(ctl, cmd, optname)) + return NULL; + + if (vshCommandOptString(cmd, optname, &n) <= 0) + return NULL; + + vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", + cmd->def->name, optname, n); + + if (name) + *name = n; + + /* try it by UUID */ + if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network UUID\n", + cmd->def->name, optname); + network = virNetworkLookupByUUIDString(ctl->conn, n); + } + /* try it by NAME */ + if (network==NULL && (flag & VSH_BYNAME)) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network NAME\n", + cmd->def->name, optname); + network = virNetworkLookupByName(ctl->conn, n); + } + + if (!network) + vshError(ctl, _("failed to get network '%s'"), n); + + return network; +} + +/* + * "net-autostart" command + */ +static const vshCmdInfo info_network_autostart[] = { + {"help", N_("autostart a network")}, + {"desc", + N_("Configure a network to be automatically started at boot.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_autostart[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {"disable", VSH_OT_BOOL, 0, N_("disable autostarting")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkAutostart(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + const char *name; + int autostart; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) + return false; + + autostart = !vshCommandOptBool(cmd, "disable"); + + if (virNetworkSetAutostart(network, autostart) < 0) { + if (autostart) + vshError(ctl, _("failed to mark network %s as autostarted"), name); + else + vshError(ctl, _("failed to unmark network %s as autostarted"), name); + virNetworkFree(network); + return false; + } + + if (autostart) + vshPrint(ctl, _("Network %s marked as autostarted\n"), name); + else + vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name); + + virNetworkFree(network); + return true; +} + +/* + * "net-create" command + */ +static const vshCmdInfo info_network_create[] = { + {"help", N_("create a network from an XML file")}, + {"desc", N_("Create a network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_create[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkCreate(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + const char *from = NULL; + bool ret = true; + char *buffer; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + network = virNetworkCreateXML(ctl->conn, buffer); + VIR_FREE(buffer); + + if (network != NULL) { + vshPrint(ctl, _("Network %s created from %s\n"), + virNetworkGetName(network), from); + virNetworkFree(network); + } else { + vshError(ctl, _("Failed to create network from %s"), from); + ret = false; + } + return ret; +} + +/* + * "net-define" command + */ +static const vshCmdInfo info_network_define[] = { + {"help", N_("define (but don't start) a network from an XML file")}, + {"desc", N_("Define a network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_define[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkDefine(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + const char *from = NULL; + bool ret = true; + char *buffer; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + network = virNetworkDefineXML(ctl->conn, buffer); + VIR_FREE(buffer); + + if (network != NULL) { + vshPrint(ctl, _("Network %s defined from %s\n"), + virNetworkGetName(network), from); + virNetworkFree(network); + } else { + vshError(ctl, _("Failed to define network from %s"), from); + ret = false; + } + return ret; +} + +/* + * "net-destroy" command + */ +static const vshCmdInfo info_network_destroy[] = { + {"help", N_("destroy (stop) a network")}, + {"desc", N_("Forcefully stop a given network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_destroy[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkDestroy(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) + return false; + + if (virNetworkDestroy(network) == 0) { + vshPrint(ctl, _("Network %s destroyed\n"), name); + } else { + vshError(ctl, _("Failed to destroy network %s"), name); + ret = false; + } + + virNetworkFree(network); + return ret; +} + +/* + * "net-dumpxml" command + */ +static const vshCmdInfo info_network_dumpxml[] = { + {"help", N_("network information in XML")}, + {"desc", N_("Output the network information as an XML dump to stdout.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_dumpxml[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {"inactive", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("network information of an inactive domain")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + bool ret = true; + char *dump; + unsigned int flags = 0; + int inactive; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, NULL))) + return false; + + inactive = vshCommandOptBool(cmd, "inactive"); + if (inactive) + flags |= VIR_NETWORK_XML_INACTIVE; + + dump = virNetworkGetXMLDesc(network, flags); + + if (dump != NULL) { + vshPrint(ctl, "%s", dump); + VIR_FREE(dump); + } else { + ret = false; + } + + virNetworkFree(network); + return ret; +} + +/* + * "net-info" command + */ +static const vshCmdInfo info_network_info[] = { + {"help", N_("network information")}, + {"desc", N_("Returns basic information about the network")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_info[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkInfo(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + char uuid[VIR_UUID_STRING_BUFLEN]; + int autostart; + int persistent = -1; + int active = -1; + char *bridge = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, NULL))) + return false; + + vshPrint(ctl, "%-15s %s\n", _("Name"), virNetworkGetName(network)); + + if (virNetworkGetUUIDString(network, uuid) == 0) + vshPrint(ctl, "%-15s %s\n", _("UUID"), uuid); + + active = virNetworkIsActive(network); + if (active >= 0) + vshPrint(ctl, "%-15s %s\n", _("Active:"), active? _("yes") : _("no")); + + persistent = virNetworkIsPersistent(network); + if (persistent < 0) + vshPrint(ctl, "%-15s %s\n", _("Persistent:"), _("unknown")); + else + vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no")); + + if (virNetworkGetAutostart(network, &autostart) < 0) + vshPrint(ctl, "%-15s %s\n", _("Autostart:"), _("no autostart")); + else + vshPrint(ctl, "%-15s %s\n", _("Autostart:"), autostart ? _("yes") : _("no")); + + bridge = virNetworkGetBridgeName(network); + if (bridge) + vshPrint(ctl, "%-15s %s\n", _("Bridge:"), bridge); + + VIR_FREE(bridge); + virNetworkFree(network); + return true; +} + +/* + * "net-list" command + */ +static const vshCmdInfo info_network_list[] = { + {"help", N_("list networks")}, + {"desc", N_("Returns list of networks.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_list[] = { + {"inactive", VSH_OT_BOOL, 0, N_("list inactive networks")}, + {"all", VSH_OT_BOOL, 0, N_("list inactive & active networks")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + bool inactive = vshCommandOptBool(cmd, "inactive"); + bool all = vshCommandOptBool(cmd, "all"); + bool active = !inactive || all; + int maxactive = 0, maxinactive = 0, i; + char **activeNames = NULL, **inactiveNames = NULL; + inactive |= all; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (active) { + maxactive = virConnectNumOfNetworks(ctl->conn); + if (maxactive < 0) { + vshError(ctl, "%s", _("Failed to list active networks")); + return false; + } + if (maxactive) { + activeNames = vshMalloc(ctl, sizeof(char *) * maxactive); + + if ((maxactive = virConnectListNetworks(ctl->conn, activeNames, + maxactive)) < 0) { + vshError(ctl, "%s", _("Failed to list active networks")); + VIR_FREE(activeNames); + return false; + } + + qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter); + } + } + if (inactive) { + maxinactive = virConnectNumOfDefinedNetworks(ctl->conn); + if (maxinactive < 0) { + vshError(ctl, "%s", _("Failed to list inactive networks")); + VIR_FREE(activeNames); + return false; + } + if (maxinactive) { + inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive); + + if ((maxinactive = + virConnectListDefinedNetworks(ctl->conn, inactiveNames, + maxinactive)) < 0) { + vshError(ctl, "%s", _("Failed to list inactive networks")); + VIR_FREE(activeNames); + VIR_FREE(inactiveNames); + return false; + } + + qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter); + } + } + vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"), + _("Autostart")); + vshPrintExtra(ctl, "-----------------------------------------\n"); + + for (i = 0; i < maxactive; i++) { + virNetworkPtr network = + virNetworkLookupByName(ctl->conn, activeNames[i]); + const char *autostartStr; + int autostart = 0; + + /* this kind of work with networks is not atomic operation */ + if (!network) { + VIR_FREE(activeNames[i]); + continue; + } + + if (virNetworkGetAutostart(network, &autostart) < 0) + autostartStr = _("no autostart"); + else + autostartStr = autostart ? _("yes") : _("no"); + + vshPrint(ctl, "%-20s %-10s %-10s\n", + virNetworkGetName(network), + _("active"), + autostartStr); + virNetworkFree(network); + VIR_FREE(activeNames[i]); + } + for (i = 0; i < maxinactive; i++) { + virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]); + const char *autostartStr; + int autostart = 0; + + /* this kind of work with networks is not atomic operation */ + if (!network) { + VIR_FREE(inactiveNames[i]); + continue; + } + + if (virNetworkGetAutostart(network, &autostart) < 0) + autostartStr = _("no autostart"); + else + autostartStr = autostart ? _("yes") : _("no"); + + vshPrint(ctl, "%-20s %-10s %-10s\n", + inactiveNames[i], + _("inactive"), + autostartStr); + + virNetworkFree(network); + VIR_FREE(inactiveNames[i]); + } + VIR_FREE(activeNames); + VIR_FREE(inactiveNames); + return true; +} + +/* + * "net-name" command + */ +static const vshCmdInfo info_network_name[] = { + {"help", N_("convert a network UUID to network name")}, + {"desc", ""}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_name[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkName(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL, + VSH_BYUUID))) + return false; + + vshPrint(ctl, "%s\n", virNetworkGetName(network)); + virNetworkFree(network); + return true; +} + +/* + * "net-start" command + */ +static const vshCmdInfo info_network_start[] = { + {"help", N_("start a (previously defined) inactive network")}, + {"desc", N_("Start a network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_start[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkStart(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + bool ret = true; + const char *name = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) + return false; + + if (virNetworkCreate(network) == 0) { + vshPrint(ctl, _("Network %s started\n"), name); + } else { + vshError(ctl, _("Failed to start network %s"), name); + ret = false; + } + virNetworkFree(network); + return ret; +} + +/* + * "net-undefine" command + */ +static const vshCmdInfo info_network_undefine[] = { + {"help", N_("undefine an inactive network")}, + {"desc", N_("Undefine the configuration for an inactive network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_undefine[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkUndefine(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) + return false; + + if (virNetworkUndefine(network) == 0) { + vshPrint(ctl, _("Network %s has been undefined\n"), name); + } else { + vshError(ctl, _("Failed to undefine network %s"), name); + ret = false; + } + + virNetworkFree(network); + return ret; +} + +/* + * "net-uuid" command + */ +static const vshCmdInfo info_network_uuid[] = { + {"help", N_("convert a network name to network UUID")}, + {"desc", ""}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_uuid[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNetworkUuid(vshControl *ctl, const vshCmd *cmd) +{ + virNetworkPtr network; + char uuid[VIR_UUID_STRING_BUFLEN]; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL, + VSH_BYNAME))) + return false; + + if (virNetworkGetUUIDString(network, uuid) != -1) + vshPrint(ctl, "%s\n", uuid); + else + vshError(ctl, "%s", _("failed to get network UUID")); + + virNetworkFree(network); + return true; +} + +/* + * "net-edit" command + */ +static const vshCmdInfo info_network_edit[] = { + {"help", N_("edit XML configuration for a network")}, + {"desc", N_("Edit the XML configuration for a network.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_network_edit[] = { + {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static char *vshNetworkGetXMLDesc(virNetworkPtr network) +{ + unsigned int flags = VIR_NETWORK_XML_INACTIVE; + char *doc = virNetworkGetXMLDesc(network, flags); + + if (!doc && last_error->code == VIR_ERR_INVALID_ARG) { + /* The server side libvirt doesn't support + * VIR_NETWORK_XML_INACTIVE, so retry without it. + */ + virFreeError(last_error); + last_error = NULL; + flags &= ~VIR_NETWORK_XML_INACTIVE; + doc = virNetworkGetXMLDesc(network, flags); + } + return doc; +} + +static bool +cmdNetworkEdit(vshControl *ctl, const vshCmd *cmd) +{ + bool ret = false; + virNetworkPtr network = NULL; + virNetworkPtr network_edited = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + network = vshCommandOptNetwork(ctl, cmd, NULL); + if (network == NULL) + goto cleanup; + +#define EDIT_GET_XML vshNetworkGetXMLDesc(network) +#define EDIT_NOT_CHANGED \ + vshPrint(ctl, _("Network %s XML configuration not changed.\n"), \ + virNetworkGetName(network)); \ + ret = true; goto edit_cleanup; +#define EDIT_DEFINE \ + (network_edited = virNetworkDefineXML(ctl->conn, doc_edited)) +#define EDIT_FREE \ + if (network_edited) \ + virNetworkFree(network_edited); +#include "virsh-edit.c" + + vshPrint(ctl, _("Network %s XML configuration edited.\n"), + virNetworkGetName(network_edited)); + + ret = true; + + cleanup: + if (network) + virNetworkFree(network); + if (network_edited) + virNetworkFree(network_edited); + + return ret; +} diff --git a/tools/virsh.c b/tools/virsh.c index db35352..8603854 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -339,14 +339,6 @@ static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, #define vshCommandOptDomain(_ctl, _cmd, _name) \ vshCommandOptDomainBy(_ctl, _cmd, _name, VSH_BYID|VSH_BYUUID|VSH_BYNAME) -static virNetworkPtr vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd, - const char **name, int flag); - -/* default is lookup by Name and UUID */ -#define vshCommandOptNetwork(_ctl, _cmd, _name) \ - vshCommandOptNetworkBy(_ctl, _cmd, _name, \ - VSH_BYUUID|VSH_BYNAME) - static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, const char **name, int flag); @@ -1278,292 +1270,6 @@ cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) } /* - * "net-autostart" command - */ -static const vshCmdInfo info_network_autostart[] = { - {"help", N_("autostart a network")}, - {"desc", - N_("Configure a network to be automatically started at boot.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_autostart[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {"disable", VSH_OT_BOOL, 0, N_("disable autostarting")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkAutostart(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - const char *name; - int autostart; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) - return false; - - autostart = !vshCommandOptBool(cmd, "disable"); - - if (virNetworkSetAutostart(network, autostart) < 0) { - if (autostart) - vshError(ctl, _("failed to mark network %s as autostarted"), name); - else - vshError(ctl, _("failed to unmark network %s as autostarted"), name); - virNetworkFree(network); - return false; - } - - if (autostart) - vshPrint(ctl, _("Network %s marked as autostarted\n"), name); - else - vshPrint(ctl, _("Network %s unmarked as autostarted\n"), name); - - virNetworkFree(network); - return true; -} - -/* - * "net-create" command - */ -static const vshCmdInfo info_network_create[] = { - {"help", N_("create a network from an XML file")}, - {"desc", N_("Create a network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_create[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkCreate(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - const char *from = NULL; - bool ret = true; - char *buffer; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - network = virNetworkCreateXML(ctl->conn, buffer); - VIR_FREE(buffer); - - if (network != NULL) { - vshPrint(ctl, _("Network %s created from %s\n"), - virNetworkGetName(network), from); - virNetworkFree(network); - } else { - vshError(ctl, _("Failed to create network from %s"), from); - ret = false; - } - return ret; -} - - -/* - * "net-define" command - */ -static const vshCmdInfo info_network_define[] = { - {"help", N_("define (but don't start) a network from an XML file")}, - {"desc", N_("Define a network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_define[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network description")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkDefine(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - const char *from = NULL; - bool ret = true; - char *buffer; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - network = virNetworkDefineXML(ctl->conn, buffer); - VIR_FREE(buffer); - - if (network != NULL) { - vshPrint(ctl, _("Network %s defined from %s\n"), - virNetworkGetName(network), from); - virNetworkFree(network); - } else { - vshError(ctl, _("Failed to define network from %s"), from); - ret = false; - } - return ret; -} - - -/* - * "net-destroy" command - */ -static const vshCmdInfo info_network_destroy[] = { - {"help", N_("destroy (stop) a network")}, - {"desc", N_("Forcefully stop a given network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_destroy[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkDestroy(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) - return false; - - if (virNetworkDestroy(network) == 0) { - vshPrint(ctl, _("Network %s destroyed\n"), name); - } else { - vshError(ctl, _("Failed to destroy network %s"), name); - ret = false; - } - - virNetworkFree(network); - return ret; -} - - -/* - * "net-dumpxml" command - */ -static const vshCmdInfo info_network_dumpxml[] = { - {"help", N_("network information in XML")}, - {"desc", N_("Output the network information as an XML dump to stdout.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_dumpxml[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {"inactive", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("network information of an inactive domain")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - bool ret = true; - char *dump; - unsigned int flags = 0; - int inactive; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, NULL))) - return false; - - inactive = vshCommandOptBool(cmd, "inactive"); - if (inactive) - flags |= VIR_NETWORK_XML_INACTIVE; - - dump = virNetworkGetXMLDesc(network, flags); - - if (dump != NULL) { - vshPrint(ctl, "%s", dump); - VIR_FREE(dump); - } else { - ret = false; - } - - virNetworkFree(network); - return ret; -} - -/* - * "net-info" command - */ -static const vshCmdInfo info_network_info[] = { - {"help", N_("network information")}, - {"desc", N_("Returns basic information about the network")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_info[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkInfo(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - char uuid[VIR_UUID_STRING_BUFLEN]; - int autostart; - int persistent = -1; - int active = -1; - char *bridge = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, NULL))) - return false; - - vshPrint(ctl, "%-15s %s\n", _("Name"), virNetworkGetName(network)); - - if (virNetworkGetUUIDString(network, uuid) == 0) - vshPrint(ctl, "%-15s %s\n", _("UUID"), uuid); - - active = virNetworkIsActive(network); - if (active >= 0) - vshPrint(ctl, "%-15s %s\n", _("Active:"), active? _("yes") : _("no")); - - persistent = virNetworkIsPersistent(network); - if (persistent < 0) - vshPrint(ctl, "%-15s %s\n", _("Persistent:"), _("unknown")); - else - vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no")); - - if (virNetworkGetAutostart(network, &autostart) < 0) - vshPrint(ctl, "%-15s %s\n", _("Autostart:"), _("no autostart")); - else - vshPrint(ctl, "%-15s %s\n", _("Autostart:"), autostart ? _("yes") : _("no")); - - bridge = virNetworkGetBridgeName(network); - if (bridge) - vshPrint(ctl, "%-15s %s\n", _("Bridge:"), bridge); - - VIR_FREE(bridge); - virNetworkFree(network); - return true; -} - -/* * "iface-edit" command */ static const vshCmdInfo info_interface_edit[] = { @@ -1618,278 +1324,6 @@ cleanup: return ret; } -/* - * "net-list" command - */ -static const vshCmdInfo info_network_list[] = { - {"help", N_("list networks")}, - {"desc", N_("Returns list of networks.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_list[] = { - {"inactive", VSH_OT_BOOL, 0, N_("list inactive networks")}, - {"all", VSH_OT_BOOL, 0, N_("list inactive & active networks")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - bool inactive = vshCommandOptBool(cmd, "inactive"); - bool all = vshCommandOptBool(cmd, "all"); - bool active = !inactive || all; - int maxactive = 0, maxinactive = 0, i; - char **activeNames = NULL, **inactiveNames = NULL; - inactive |= all; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (active) { - maxactive = virConnectNumOfNetworks(ctl->conn); - if (maxactive < 0) { - vshError(ctl, "%s", _("Failed to list active networks")); - return false; - } - if (maxactive) { - activeNames = vshMalloc(ctl, sizeof(char *) * maxactive); - - if ((maxactive = virConnectListNetworks(ctl->conn, activeNames, - maxactive)) < 0) { - vshError(ctl, "%s", _("Failed to list active networks")); - VIR_FREE(activeNames); - return false; - } - - qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter); - } - } - if (inactive) { - maxinactive = virConnectNumOfDefinedNetworks(ctl->conn); - if (maxinactive < 0) { - vshError(ctl, "%s", _("Failed to list inactive networks")); - VIR_FREE(activeNames); - return false; - } - if (maxinactive) { - inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive); - - if ((maxinactive = - virConnectListDefinedNetworks(ctl->conn, inactiveNames, - maxinactive)) < 0) { - vshError(ctl, "%s", _("Failed to list inactive networks")); - VIR_FREE(activeNames); - VIR_FREE(inactiveNames); - return false; - } - - qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter); - } - } - vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"), - _("Autostart")); - vshPrintExtra(ctl, "-----------------------------------------\n"); - - for (i = 0; i < maxactive; i++) { - virNetworkPtr network = - virNetworkLookupByName(ctl->conn, activeNames[i]); - const char *autostartStr; - int autostart = 0; - - /* this kind of work with networks is not atomic operation */ - if (!network) { - VIR_FREE(activeNames[i]); - continue; - } - - if (virNetworkGetAutostart(network, &autostart) < 0) - autostartStr = _("no autostart"); - else - autostartStr = autostart ? _("yes") : _("no"); - - vshPrint(ctl, "%-20s %-10s %-10s\n", - virNetworkGetName(network), - _("active"), - autostartStr); - virNetworkFree(network); - VIR_FREE(activeNames[i]); - } - for (i = 0; i < maxinactive; i++) { - virNetworkPtr network = virNetworkLookupByName(ctl->conn, inactiveNames[i]); - const char *autostartStr; - int autostart = 0; - - /* this kind of work with networks is not atomic operation */ - if (!network) { - VIR_FREE(inactiveNames[i]); - continue; - } - - if (virNetworkGetAutostart(network, &autostart) < 0) - autostartStr = _("no autostart"); - else - autostartStr = autostart ? _("yes") : _("no"); - - vshPrint(ctl, "%-20s %-10s %-10s\n", - inactiveNames[i], - _("inactive"), - autostartStr); - - virNetworkFree(network); - VIR_FREE(inactiveNames[i]); - } - VIR_FREE(activeNames); - VIR_FREE(inactiveNames); - return true; -} - - -/* - * "net-name" command - */ -static const vshCmdInfo info_network_name[] = { - {"help", N_("convert a network UUID to network name")}, - {"desc", ""}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_name[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkName(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL, - VSH_BYUUID))) - return false; - - vshPrint(ctl, "%s\n", virNetworkGetName(network)); - virNetworkFree(network); - return true; -} - - -/* - * "net-start" command - */ -static const vshCmdInfo info_network_start[] = { - {"help", N_("start a (previously defined) inactive network")}, - {"desc", N_("Start a network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_start[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkStart(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - bool ret = true; - const char *name = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) - return false; - - if (virNetworkCreate(network) == 0) { - vshPrint(ctl, _("Network %s started\n"), name); - } else { - vshError(ctl, _("Failed to start network %s"), name); - ret = false; - } - virNetworkFree(network); - return ret; -} - - -/* - * "net-undefine" command - */ -static const vshCmdInfo info_network_undefine[] = { - {"help", N_("undefine an inactive network")}, - {"desc", N_("Undefine the configuration for an inactive network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_undefine[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkUndefine(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetwork(ctl, cmd, &name))) - return false; - - if (virNetworkUndefine(network) == 0) { - vshPrint(ctl, _("Network %s has been undefined\n"), name); - } else { - vshError(ctl, _("Failed to undefine network %s"), name); - ret = false; - } - - virNetworkFree(network); - return ret; -} - - -/* - * "net-uuid" command - */ -static const vshCmdInfo info_network_uuid[] = { - {"help", N_("convert a network name to network UUID")}, - {"desc", ""}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_uuid[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNetworkUuid(vshControl *ctl, const vshCmd *cmd) -{ - virNetworkPtr network; - char uuid[VIR_UUID_STRING_BUFLEN]; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(network = vshCommandOptNetworkBy(ctl, cmd, NULL, - VSH_BYNAME))) - return false; - - if (virNetworkGetUUIDString(network, uuid) != -1) - vshPrint(ctl, "%s\n", uuid); - else - vshError(ctl, "%s", _("failed to get network UUID")); - - virNetworkFree(network); - return true; -} - - /**************************************************************************/ /* * "iface-list" command @@ -4210,77 +3644,6 @@ cmdEcho(vshControl *ctl, const vshCmd *cmd) } /* - * "net-edit" command - */ -static const vshCmdInfo info_network_edit[] = { - {"help", N_("edit XML configuration for a network")}, - {"desc", N_("Edit the XML configuration for a network.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_network_edit[] = { - {"network", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static char *vshNetworkGetXMLDesc(virNetworkPtr network) -{ - unsigned int flags = VIR_NETWORK_XML_INACTIVE; - char *doc = virNetworkGetXMLDesc(network, flags); - - if (!doc && last_error->code == VIR_ERR_INVALID_ARG) { - /* The server side libvirt doesn't support - * VIR_NETWORK_XML_INACTIVE, so retry without it. - */ - virFreeError(last_error); - last_error = NULL; - flags &= ~VIR_NETWORK_XML_INACTIVE; - doc = virNetworkGetXMLDesc(network, flags); - } - return doc; -} - -static bool -cmdNetworkEdit(vshControl *ctl, const vshCmd *cmd) -{ - bool ret = false; - virNetworkPtr network = NULL; - virNetworkPtr network_edited = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - network = vshCommandOptNetwork(ctl, cmd, NULL); - if (network == NULL) - goto cleanup; - -#define EDIT_GET_XML vshNetworkGetXMLDesc(network) -#define EDIT_NOT_CHANGED \ - vshPrint(ctl, _("Network %s XML configuration not changed.\n"), \ - virNetworkGetName(network)); \ - ret = true; goto edit_cleanup; -#define EDIT_DEFINE \ - (network_edited = virNetworkDefineXML(ctl->conn, doc_edited)) -#define EDIT_FREE \ - if (network_edited) \ - virNetworkFree(network_edited); -#include "virsh-edit.c" - - vshPrint(ctl, _("Network %s XML configuration edited.\n"), - virNetworkGetName(network_edited)); - - ret = true; - - cleanup: - if (network) - virNetworkFree(network); - if (network_edited) - virNetworkFree(network_edited); - - return ret; -} - -/* * "quit" command */ static const vshCmdInfo info_quit[] = { @@ -6717,45 +6080,6 @@ vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, return dom; } -static virNetworkPtr -vshCommandOptNetworkBy(vshControl *ctl, const vshCmd *cmd, - const char **name, int flag) -{ - virNetworkPtr network = NULL; - const char *n = NULL; - const char *optname = "network"; - if (!cmd_has_option(ctl, cmd, optname)) - return NULL; - - if (vshCommandOptString(cmd, optname, &n) <= 0) - return NULL; - - vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", - cmd->def->name, optname, n); - - if (name) - *name = n; - - /* try it by UUID */ - if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network UUID\n", - cmd->def->name, optname); - network = virNetworkLookupByUUIDString(ctl->conn, n); - } - /* try it by NAME */ - if (network==NULL && (flag & VSH_BYNAME)) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as network NAME\n", - cmd->def->name, optname); - network = virNetworkLookupByName(ctl->conn, n); - } - - if (!network) - vshError(ctl, _("failed to get network '%s'"), n); - - return network; -} - - static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, const char **name, int flag) @@ -8354,6 +7678,8 @@ static const vshCmdDef storageVolCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-network.c" + static const vshCmdDef networkCmds[] = { {"net-autostart", cmdNetworkAutostart, opts_network_autostart, info_network_autostart, 0}, -- 1.7.7.3

Commands to manage host interface are moved from virsh.c to virsh-interface.c, with a few helpers. * virsh.c: Remove interface commands and a few helpers. * virsh-interface.c: New file, filled with interface commands its helpers. --- tools/virsh-interface.c | 1000 +++++++++++++++++++++++++++++++++++ tools/virsh.c | 1338 +++++++---------------------------------------- 2 files changed, 1177 insertions(+), 1161 deletions(-) create mode 100644 tools/virsh-interface.c diff --git a/tools/virsh-interface.c b/tools/virsh-interface.c new file mode 100644 index 0000000..6a43bb1 --- /dev/null +++ b/tools/virsh-interface.c @@ -0,0 +1,1000 @@ +/* + * virsh-interface.c: Commands to manage host interface + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* default is lookup by Name and MAC */ +#define vshCommandOptInterface(_ctl, _cmd, _name) \ + vshCommandOptInterfaceBy(_ctl, _cmd, NULL, _name, \ + VSH_BYMAC|VSH_BYNAME) + +static virInterfacePtr +vshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd, + const char *optname, + const char **name, int flag) +{ + virInterfacePtr iface = NULL; + const char *n = NULL; + + if (!optname) + optname = "interface"; + if (!cmd_has_option(ctl, cmd, optname)) + return NULL; + + if (vshCommandOptString(cmd, optname, &n) <= 0) + return NULL; + + vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", + cmd->def->name, optname, n); + + if (name) + *name = n; + + /* try it by NAME */ + if (flag & VSH_BYNAME) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface NAME\n", + cmd->def->name, optname); + iface = virInterfaceLookupByName(ctl->conn, n); + } + /* try it by MAC */ + if (iface == NULL && (flag & VSH_BYMAC)) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface MAC\n", + cmd->def->name, optname); + iface = virInterfaceLookupByMACString(ctl->conn, n); + } + + if (!iface) + vshError(ctl, _("failed to get interface '%s'"), n); + + return iface; +} + +/* + * "iface-edit" command + */ +static const vshCmdInfo info_interface_edit[] = { + {"help", N_("edit XML configuration for a physical host interface")}, + {"desc", N_("Edit the XML configuration for a physical host interface.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_edit[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceEdit(vshControl *ctl, const vshCmd *cmd) +{ + bool ret = false; + virInterfacePtr iface = NULL; + virInterfacePtr iface_edited = NULL; + unsigned int flags = VIR_INTERFACE_XML_INACTIVE; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + iface = vshCommandOptInterface(ctl, cmd, NULL); + if (iface == NULL) + goto cleanup; + +#define EDIT_GET_XML virInterfaceGetXMLDesc(iface, flags) +#define EDIT_NOT_CHANGED \ + vshPrint(ctl, _("Interface %s XML configuration not changed.\n"), \ + virInterfaceGetName(iface)); \ + ret = true; goto edit_cleanup; +#define EDIT_DEFINE \ + (iface_edited = virInterfaceDefineXML(ctl->conn, doc_edited, 0)) +#define EDIT_FREE \ + if (iface_edited) \ + virInterfaceFree(iface_edited); +#include "virsh-edit.c" + + vshPrint(ctl, _("Interface %s XML configuration edited.\n"), + virInterfaceGetName(iface_edited)); + + ret = true; + +cleanup: + if (iface) + virInterfaceFree(iface); + if (iface_edited) + virInterfaceFree(iface_edited); + + return ret; +} + +/* + * "iface-list" command + */ +static const vshCmdInfo info_interface_list[] = { + {"help", N_("list physical host interfaces")}, + {"desc", N_("Returns list of physical host interfaces.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_list[] = { + {"inactive", VSH_OT_BOOL, 0, N_("list inactive interfaces")}, + {"all", VSH_OT_BOOL, 0, N_("list inactive & active interfaces")}, + {NULL, 0, 0, NULL} +}; +static bool +cmdInterfaceList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + bool inactive = vshCommandOptBool(cmd, "inactive"); + bool all = vshCommandOptBool(cmd, "all"); + bool active = !inactive || all; + int maxactive = 0, maxinactive = 0, i; + char **activeNames = NULL, **inactiveNames = NULL; + inactive |= all; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (active) { + maxactive = virConnectNumOfInterfaces(ctl->conn); + if (maxactive < 0) { + vshError(ctl, "%s", _("Failed to list active interfaces")); + return false; + } + if (maxactive) { + activeNames = vshMalloc(ctl, sizeof(char *) * maxactive); + + if ((maxactive = virConnectListInterfaces(ctl->conn, activeNames, + maxactive)) < 0) { + vshError(ctl, "%s", _("Failed to list active interfaces")); + VIR_FREE(activeNames); + return false; + } + + qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter); + } + } + if (inactive) { + maxinactive = virConnectNumOfDefinedInterfaces(ctl->conn); + if (maxinactive < 0) { + vshError(ctl, "%s", _("Failed to list inactive interfaces")); + VIR_FREE(activeNames); + return false; + } + if (maxinactive) { + inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive); + + if ((maxinactive = + virConnectListDefinedInterfaces(ctl->conn, inactiveNames, + maxinactive)) < 0) { + vshError(ctl, "%s", _("Failed to list inactive interfaces")); + VIR_FREE(activeNames); + VIR_FREE(inactiveNames); + return false; + } + + qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter); + } + } + vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"), + _("MAC Address")); + vshPrintExtra(ctl, "--------------------------------------------\n"); + + for (i = 0; i < maxactive; i++) { + virInterfacePtr iface = + virInterfaceLookupByName(ctl->conn, activeNames[i]); + + /* this kind of work with interfaces is not atomic */ + if (!iface) { + VIR_FREE(activeNames[i]); + continue; + } + + vshPrint(ctl, "%-20s %-10s %s\n", + virInterfaceGetName(iface), + _("active"), + virInterfaceGetMACString(iface)); + virInterfaceFree(iface); + VIR_FREE(activeNames[i]); + } + for (i = 0; i < maxinactive; i++) { + virInterfacePtr iface = + virInterfaceLookupByName(ctl->conn, inactiveNames[i]); + + /* this kind of work with interfaces is not atomic */ + if (!iface) { + VIR_FREE(inactiveNames[i]); + continue; + } + + vshPrint(ctl, "%-20s %-10s %s\n", + virInterfaceGetName(iface), + _("inactive"), + virInterfaceGetMACString(iface)); + virInterfaceFree(iface); + VIR_FREE(inactiveNames[i]); + } + VIR_FREE(activeNames); + VIR_FREE(inactiveNames); + return true; + +} + +/* + * "iface-name" command + */ +static const vshCmdInfo info_interface_name[] = { + {"help", N_("convert an interface MAC address to interface name")}, + {"desc", ""}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_name[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface mac")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceName(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL, + VSH_BYMAC))) + return false; + + vshPrint(ctl, "%s\n", virInterfaceGetName(iface)); + virInterfaceFree(iface); + return true; +} + +/* + * "iface-mac" command + */ +static const vshCmdInfo info_interface_mac[] = { + {"help", N_("convert an interface name to interface MAC address")}, + {"desc", ""}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_mac[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceMAC(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL, + VSH_BYNAME))) + return false; + + vshPrint(ctl, "%s\n", virInterfaceGetMACString(iface)); + virInterfaceFree(iface); + return true; +} + +/* + * "iface-dumpxml" command + */ +static const vshCmdInfo info_interface_dumpxml[] = { + {"help", N_("interface information in XML")}, + {"desc", N_("Output the physical host interface information as an XML dump to stdout.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_dumpxml[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, + {"inactive", VSH_OT_BOOL, 0, N_("show inactive defined XML")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + bool ret = true; + char *dump; + unsigned int flags = 0; + bool inactive = vshCommandOptBool(cmd, "inactive"); + + if (inactive) + flags |= VIR_INTERFACE_XML_INACTIVE; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(iface = vshCommandOptInterface(ctl, cmd, NULL))) + return false; + + dump = virInterfaceGetXMLDesc(iface, flags); + if (dump != NULL) { + vshPrint(ctl, "%s", dump); + VIR_FREE(dump); + } else { + ret = false; + } + + virInterfaceFree(iface); + return ret; +} + +/* + * "iface-define" command + */ +static const vshCmdInfo info_interface_define[] = { + {"help", N_("define (but don't start) a physical host interface from an XML file")}, + {"desc", N_("Define a physical host interface.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_define[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML interface description")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceDefine(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + const char *from = NULL; + bool ret = true; + char *buffer; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + iface = virInterfaceDefineXML(ctl->conn, buffer, 0); + VIR_FREE(buffer); + + if (iface != NULL) { + vshPrint(ctl, _("Interface %s defined from %s\n"), + virInterfaceGetName(iface), from); + virInterfaceFree(iface); + } else { + vshError(ctl, _("Failed to define interface from %s"), from); + ret = false; + } + return ret; +} + +/* + * "iface-undefine" command + */ +static const vshCmdInfo info_interface_undefine[] = { + {"help", N_("undefine a physical host interface (remove it from configuration)")}, + {"desc", N_("undefine an interface.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_undefine[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceUndefine(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) + return false; + + if (virInterfaceUndefine(iface) == 0) { + vshPrint(ctl, _("Interface %s undefined\n"), name); + } else { + vshError(ctl, _("Failed to undefine interface %s"), name); + ret = false; + } + + virInterfaceFree(iface); + return ret; +} + +/* + * "iface-start" command + */ +static const vshCmdInfo info_interface_start[] = { + {"help", N_("start a physical host interface (enable it / \"if-up\")")}, + {"desc", N_("start a physical host interface.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_start[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceStart(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) + return false; + + if (virInterfaceCreate(iface, 0) == 0) { + vshPrint(ctl, _("Interface %s started\n"), name); + } else { + vshError(ctl, _("Failed to start interface %s"), name); + ret = false; + } + + virInterfaceFree(iface); + return ret; +} + +/* + * "iface-destroy" command + */ +static const vshCmdInfo info_interface_destroy[] = { + {"help", N_("destroy a physical host interface (disable it / \"if-down\")")}, + {"desc", N_("forcefully stop a physical host interface.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_destroy[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceDestroy(vshControl *ctl, const vshCmd *cmd) +{ + virInterfacePtr iface; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) + return false; + + if (virInterfaceDestroy(iface, 0) == 0) { + vshPrint(ctl, _("Interface %s destroyed\n"), name); + } else { + vshError(ctl, _("Failed to destroy interface %s"), name); + ret = false; + } + + virInterfaceFree(iface); + return ret; +} + +/* + * "iface-begin" command + */ +static const vshCmdInfo info_interface_begin[] = { + {"help", N_("create a snapshot of current interfaces settings, " + "which can be later committed (iface-commit) or " + "restored (iface-rollback)")}, + {"desc", N_("Create a restore point for interfaces settings")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_begin[] = { + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceBegin(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (virInterfaceChangeBegin(ctl->conn, 0) < 0) { + vshError(ctl, "%s", _("Failed to begin network config change transaction")); + return false; + } + + vshPrint(ctl, "%s", _("Network config change transaction started\n")); + return true; +} + +/* + * "iface-commit" command + */ +static const vshCmdInfo info_interface_commit[] = { + {"help", N_("commit changes made since iface-begin and free restore point")}, + {"desc", N_("commit changes and free restore point")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_commit[] = { + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceCommit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (virInterfaceChangeCommit(ctl->conn, 0) < 0) { + vshError(ctl, "%s", _("Failed to commit network config change transaction")); + return false; + } + + vshPrint(ctl, "%s", _("Network config change transaction committed\n")); + return true; +} + +/* + * "iface-rollback" command + */ +static const vshCmdInfo info_interface_rollback[] = { + {"help", N_("rollback to previous saved configuration created via iface-begin")}, + {"desc", N_("rollback to previous restore point")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_rollback[] = { + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceRollback(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (virInterfaceChangeRollback(ctl->conn, 0) < 0) { + vshError(ctl, "%s", _("Failed to rollback network config change transaction")); + return false; + } + + vshPrint(ctl, "%s", _("Network config change transaction rolled back\n")); + return true; +} + +/* + * "iface-bridge" command + */ +static const vshCmdInfo info_interface_bridge[] = { + {"help", N_("create a bridge device and attach an existing network device to it")}, + {"desc", N_("bridge an existing network device")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_bridge[] = { + {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("existing interface name")}, + {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("new bridge device name")}, + {"no-stp", VSH_OT_BOOL, 0, N_("do not enable STP for this bridge")}, + {"delay", VSH_OT_INT, 0, + N_("number of seconds to squelch traffic on newly connected ports")}, + {"no-start", VSH_OT_BOOL, 0, N_("don't start the bridge immediately")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceBridge(vshControl *ctl, const vshCmd *cmd) +{ + bool ret = false; + virInterfacePtr if_handle = NULL, br_handle = NULL; + const char *if_name, *br_name; + char *if_type = NULL, *if2_name = NULL, *delay_str = NULL; + bool stp = false, nostart = false; + unsigned int delay = 0; + char *if_xml = NULL; + xmlChar *br_xml = NULL; + int br_xml_size; + xmlDocPtr xml_doc = NULL; + xmlXPathContextPtr ctxt = NULL; + xmlNodePtr top_node, br_node, if_node, cur; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + /* Get a handle to the original device */ + if (!(if_handle = vshCommandOptInterfaceBy(ctl, cmd, "interface", + &if_name, VSH_BYNAME))) { + goto cleanup; + } + + /* Name for new bridge device */ + if (vshCommandOptString(cmd, "bridge", &br_name) <= 0) { + vshError(ctl, "%s", _("Missing bridge device name in command")); + goto cleanup; + } + + /* make sure "new" device doesn't already exist */ + if ((br_handle = virInterfaceLookupByName(ctl->conn, br_name))) { + vshError(ctl, _("Network device %s already exists"), br_name); + goto cleanup; + } + + /* use "no-stp" because we want "stp" to default true */ + stp = !vshCommandOptBool(cmd, "no-stp"); + + if (vshCommandOptUInt(cmd, "delay", &delay) < 0) { + vshError(ctl, "%s", _("Unable to parse delay parameter")); + goto cleanup; + } + + nostart = vshCommandOptBool(cmd, "no-start"); + + /* Get the original interface into an xmlDoc */ + if (!(if_xml = virInterfaceGetXMLDesc(if_handle, VIR_INTERFACE_XML_INACTIVE))) + goto cleanup; + if (!(xml_doc = virXMLParseStringCtxt(if_xml, + _("(interface definition)"), &ctxt))) { + vshError(ctl, _("Failed to parse configuration of %s"), if_name); + goto cleanup; + } + top_node = ctxt->node; + + /* Verify that the original device isn't already a bridge. */ + if (!(if_type = virXMLPropString(top_node, "type"))) { + vshError(ctl, _("Existing device %s has no type"), if_name); + goto cleanup; + } + + if (STREQ(if_type, "bridge")) { + vshError(ctl, _("Existing device %s is already a bridge"), if_name); + goto cleanup; + } + + /* verify the name in the XML matches the device name */ + if (!(if2_name = virXMLPropString(top_node, "name")) || + STRNEQ(if2_name, if_name)) { + vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"), + if2_name, if_name); + goto cleanup; + } + + /* Create a <bridge> node under <interface>. */ + if (!(br_node = xmlNewChild(top_node, NULL, BAD_CAST "bridge", NULL))) { + vshError(ctl, "%s", _("Failed to create bridge node in xml document")); + goto cleanup; + } + + /* Set stp and delay attributes in <bridge> according to the + * commandline options. + */ + if (!xmlSetProp(br_node, BAD_CAST "stp", BAD_CAST (stp ? "on" : "off"))) { + vshError(ctl, "%s", _("Failed to set stp attribute in xml document")); + goto cleanup; + } + + if ((delay || stp) && + ((virAsprintf(&delay_str, "%d", delay) < 0) || + !xmlSetProp(br_node, BAD_CAST "delay", BAD_CAST delay_str))) { + vshError(ctl, _("Failed to set bridge delay %d in xml document"), delay); + goto cleanup; + } + + /* Change the type of the outer/master interface to "bridge" and the + * name to the provided bridge name. + */ + if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST "bridge")) { + vshError(ctl, "%s", _("Failed to set bridge interface type to 'bridge' in xml document")); + goto cleanup; + } + + if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST br_name)) { + vshError(ctl, _("Failed to set master bridge interface name to '%s' in xml document"), + br_name); + goto cleanup; + } + + /* Create an <interface> node under <bridge> that uses the + * original interface's type and name. + */ + if (!(if_node = xmlNewChild(br_node, NULL, BAD_CAST "interface", NULL))) { + vshError(ctl, "%s", _("Failed to create interface node under bridge node in xml document")); + goto cleanup; + } + + /* set the type of the inner/slave interface to the original + * if_type, and the name to the original if_name. + */ + if (!xmlSetProp(if_node, BAD_CAST "type", BAD_CAST if_type)) { + vshError(ctl, _("Failed to set new slave interface type to '%s' in xml document"), + if_name); + goto cleanup; + } + + if (!xmlSetProp(if_node, BAD_CAST "name", BAD_CAST if_name)) { + vshError(ctl, _("Failed to set new slave interface name to '%s' in xml document"), + br_name); + goto cleanup; + } + + /* Cycle through all the nodes under the original <interface>, + * moving all <mac>, <bond> and <vlan> nodes down into the new + * lower level <interface>. + */ + cur = top_node->children; + while (cur) { + xmlNodePtr old = cur; + + cur = cur->next; + if ((old->type == XML_ELEMENT_NODE) && + (xmlStrEqual(old->name, BAD_CAST "mac") || /* ethernet stuff to move down */ + xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */ + xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */ + xmlUnlinkNode(old); + if (!xmlAddChild(if_node, old)) { + vshError(ctl, _("Failed to move '%s' element in xml document"), old->name); + xmlFreeNode(old); + goto cleanup; + } + } + } + + /* The document should now be fully converted; write it out to a string. */ + xmlDocDumpMemory(xml_doc, &br_xml, &br_xml_size); + + if (!br_xml || br_xml_size <= 0) { + vshError(ctl, _("Failed to format new xml document for bridge %s"), br_name); + goto cleanup; + } + + + /* br_xml is the new interface to define. It will automatically undefine the + * independent original interface. + */ + if (!(br_handle = virInterfaceDefineXML(ctl->conn, (char *) br_xml, 0))) { + vshError(ctl, _("Failed to define new bridge interface %s"), + br_name); + goto cleanup; + } + + vshPrint(ctl, _("Created bridge %s with attached device %s\n"), + br_name, if_name); + + /* start it up unless requested not to */ + if (!nostart) { + if (virInterfaceCreate(br_handle, 0) < 0) { + vshError(ctl, _("Failed to start bridge interface %s"), br_name); + goto cleanup; + } + vshPrint(ctl, _("Bridge interface %s started\n"), br_name); + } + + ret = true; + cleanup: + if (if_handle) + virInterfaceFree(if_handle); + if (br_handle) + virInterfaceFree(br_handle); + VIR_FREE(if_xml); + VIR_FREE(br_xml); + VIR_FREE(if_type); + VIR_FREE(if2_name); + VIR_FREE(delay_str); + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml_doc); + return ret; +} + +/* + * "iface-unbridge" command + */ +static const vshCmdInfo info_interface_unbridge[] = { + {"help", N_("undefine a bridge device after detaching its slave device")}, + {"desc", N_("unbridge a network device")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_interface_unbridge[] = { + {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("current bridge device name")}, + {"no-start", VSH_OT_BOOL, 0, + N_("don't start the un-slaved interface immediately (not recommended)")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdInterfaceUnbridge(vshControl *ctl, const vshCmd *cmd) +{ + bool ret = false; + virInterfacePtr if_handle = NULL, br_handle = NULL; + const char *br_name; + char *if_type = NULL, *if_name = NULL; + bool nostart = false; + char *br_xml = NULL; + xmlChar *if_xml = NULL; + int if_xml_size; + xmlDocPtr xml_doc = NULL; + xmlXPathContextPtr ctxt = NULL; + xmlNodePtr top_node, br_node, if_node, cur; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + /* Get a handle to the original device */ + if (!(br_handle = vshCommandOptInterfaceBy(ctl, cmd, "bridge", + &br_name, VSH_BYNAME))) { + goto cleanup; + } + + nostart = vshCommandOptBool(cmd, "no-start"); + + /* Get the bridge xml into an xmlDoc */ + if (!(br_xml = virInterfaceGetXMLDesc(br_handle, VIR_INTERFACE_XML_INACTIVE))) + goto cleanup; + if (!(xml_doc = virXMLParseStringCtxt(br_xml, + _("(bridge interface definition)"), + &ctxt))) { + vshError(ctl, _("Failed to parse configuration of %s"), br_name); + goto cleanup; + } + top_node = ctxt->node; + + /* Verify that the device really is a bridge. */ + if (!(if_type = virXMLPropString(top_node, "type"))) { + vshError(ctl, _("Existing device %s has no type"), br_name); + goto cleanup; + } + + if (STRNEQ(if_type, "bridge")) { + vshError(ctl, _("Device %s is not a bridge"), br_name); + goto cleanup; + } + VIR_FREE(if_type); + + /* verify the name in the XML matches the device name */ + if (!(if_name = virXMLPropString(top_node, "name")) || + STRNEQ(if_name, br_name)) { + vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"), + if_name, br_name); + goto cleanup; + } + VIR_FREE(if_name); + + /* Find the <bridge> node under <interface>. */ + if (!(br_node = virXPathNode("./bridge", ctxt))) { + vshError(ctl, "%s", _("No bridge node in xml document")); + goto cleanup; + } + + if ((if_node = virXPathNode("./bridge/interface[2]", ctxt))) { + vshError(ctl, "%s", _("Multiple interfaces attached to bridge")); + goto cleanup; + } + + if (!(if_node = virXPathNode("./bridge/interface", ctxt))) { + vshError(ctl, "%s", _("No interface attached to bridge")); + goto cleanup; + } + + /* Change the type and name of the outer/master interface to + * the type/name of the attached slave interface. + */ + if (!(if_name = virXMLPropString(if_node, "name"))) { + vshError(ctl, _("Device attached to bridge %s has no name"), br_name); + goto cleanup; + } + + if (!(if_type = virXMLPropString(if_node, "type"))) { + vshError(ctl, _("Attached device %s has no type"), if_name); + goto cleanup; + } + + if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST if_type)) { + vshError(ctl, _("Failed to set interface type to '%s' in xml document"), + if_type); + goto cleanup; + } + + if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST if_name)) { + vshError(ctl, _("Failed to set interface name to '%s' in xml document"), + if_name); + goto cleanup; + } + + /* Cycle through all the nodes under the attached <interface>, + * moving all <mac>, <bond> and <vlan> nodes up into the toplevel + * <interface>. + */ + cur = if_node->children; + while (cur) { + xmlNodePtr old = cur; + + cur = cur->next; + if ((old->type == XML_ELEMENT_NODE) && + (xmlStrEqual(old->name, BAD_CAST "mac") || /* ethernet stuff to move down */ + xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */ + xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */ + xmlUnlinkNode(old); + if (!xmlAddChild(top_node, old)) { + vshError(ctl, _("Failed to move '%s' element in xml document"), old->name); + xmlFreeNode(old); + goto cleanup; + } + } + } + + /* The document should now be fully converted; write it out to a string. */ + xmlDocDumpMemory(xml_doc, &if_xml, &if_xml_size); + + if (!if_xml || if_xml_size <= 0) { + vshError(ctl, _("Failed to format new xml document for un-enslaved interface %s"), + if_name); + goto cleanup; + } + + /* Destroy and Undefine the bridge device, since we otherwise + * can't safely define the unattached device. + */ + if (virInterfaceDestroy(br_handle, 0) < 0) { + vshError(ctl, _("Failed to destroy bridge interface %s"), br_name); + goto cleanup; + } + if (virInterfaceUndefine(br_handle) < 0) { + vshError(ctl, _("Failed to undefine bridge interface %s"), br_name); + goto cleanup; + } + + /* if_xml is the new interface to define. + */ + if (!(if_handle = virInterfaceDefineXML(ctl->conn, (char *) if_xml, 0))) { + vshError(ctl, _("Failed to define new interface %s"), if_name); + goto cleanup; + } + + vshPrint(ctl, _("Device %s un-attached from bridge %s\n"), + if_name, br_name); + + /* unless requested otherwise, undefine the bridge device */ + if (!nostart) { + if (virInterfaceCreate(if_handle, 0) < 0) { + vshError(ctl, _("Failed to start interface %s"), if_name); + goto cleanup; + } + vshPrint(ctl, _("Interface %s started\n"), if_name); + } + + ret = true; + cleanup: + if (if_handle) + virInterfaceFree(if_handle); + if (br_handle) + virInterfaceFree(br_handle); + VIR_FREE(if_xml); + VIR_FREE(br_xml); + VIR_FREE(if_type); + VIR_FREE(if_name); + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml_doc); + return ret; +} diff --git a/tools/virsh.c b/tools/virsh.c index 8603854..23b2ec9 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -347,20 +347,6 @@ static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd vshCommandOptNWFilterBy(_ctl, _cmd, _name, \ VSH_BYUUID|VSH_BYNAME) -static virInterfacePtr vshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd, - const char *optname, - const char **name, int flag); - -/* default is lookup by Name and MAC */ -#define vshCommandOptInterface(_ctl, _cmd, _name) \ - vshCommandOptInterfaceBy(_ctl, _cmd, NULL, _name, \ - VSH_BYMAC|VSH_BYNAME) - -/* default is lookup by Name and UUID */ -#define vshCommandOptVol(_ctl, _cmd, _optname, _pooloptname, _name) \ - vshCommandOptVolBy(_ctl, _cmd, _optname, _pooloptname, _name, \ - VSH_BYUUID|VSH_BYNAME) - static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name); @@ -1024,1180 +1010,249 @@ cmdNodeCpuStats(vshControl *ctl, const vshCmd *cmd) if (vshCommandOptInt(cmd, "cpu", &cpuNum) < 0) { vshError(ctl, "%s", _("Invalid value of cpuNum")); - return false; - } - - if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) { - vshError(ctl, "%s", - _("Unable to get number of cpu stats")); - return false; - } - if (nparams == 0) { - /* nothing to output */ - return true; - } - - memset(cpu_stats, 0, sizeof(cpu_stats)); - params = vshCalloc(ctl, nparams, sizeof(*params)); - - for (i = 0; i < 2; i++) { - if (i > 0) - sleep(1); - - if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) { - vshError(ctl, "%s", _("Unable to get node cpu stats")); - goto cleanup; - } - - for (j = 0; j < nparams; j++) { - unsigned long long value = params[j].value; - - if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) { - cpu_stats[i].sys = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) { - cpu_stats[i].user = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) { - cpu_stats[i].idle = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) { - cpu_stats[i].iowait = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) { - cpu_stats[i].util = value; - flag_utilization = true; - } - } - - if (flag_utilization || !flag_percent) - break; - } - - if (!flag_percent) { - if (!flag_utilization) { - vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user); - vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys); - vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle); - vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait); - } - } else { - if (flag_utilization) { - usage = cpu_stats[0].util; - - vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage); - vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage); - } else { - user_time = cpu_stats[1].user - cpu_stats[0].user; - sys_time = cpu_stats[1].sys - cpu_stats[0].sys; - idle_time = cpu_stats[1].idle - cpu_stats[0].idle; - iowait_time = cpu_stats[1].iowait - cpu_stats[0].iowait; - total_time = user_time + sys_time + idle_time + iowait_time; - - usage = (user_time + sys_time) / total_time * 100; - - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("usage:"), usage); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("user:"), user_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("system:"), sys_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("idle:"), idle_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("iowait:"), iowait_time / total_time * 100); - } - } - - ret = true; - - cleanup: - VIR_FREE(params); - return ret; -} - -/* - * "nodememstats" command - */ -static const vshCmdInfo info_nodememstats[] = { - {"help", N_("Prints memory stats of the node.")}, - {"desc", N_("Returns memory stats of the node, in kilobytes.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_memstats[] = { - {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd) -{ - int nparams = 0; - unsigned int i = 0; - int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS; - virNodeMemoryStatsPtr params = NULL; - bool ret = false; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) { - vshError(ctl, "%s", _("Invalid value of cellNum")); - return false; - } - - /* get the number of memory parameters */ - if (virNodeGetMemoryStats(ctl->conn, cellNum, NULL, &nparams, 0) != 0) { - vshError(ctl, "%s", - _("Unable to get number of memory stats")); - goto cleanup; - } - - if (nparams == 0) { - /* nothing to output */ - ret = true; - goto cleanup; - } - - /* now go get all the memory parameters */ - params = vshCalloc(ctl, nparams, sizeof(*params)); - if (virNodeGetMemoryStats(ctl->conn, cellNum, params, &nparams, 0) != 0) { - vshError(ctl, "%s", _("Unable to get memory stats")); - goto cleanup; - } - - for (i = 0; i < nparams; i++) - vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value); - - ret = true; - - cleanup: - VIR_FREE(params); - return ret; -} - -/* - * "nodesuspend" command - */ -static const vshCmdInfo info_nodesuspend[] = { - {"help", N_("suspend the host node for a given time duration")}, - {"desc", N_("Suspend the host node for a given time duration " - "and attempt to resume thereafter.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_suspend[] = { - {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), " - "disk(Suspend-to-Disk), hybrid(Hybrid-Suspend)")}, - {"duration", VSH_OT_INT, VSH_OFLAG_REQ, N_("Suspend duration in seconds")}, - {"flags", VSH_OT_INT, VSH_OFLAG_NONE, N_("Suspend flags, 0 for default")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd) -{ - const char *target = NULL; - unsigned int suspendTarget; - long long duration; - unsigned int flags = 0; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "target", &target) < 0) { - vshError(ctl, _("Invalid target argument")); - return false; - } - - if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) { - vshError(ctl, _("Invalid duration argument")); - return false; - } - - if (vshCommandOptUInt(cmd, "flags", &flags) < 0) { - vshError(ctl, _("Invalid flags argument")); - return false; - } - - if (STREQ(target, "mem")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM; - else if (STREQ(target, "disk")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK; - else if (STREQ(target, "hybrid")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID; - else { - vshError(ctl, "%s", _("Invalid target")); - return false; - } - - if (duration <= 0) { - vshError(ctl, "%s", _("Invalid duration")); - return false; - } - - if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration, - flags) < 0) { - vshError(ctl, "%s", _("The host was not suspended")); - return false; - } - return true; -} - - -/* - * "capabilities" command - */ -static const vshCmdInfo info_capabilities[] = { - {"help", N_("capabilities")}, - {"desc", N_("Returns capabilities of hypervisor/driver.")}, - {NULL, NULL} -}; - -static bool -cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - char *caps; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if ((caps = virConnectGetCapabilities(ctl->conn)) == NULL) { - vshError(ctl, "%s", _("failed to get capabilities")); - return false; - } - vshPrint(ctl, "%s\n", caps); - VIR_FREE(caps); - - return true; -} - -/* - * "iface-edit" command - */ -static const vshCmdInfo info_interface_edit[] = { - {"help", N_("edit XML configuration for a physical host interface")}, - {"desc", N_("Edit the XML configuration for a physical host interface.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_edit[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceEdit(vshControl *ctl, const vshCmd *cmd) -{ - bool ret = false; - virInterfacePtr iface = NULL; - virInterfacePtr iface_edited = NULL; - unsigned int flags = VIR_INTERFACE_XML_INACTIVE; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - iface = vshCommandOptInterface(ctl, cmd, NULL); - if (iface == NULL) - goto cleanup; - -#define EDIT_GET_XML virInterfaceGetXMLDesc(iface, flags) -#define EDIT_NOT_CHANGED \ - vshPrint(ctl, _("Interface %s XML configuration not changed.\n"), \ - virInterfaceGetName(iface)); \ - ret = true; goto edit_cleanup; -#define EDIT_DEFINE \ - (iface_edited = virInterfaceDefineXML(ctl->conn, doc_edited, 0)) -#define EDIT_FREE \ - if (iface_edited) \ - virInterfaceFree(iface_edited); -#include "virsh-edit.c" - - vshPrint(ctl, _("Interface %s XML configuration edited.\n"), - virInterfaceGetName(iface_edited)); - - ret = true; - -cleanup: - if (iface) - virInterfaceFree(iface); - if (iface_edited) - virInterfaceFree(iface_edited); - - return ret; -} - -/**************************************************************************/ -/* - * "iface-list" command - */ -static const vshCmdInfo info_interface_list[] = { - {"help", N_("list physical host interfaces")}, - {"desc", N_("Returns list of physical host interfaces.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_list[] = { - {"inactive", VSH_OT_BOOL, 0, N_("list inactive interfaces")}, - {"all", VSH_OT_BOOL, 0, N_("list inactive & active interfaces")}, - {NULL, 0, 0, NULL} -}; -static bool -cmdInterfaceList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - bool inactive = vshCommandOptBool(cmd, "inactive"); - bool all = vshCommandOptBool(cmd, "all"); - bool active = !inactive || all; - int maxactive = 0, maxinactive = 0, i; - char **activeNames = NULL, **inactiveNames = NULL; - inactive |= all; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (active) { - maxactive = virConnectNumOfInterfaces(ctl->conn); - if (maxactive < 0) { - vshError(ctl, "%s", _("Failed to list active interfaces")); - return false; - } - if (maxactive) { - activeNames = vshMalloc(ctl, sizeof(char *) * maxactive); - - if ((maxactive = virConnectListInterfaces(ctl->conn, activeNames, - maxactive)) < 0) { - vshError(ctl, "%s", _("Failed to list active interfaces")); - VIR_FREE(activeNames); - return false; - } - - qsort(&activeNames[0], maxactive, sizeof(char *), vshNameSorter); - } - } - if (inactive) { - maxinactive = virConnectNumOfDefinedInterfaces(ctl->conn); - if (maxinactive < 0) { - vshError(ctl, "%s", _("Failed to list inactive interfaces")); - VIR_FREE(activeNames); - return false; - } - if (maxinactive) { - inactiveNames = vshMalloc(ctl, sizeof(char *) * maxinactive); - - if ((maxinactive = - virConnectListDefinedInterfaces(ctl->conn, inactiveNames, - maxinactive)) < 0) { - vshError(ctl, "%s", _("Failed to list inactive interfaces")); - VIR_FREE(activeNames); - VIR_FREE(inactiveNames); - return false; - } - - qsort(&inactiveNames[0], maxinactive, sizeof(char*), vshNameSorter); - } - } - vshPrintExtra(ctl, "%-20s %-10s %s\n", _("Name"), _("State"), - _("MAC Address")); - vshPrintExtra(ctl, "--------------------------------------------\n"); - - for (i = 0; i < maxactive; i++) { - virInterfacePtr iface = - virInterfaceLookupByName(ctl->conn, activeNames[i]); - - /* this kind of work with interfaces is not atomic */ - if (!iface) { - VIR_FREE(activeNames[i]); - continue; - } - - vshPrint(ctl, "%-20s %-10s %s\n", - virInterfaceGetName(iface), - _("active"), - virInterfaceGetMACString(iface)); - virInterfaceFree(iface); - VIR_FREE(activeNames[i]); - } - for (i = 0; i < maxinactive; i++) { - virInterfacePtr iface = - virInterfaceLookupByName(ctl->conn, inactiveNames[i]); - - /* this kind of work with interfaces is not atomic */ - if (!iface) { - VIR_FREE(inactiveNames[i]); - continue; - } - - vshPrint(ctl, "%-20s %-10s %s\n", - virInterfaceGetName(iface), - _("inactive"), - virInterfaceGetMACString(iface)); - virInterfaceFree(iface); - VIR_FREE(inactiveNames[i]); - } - VIR_FREE(activeNames); - VIR_FREE(inactiveNames); - return true; - -} - -/* - * "iface-name" command - */ -static const vshCmdInfo info_interface_name[] = { - {"help", N_("convert an interface MAC address to interface name")}, - {"desc", ""}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_name[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface mac")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceName(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL, - VSH_BYMAC))) - return false; - - vshPrint(ctl, "%s\n", virInterfaceGetName(iface)); - virInterfaceFree(iface); - return true; -} - -/* - * "iface-mac" command - */ -static const vshCmdInfo info_interface_mac[] = { - {"help", N_("convert an interface name to interface MAC address")}, - {"desc", ""}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_mac[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceMAC(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (!(iface = vshCommandOptInterfaceBy(ctl, cmd, NULL, NULL, - VSH_BYNAME))) - return false; - - vshPrint(ctl, "%s\n", virInterfaceGetMACString(iface)); - virInterfaceFree(iface); - return true; -} - -/* - * "iface-dumpxml" command - */ -static const vshCmdInfo info_interface_dumpxml[] = { - {"help", N_("interface information in XML")}, - {"desc", N_("Output the physical host interface information as an XML dump to stdout.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_dumpxml[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, - {"inactive", VSH_OT_BOOL, 0, N_("show inactive defined XML")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - bool ret = true; - char *dump; - unsigned int flags = 0; - bool inactive = vshCommandOptBool(cmd, "inactive"); - - if (inactive) - flags |= VIR_INTERFACE_XML_INACTIVE; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(iface = vshCommandOptInterface(ctl, cmd, NULL))) - return false; - - dump = virInterfaceGetXMLDesc(iface, flags); - if (dump != NULL) { - vshPrint(ctl, "%s", dump); - VIR_FREE(dump); - } else { - ret = false; - } - - virInterfaceFree(iface); - return ret; -} - -/* - * "iface-define" command - */ -static const vshCmdInfo info_interface_define[] = { - {"help", N_("define (but don't start) a physical host interface from an XML file")}, - {"desc", N_("Define a physical host interface.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_define[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML interface description")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceDefine(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - const char *from = NULL; - bool ret = true; - char *buffer; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - iface = virInterfaceDefineXML(ctl->conn, buffer, 0); - VIR_FREE(buffer); - - if (iface != NULL) { - vshPrint(ctl, _("Interface %s defined from %s\n"), - virInterfaceGetName(iface), from); - virInterfaceFree(iface); - } else { - vshError(ctl, _("Failed to define interface from %s"), from); - ret = false; - } - return ret; -} - -/* - * "iface-undefine" command - */ -static const vshCmdInfo info_interface_undefine[] = { - {"help", N_("undefine a physical host interface (remove it from configuration)")}, - {"desc", N_("undefine an interface.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_undefine[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceUndefine(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) - return false; - - if (virInterfaceUndefine(iface) == 0) { - vshPrint(ctl, _("Interface %s undefined\n"), name); - } else { - vshError(ctl, _("Failed to undefine interface %s"), name); - ret = false; - } - - virInterfaceFree(iface); - return ret; -} - -/* - * "iface-start" command - */ -static const vshCmdInfo info_interface_start[] = { - {"help", N_("start a physical host interface (enable it / \"if-up\")")}, - {"desc", N_("start a physical host interface.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_start[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceStart(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) - return false; - - if (virInterfaceCreate(iface, 0) == 0) { - vshPrint(ctl, _("Interface %s started\n"), name); - } else { - vshError(ctl, _("Failed to start interface %s"), name); - ret = false; - } - - virInterfaceFree(iface); - return ret; -} - -/* - * "iface-destroy" command - */ -static const vshCmdInfo info_interface_destroy[] = { - {"help", N_("destroy a physical host interface (disable it / \"if-down\")")}, - {"desc", N_("forcefully stop a physical host interface.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_destroy[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("interface name or MAC address")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceDestroy(vshControl *ctl, const vshCmd *cmd) -{ - virInterfacePtr iface; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(iface = vshCommandOptInterface(ctl, cmd, &name))) - return false; - - if (virInterfaceDestroy(iface, 0) == 0) { - vshPrint(ctl, _("Interface %s destroyed\n"), name); - } else { - vshError(ctl, _("Failed to destroy interface %s"), name); - ret = false; - } - - virInterfaceFree(iface); - return ret; -} - -/* - * "iface-begin" command - */ -static const vshCmdInfo info_interface_begin[] = { - {"help", N_("create a snapshot of current interfaces settings, " - "which can be later committed (iface-commit) or " - "restored (iface-rollback)")}, - {"desc", N_("Create a restore point for interfaces settings")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_begin[] = { - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceBegin(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (virInterfaceChangeBegin(ctl->conn, 0) < 0) { - vshError(ctl, "%s", _("Failed to begin network config change transaction")); - return false; - } - - vshPrint(ctl, "%s", _("Network config change transaction started\n")); - return true; -} - -/* - * "iface-commit" command - */ -static const vshCmdInfo info_interface_commit[] = { - {"help", N_("commit changes made since iface-begin and free restore point")}, - {"desc", N_("commit changes and free restore point")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_commit[] = { - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceCommit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (virInterfaceChangeCommit(ctl->conn, 0) < 0) { - vshError(ctl, "%s", _("Failed to commit network config change transaction")); - return false; - } - - vshPrint(ctl, "%s", _("Network config change transaction committed\n")); - return true; -} - -/* - * "iface-rollback" command - */ -static const vshCmdInfo info_interface_rollback[] = { - {"help", N_("rollback to previous saved configuration created via iface-begin")}, - {"desc", N_("rollback to previous restore point")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_rollback[] = { - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceRollback(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (virInterfaceChangeRollback(ctl->conn, 0) < 0) { - vshError(ctl, "%s", _("Failed to rollback network config change transaction")); - return false; - } - - vshPrint(ctl, "%s", _("Network config change transaction rolled back\n")); - return true; -} - -/* - * "iface-bridge" command - */ -static const vshCmdInfo info_interface_bridge[] = { - {"help", N_("create a bridge device and attach an existing network device to it")}, - {"desc", N_("bridge an existing network device")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_interface_bridge[] = { - {"interface", VSH_OT_DATA, VSH_OFLAG_REQ, N_("existing interface name")}, - {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("new bridge device name")}, - {"no-stp", VSH_OT_BOOL, 0, N_("do not enable STP for this bridge")}, - {"delay", VSH_OT_INT, 0, - N_("number of seconds to squelch traffic on newly connected ports")}, - {"no-start", VSH_OT_BOOL, 0, N_("don't start the bridge immediately")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdInterfaceBridge(vshControl *ctl, const vshCmd *cmd) -{ - bool ret = false; - virInterfacePtr if_handle = NULL, br_handle = NULL; - const char *if_name, *br_name; - char *if_type = NULL, *if2_name = NULL, *delay_str = NULL; - bool stp = false, nostart = false; - unsigned int delay = 0; - char *if_xml = NULL; - xmlChar *br_xml = NULL; - int br_xml_size; - xmlDocPtr xml_doc = NULL; - xmlXPathContextPtr ctxt = NULL; - xmlNodePtr top_node, br_node, if_node, cur; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - /* Get a handle to the original device */ - if (!(if_handle = vshCommandOptInterfaceBy(ctl, cmd, "interface", - &if_name, VSH_BYNAME))) { - goto cleanup; - } - - /* Name for new bridge device */ - if (vshCommandOptString(cmd, "bridge", &br_name) <= 0) { - vshError(ctl, "%s", _("Missing bridge device name in command")); - goto cleanup; - } - - /* make sure "new" device doesn't already exist */ - if ((br_handle = virInterfaceLookupByName(ctl->conn, br_name))) { - vshError(ctl, _("Network device %s already exists"), br_name); - goto cleanup; - } - - /* use "no-stp" because we want "stp" to default true */ - stp = !vshCommandOptBool(cmd, "no-stp"); - - if (vshCommandOptUInt(cmd, "delay", &delay) < 0) { - vshError(ctl, "%s", _("Unable to parse delay parameter")); - goto cleanup; - } - - nostart = vshCommandOptBool(cmd, "no-start"); - - /* Get the original interface into an xmlDoc */ - if (!(if_xml = virInterfaceGetXMLDesc(if_handle, VIR_INTERFACE_XML_INACTIVE))) - goto cleanup; - if (!(xml_doc = virXMLParseStringCtxt(if_xml, - _("(interface definition)"), &ctxt))) { - vshError(ctl, _("Failed to parse configuration of %s"), if_name); - goto cleanup; - } - top_node = ctxt->node; - - /* Verify that the original device isn't already a bridge. */ - if (!(if_type = virXMLPropString(top_node, "type"))) { - vshError(ctl, _("Existing device %s has no type"), if_name); - goto cleanup; - } - - if (STREQ(if_type, "bridge")) { - vshError(ctl, _("Existing device %s is already a bridge"), if_name); - goto cleanup; - } - - /* verify the name in the XML matches the device name */ - if (!(if2_name = virXMLPropString(top_node, "name")) || - STRNEQ(if2_name, if_name)) { - vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"), - if2_name, if_name); - goto cleanup; - } - - /* Create a <bridge> node under <interface>. */ - if (!(br_node = xmlNewChild(top_node, NULL, BAD_CAST "bridge", NULL))) { - vshError(ctl, "%s", _("Failed to create bridge node in xml document")); - goto cleanup; - } - - /* Set stp and delay attributes in <bridge> according to the - * commandline options. - */ - if (!xmlSetProp(br_node, BAD_CAST "stp", BAD_CAST (stp ? "on" : "off"))) { - vshError(ctl, "%s", _("Failed to set stp attribute in xml document")); - goto cleanup; - } - - if ((delay || stp) && - ((virAsprintf(&delay_str, "%d", delay) < 0) || - !xmlSetProp(br_node, BAD_CAST "delay", BAD_CAST delay_str))) { - vshError(ctl, _("Failed to set bridge delay %d in xml document"), delay); - goto cleanup; - } - - /* Change the type of the outer/master interface to "bridge" and the - * name to the provided bridge name. - */ - if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST "bridge")) { - vshError(ctl, "%s", _("Failed to set bridge interface type to 'bridge' in xml document")); - goto cleanup; + return false; } - if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST br_name)) { - vshError(ctl, _("Failed to set master bridge interface name to '%s' in xml document"), - br_name); - goto cleanup; + if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) { + vshError(ctl, "%s", + _("Unable to get number of cpu stats")); + return false; } - - /* Create an <interface> node under <bridge> that uses the - * original interface's type and name. - */ - if (!(if_node = xmlNewChild(br_node, NULL, BAD_CAST "interface", NULL))) { - vshError(ctl, "%s", _("Failed to create interface node under bridge node in xml document")); - goto cleanup; + if (nparams == 0) { + /* nothing to output */ + return true; } - /* set the type of the inner/slave interface to the original - * if_type, and the name to the original if_name. - */ - if (!xmlSetProp(if_node, BAD_CAST "type", BAD_CAST if_type)) { - vshError(ctl, _("Failed to set new slave interface type to '%s' in xml document"), - if_name); - goto cleanup; - } + memset(cpu_stats, 0, sizeof(cpu_stats)); + params = vshCalloc(ctl, nparams, sizeof(*params)); - if (!xmlSetProp(if_node, BAD_CAST "name", BAD_CAST if_name)) { - vshError(ctl, _("Failed to set new slave interface name to '%s' in xml document"), - br_name); - goto cleanup; - } + for (i = 0; i < 2; i++) { + if (i > 0) + sleep(1); - /* Cycle through all the nodes under the original <interface>, - * moving all <mac>, <bond> and <vlan> nodes down into the new - * lower level <interface>. - */ - cur = top_node->children; - while (cur) { - xmlNodePtr old = cur; - - cur = cur->next; - if ((old->type == XML_ELEMENT_NODE) && - (xmlStrEqual(old->name, BAD_CAST "mac") || /* ethernet stuff to move down */ - xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */ - xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */ - xmlUnlinkNode(old); - if (!xmlAddChild(if_node, old)) { - vshError(ctl, _("Failed to move '%s' element in xml document"), old->name); - xmlFreeNode(old); - goto cleanup; - } + if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) { + vshError(ctl, "%s", _("Unable to get node cpu stats")); + goto cleanup; } - } - /* The document should now be fully converted; write it out to a string. */ - xmlDocDumpMemory(xml_doc, &br_xml, &br_xml_size); + for (j = 0; j < nparams; j++) { + unsigned long long value = params[j].value; - if (!br_xml || br_xml_size <= 0) { - vshError(ctl, _("Failed to format new xml document for bridge %s"), br_name); - goto cleanup; + if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) { + cpu_stats[i].sys = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) { + cpu_stats[i].user = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) { + cpu_stats[i].idle = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) { + cpu_stats[i].iowait = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) { + cpu_stats[i].util = value; + flag_utilization = true; + } + } + + if (flag_utilization || !flag_percent) + break; } + if (!flag_percent) { + if (!flag_utilization) { + vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user); + vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys); + vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle); + vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait); + } + } else { + if (flag_utilization) { + usage = cpu_stats[0].util; - /* br_xml is the new interface to define. It will automatically undefine the - * independent original interface. - */ - if (!(br_handle = virInterfaceDefineXML(ctl->conn, (char *) br_xml, 0))) { - vshError(ctl, _("Failed to define new bridge interface %s"), - br_name); - goto cleanup; - } + vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage); + vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage); + } else { + user_time = cpu_stats[1].user - cpu_stats[0].user; + sys_time = cpu_stats[1].sys - cpu_stats[0].sys; + idle_time = cpu_stats[1].idle - cpu_stats[0].idle; + iowait_time = cpu_stats[1].iowait - cpu_stats[0].iowait; + total_time = user_time + sys_time + idle_time + iowait_time; - vshPrint(ctl, _("Created bridge %s with attached device %s\n"), - br_name, if_name); + usage = (user_time + sys_time) / total_time * 100; - /* start it up unless requested not to */ - if (!nostart) { - if (virInterfaceCreate(br_handle, 0) < 0) { - vshError(ctl, _("Failed to start bridge interface %s"), br_name); - goto cleanup; + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("usage:"), usage); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("user:"), user_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("system:"), sys_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("idle:"), idle_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("iowait:"), iowait_time / total_time * 100); } - vshPrint(ctl, _("Bridge interface %s started\n"), br_name); } ret = true; - cleanup: - if (if_handle) - virInterfaceFree(if_handle); - if (br_handle) - virInterfaceFree(br_handle); - VIR_FREE(if_xml); - VIR_FREE(br_xml); - VIR_FREE(if_type); - VIR_FREE(if2_name); - VIR_FREE(delay_str); - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml_doc); + + cleanup: + VIR_FREE(params); return ret; } /* - * "iface-unbridge" command + * "nodememstats" command */ -static const vshCmdInfo info_interface_unbridge[] = { - {"help", N_("undefine a bridge device after detaching its slave device")}, - {"desc", N_("unbridge a network device")}, +static const vshCmdInfo info_nodememstats[] = { + {"help", N_("Prints memory stats of the node.")}, + {"desc", N_("Returns memory stats of the node, in kilobytes.")}, {NULL, NULL} }; -static const vshCmdOptDef opts_interface_unbridge[] = { - {"bridge", VSH_OT_DATA, VSH_OFLAG_REQ, N_("current bridge device name")}, - {"no-start", VSH_OT_BOOL, 0, - N_("don't start the un-slaved interface immediately (not recommended)")}, +static const vshCmdOptDef opts_node_memstats[] = { + {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")}, {NULL, 0, 0, NULL} }; static bool -cmdInterfaceUnbridge(vshControl *ctl, const vshCmd *cmd) +cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd) { + int nparams = 0; + unsigned int i = 0; + int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS; + virNodeMemoryStatsPtr params = NULL; bool ret = false; - virInterfacePtr if_handle = NULL, br_handle = NULL; - const char *br_name; - char *if_type = NULL, *if_name = NULL; - bool nostart = false; - char *br_xml = NULL; - xmlChar *if_xml = NULL; - int if_xml_size; - xmlDocPtr xml_doc = NULL; - xmlXPathContextPtr ctxt = NULL; - xmlNodePtr top_node, br_node, if_node, cur; if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; + return false; - /* Get a handle to the original device */ - if (!(br_handle = vshCommandOptInterfaceBy(ctl, cmd, "bridge", - &br_name, VSH_BYNAME))) { - goto cleanup; + if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) { + vshError(ctl, "%s", _("Invalid value of cellNum")); + return false; } - nostart = vshCommandOptBool(cmd, "no-start"); - - /* Get the bridge xml into an xmlDoc */ - if (!(br_xml = virInterfaceGetXMLDesc(br_handle, VIR_INTERFACE_XML_INACTIVE))) - goto cleanup; - if (!(xml_doc = virXMLParseStringCtxt(br_xml, - _("(bridge interface definition)"), - &ctxt))) { - vshError(ctl, _("Failed to parse configuration of %s"), br_name); + /* get the number of memory parameters */ + if (virNodeGetMemoryStats(ctl->conn, cellNum, NULL, &nparams, 0) != 0) { + vshError(ctl, "%s", + _("Unable to get number of memory stats")); goto cleanup; } - top_node = ctxt->node; - /* Verify that the device really is a bridge. */ - if (!(if_type = virXMLPropString(top_node, "type"))) { - vshError(ctl, _("Existing device %s has no type"), br_name); + if (nparams == 0) { + /* nothing to output */ + ret = true; goto cleanup; } - if (STRNEQ(if_type, "bridge")) { - vshError(ctl, _("Device %s is not a bridge"), br_name); + /* now go get all the memory parameters */ + params = vshCalloc(ctl, nparams, sizeof(*params)); + if (virNodeGetMemoryStats(ctl->conn, cellNum, params, &nparams, 0) != 0) { + vshError(ctl, "%s", _("Unable to get memory stats")); goto cleanup; } - VIR_FREE(if_type); - /* verify the name in the XML matches the device name */ - if (!(if_name = virXMLPropString(top_node, "name")) || - STRNEQ(if_name, br_name)) { - vshError(ctl, _("Interface name from config %s doesn't match given supplied name %s"), - if_name, br_name); - goto cleanup; - } - VIR_FREE(if_name); + for (i = 0; i < nparams; i++) + vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value); - /* Find the <bridge> node under <interface>. */ - if (!(br_node = virXPathNode("./bridge", ctxt))) { - vshError(ctl, "%s", _("No bridge node in xml document")); - goto cleanup; - } + ret = true; - if ((if_node = virXPathNode("./bridge/interface[2]", ctxt))) { - vshError(ctl, "%s", _("Multiple interfaces attached to bridge")); - goto cleanup; - } + cleanup: + VIR_FREE(params); + return ret; +} - if (!(if_node = virXPathNode("./bridge/interface", ctxt))) { - vshError(ctl, "%s", _("No interface attached to bridge")); - goto cleanup; - } +/* + * "nodesuspend" command + */ +static const vshCmdInfo info_nodesuspend[] = { + {"help", N_("suspend the host node for a given time duration")}, + {"desc", N_("Suspend the host node for a given time duration " + "and attempt to resume thereafter.")}, + {NULL, NULL} +}; - /* Change the type and name of the outer/master interface to - * the type/name of the attached slave interface. - */ - if (!(if_name = virXMLPropString(if_node, "name"))) { - vshError(ctl, _("Device attached to bridge %s has no name"), br_name); - goto cleanup; - } +static const vshCmdOptDef opts_node_suspend[] = { + {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), " + "disk(Suspend-to-Disk), hybrid(Hybrid-Suspend)")}, + {"duration", VSH_OT_INT, VSH_OFLAG_REQ, N_("Suspend duration in seconds")}, + {"flags", VSH_OT_INT, VSH_OFLAG_NONE, N_("Suspend flags, 0 for default")}, + {NULL, 0, 0, NULL} +}; - if (!(if_type = virXMLPropString(if_node, "type"))) { - vshError(ctl, _("Attached device %s has no type"), if_name); - goto cleanup; - } +static bool +cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd) +{ + const char *target = NULL; + unsigned int suspendTarget; + long long duration; + unsigned int flags = 0; - if (!xmlSetProp(top_node, BAD_CAST "type", BAD_CAST if_type)) { - vshError(ctl, _("Failed to set interface type to '%s' in xml document"), - if_type); - goto cleanup; - } + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; - if (!xmlSetProp(top_node, BAD_CAST "name", BAD_CAST if_name)) { - vshError(ctl, _("Failed to set interface name to '%s' in xml document"), - if_name); - goto cleanup; + if (vshCommandOptString(cmd, "target", &target) < 0) { + vshError(ctl, _("Invalid target argument")); + return false; } - /* Cycle through all the nodes under the attached <interface>, - * moving all <mac>, <bond> and <vlan> nodes up into the toplevel - * <interface>. - */ - cur = if_node->children; - while (cur) { - xmlNodePtr old = cur; - - cur = cur->next; - if ((old->type == XML_ELEMENT_NODE) && - (xmlStrEqual(old->name, BAD_CAST "mac") || /* ethernet stuff to move down */ - xmlStrEqual(old->name, BAD_CAST "bond") || /* bond stuff to move down */ - xmlStrEqual(old->name, BAD_CAST "vlan"))) { /* vlan stuff to move down */ - xmlUnlinkNode(old); - if (!xmlAddChild(top_node, old)) { - vshError(ctl, _("Failed to move '%s' element in xml document"), old->name); - xmlFreeNode(old); - goto cleanup; - } - } + if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) { + vshError(ctl, _("Invalid duration argument")); + return false; } - /* The document should now be fully converted; write it out to a string. */ - xmlDocDumpMemory(xml_doc, &if_xml, &if_xml_size); - - if (!if_xml || if_xml_size <= 0) { - vshError(ctl, _("Failed to format new xml document for un-enslaved interface %s"), - if_name); - goto cleanup; + if (vshCommandOptUInt(cmd, "flags", &flags) < 0) { + vshError(ctl, _("Invalid flags argument")); + return false; } - /* Destroy and Undefine the bridge device, since we otherwise - * can't safely define the unattached device. - */ - if (virInterfaceDestroy(br_handle, 0) < 0) { - vshError(ctl, _("Failed to destroy bridge interface %s"), br_name); - goto cleanup; + if (STREQ(target, "mem")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM; + else if (STREQ(target, "disk")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK; + else if (STREQ(target, "hybrid")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID; + else { + vshError(ctl, "%s", _("Invalid target")); + return false; } - if (virInterfaceUndefine(br_handle) < 0) { - vshError(ctl, _("Failed to undefine bridge interface %s"), br_name); - goto cleanup; + + if (duration <= 0) { + vshError(ctl, "%s", _("Invalid duration")); + return false; } - /* if_xml is the new interface to define. - */ - if (!(if_handle = virInterfaceDefineXML(ctl->conn, (char *) if_xml, 0))) { - vshError(ctl, _("Failed to define new interface %s"), if_name); - goto cleanup; + if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration, + flags) < 0) { + vshError(ctl, "%s", _("The host was not suspended")); + return false; } + return true; +} - vshPrint(ctl, _("Device %s un-attached from bridge %s\n"), - if_name, br_name); - /* unless requested otherwise, undefine the bridge device */ - if (!nostart) { - if (virInterfaceCreate(if_handle, 0) < 0) { - vshError(ctl, _("Failed to start interface %s"), if_name); - goto cleanup; - } - vshPrint(ctl, _("Interface %s started\n"), if_name); +/* + * "capabilities" command + */ +static const vshCmdInfo info_capabilities[] = { + {"help", N_("capabilities")}, + {"desc", N_("Returns capabilities of hypervisor/driver.")}, + {NULL, NULL} +}; + +static bool +cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + char *caps; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if ((caps = virConnectGetCapabilities(ctl->conn)) == NULL) { + vshError(ctl, "%s", _("failed to get capabilities")); + return false; } + vshPrint(ctl, "%s\n", caps); + VIR_FREE(caps); - ret = true; - cleanup: - if (if_handle) - virInterfaceFree(if_handle); - if (br_handle) - virInterfaceFree(br_handle); - VIR_FREE(if_xml); - VIR_FREE(br_xml); - VIR_FREE(if_type); - VIR_FREE(if_name); - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml_doc); - return ret; + return true; } /* @@ -6118,47 +5173,6 @@ vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, return nwfilter; } -static virInterfacePtr -vshCommandOptInterfaceBy(vshControl *ctl, const vshCmd *cmd, - const char *optname, - const char **name, int flag) -{ - virInterfacePtr iface = NULL; - const char *n = NULL; - - if (!optname) - optname = "interface"; - if (!cmd_has_option(ctl, cmd, optname)) - return NULL; - - if (vshCommandOptString(cmd, optname, &n) <= 0) - return NULL; - - vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", - cmd->def->name, optname, n); - - if (name) - *name = n; - - /* try it by NAME */ - if (flag & VSH_BYNAME) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface NAME\n", - cmd->def->name, optname); - iface = virInterfaceLookupByName(ctl->conn, n); - } - /* try it by MAC */ - if (iface == NULL && (flag & VSH_BYMAC)) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as interface MAC\n", - cmd->def->name, optname); - iface = virInterfaceLookupByMACString(ctl->conn, n); - } - - if (!iface) - vshError(ctl, _("failed to get interface '%s'"), n); - - return iface; -} - static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name) { @@ -7722,6 +6736,8 @@ static const vshCmdDef nodedevCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-interface.c" + static const vshCmdDef ifaceCmds[] = { {"iface-begin", cmdInterfaceBegin, opts_interface_begin, info_interface_begin, 0}, -- 1.7.7.3

Commands to manage network filter are moved from virsh.c to virsh-nwfilter.c, with a few helpers for network filter command use. * virsh.c: Remove network filter commands and a few helpers. * virsh-nwfilter.c: New file, filled with network filter commands and its helpers. --- tools/virsh-nwfilter.c | 310 ++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 294 +--------------------------------------------- 2 files changed, 312 insertions(+), 292 deletions(-) create mode 100644 tools/virsh-nwfilter.c diff --git a/tools/virsh-nwfilter.c b/tools/virsh-nwfilter.c new file mode 100644 index 0000000..4b4996a --- /dev/null +++ b/tools/virsh-nwfilter.c @@ -0,0 +1,310 @@ +/* + * virsh-domain.c: Commands to manage network filters + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* default is lookup by Name and UUID */ +#define vshCommandOptNWFilter(_ctl, _cmd, _name) \ + vshCommandOptNWFilterBy(_ctl, _cmd, _name, \ + VSH_BYUUID|VSH_BYNAME) + +static virNWFilterPtr +vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, + const char **name, int flag) +{ + virNWFilterPtr nwfilter = NULL; + const char *n = NULL; + const char *optname = "nwfilter"; + if (!cmd_has_option(ctl, cmd, optname)) + return NULL; + + if (vshCommandOptString(cmd, optname, &n) <= 0) + return NULL; + + vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", + cmd->def->name, optname, n); + + if (name) + *name = n; + + /* try it by UUID */ + if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter UUID\n", + cmd->def->name, optname); + nwfilter = virNWFilterLookupByUUIDString(ctl->conn, n); + } + /* try it by NAME */ + if (nwfilter == NULL && (flag & VSH_BYNAME)) { + vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter NAME\n", + cmd->def->name, optname); + nwfilter = virNWFilterLookupByName(ctl->conn, n); + } + + if (!nwfilter) + vshError(ctl, _("failed to get nwfilter '%s'"), n); + + return nwfilter; +} + +/* + * "nwfilter-define" command + */ +static const vshCmdInfo info_nwfilter_define[] = { + {"help", N_("define or update a network filter from an XML file")}, + {"desc", N_("Define a new network filter or update an existing one.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_nwfilter_define[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network filter description")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNWFilterDefine(vshControl *ctl, const vshCmd *cmd) +{ + virNWFilterPtr nwfilter; + const char *from = NULL; + bool ret = true; + char *buffer; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + nwfilter = virNWFilterDefineXML(ctl->conn, buffer); + VIR_FREE(buffer); + + if (nwfilter != NULL) { + vshPrint(ctl, _("Network filter %s defined from %s\n"), + virNWFilterGetName(nwfilter), from); + virNWFilterFree(nwfilter); + } else { + vshError(ctl, _("Failed to define network filter from %s"), from); + ret = false; + } + return ret; +} + +/* + * "nwfilter-undefine" command + */ +static const vshCmdInfo info_nwfilter_undefine[] = { + {"help", N_("undefine a network filter")}, + {"desc", N_("Undefine a given network filter.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_nwfilter_undefine[] = { + {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNWFilterUndefine(vshControl *ctl, const vshCmd *cmd) +{ + virNWFilterPtr nwfilter; + bool ret = true; + const char *name; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, &name))) + return false; + + if (virNWFilterUndefine(nwfilter) == 0) { + vshPrint(ctl, _("Network filter %s undefined\n"), name); + } else { + vshError(ctl, _("Failed to undefine network filter %s"), name); + ret = false; + } + + virNWFilterFree(nwfilter); + return ret; +} + +/* + * "nwfilter-dumpxml" command + */ +static const vshCmdInfo info_nwfilter_dumpxml[] = { + {"help", N_("network filter information in XML")}, + {"desc", N_("Output the network filter information as an XML dump to stdout.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_nwfilter_dumpxml[] = { + {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNWFilterDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + virNWFilterPtr nwfilter; + bool ret = true; + char *dump; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL))) + return false; + + dump = virNWFilterGetXMLDesc(nwfilter, 0); + if (dump != NULL) { + vshPrint(ctl, "%s", dump); + VIR_FREE(dump); + } else { + ret = false; + } + + virNWFilterFree(nwfilter); + return ret; +} + +/* + * "nwfilter-list" command + */ +static const vshCmdInfo info_nwfilter_list[] = { + {"help", N_("list network filters")}, + {"desc", N_("Returns list of network filters.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_nwfilter_list[] = { + {NULL, 0, 0, NULL} +}; + +static bool +cmdNWFilterList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + int numfilters, i; + char **names; + char uuid[VIR_UUID_STRING_BUFLEN]; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + numfilters = virConnectNumOfNWFilters(ctl->conn); + if (numfilters < 0) { + vshError(ctl, "%s", _("Failed to list network filters")); + return false; + } + + names = vshMalloc(ctl, sizeof(char *) * numfilters); + + if ((numfilters = virConnectListNWFilters(ctl->conn, names, + numfilters)) < 0) { + vshError(ctl, "%s", _("Failed to list network filters")); + VIR_FREE(names); + return false; + } + + qsort(&names[0], numfilters, sizeof(char *), vshNameSorter); + + vshPrintExtra(ctl, "%-36s %-20s \n", _("UUID"), _("Name")); + vshPrintExtra(ctl, + "----------------------------------------------------------------\n"); + + for (i = 0; i < numfilters; i++) { + virNWFilterPtr nwfilter = + virNWFilterLookupByName(ctl->conn, names[i]); + + /* this kind of work with networks is not atomic operation */ + if (!nwfilter) { + VIR_FREE(names[i]); + continue; + } + + virNWFilterGetUUIDString(nwfilter, uuid); + vshPrint(ctl, "%-36s %-20s\n", + uuid, + virNWFilterGetName(nwfilter)); + virNWFilterFree(nwfilter); + VIR_FREE(names[i]); + } + + VIR_FREE(names); + return true; +} + +/* + * "nwfilter-edit" command + */ +static const vshCmdInfo info_nwfilter_edit[] = { + {"help", N_("edit XML configuration for a network filter")}, + {"desc", N_("Edit the XML configuration for a network filter.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_nwfilter_edit[] = { + {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNWFilterEdit(vshControl *ctl, const vshCmd *cmd) +{ + bool ret = false; + virNWFilterPtr nwfilter = NULL; + virNWFilterPtr nwfilter_edited = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL); + if (nwfilter == NULL) + goto cleanup; + +#define EDIT_GET_XML virNWFilterGetXMLDesc(nwfilter, 0) +#define EDIT_NOT_CHANGED \ + vshPrint(ctl, _("Network filter %s XML " \ + "configuration not changed.\n"), \ + virNWFilterGetName(nwfilter)); \ + ret = true; goto edit_cleanup; +#define EDIT_DEFINE \ + (nwfilter_edited = virNWFilterDefineXML(ctl->conn, doc_edited)) +#define EDIT_FREE \ + if (nwfilter_edited) \ + virNWFilterFree(nwfilter); +#include "virsh-edit.c" + + vshPrint(ctl, _("Network filter %s XML configuration edited.\n"), + virNWFilterGetName(nwfilter_edited)); + + ret = true; + +cleanup: + if (nwfilter) + virNWFilterFree(nwfilter); + if (nwfilter_edited) + virNWFilterFree(nwfilter_edited); + + return ret; +} diff --git a/tools/virsh.c b/tools/virsh.c index 23b2ec9..4844e31 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -339,14 +339,6 @@ static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, #define vshCommandOptDomain(_ctl, _cmd, _name) \ vshCommandOptDomainBy(_ctl, _cmd, _name, VSH_BYID|VSH_BYUUID|VSH_BYNAME) -static virNWFilterPtr vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, - const char **name, int flag); - -/* default is lookup by Name and UUID */ -#define vshCommandOptNWFilter(_ctl, _cmd, _name) \ - vshCommandOptNWFilterBy(_ctl, _cmd, _name, \ - VSH_BYUUID|VSH_BYNAME) - static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name); @@ -1256,252 +1248,6 @@ cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) } /* - * "nwfilter-define" command - */ -static const vshCmdInfo info_nwfilter_define[] = { - {"help", N_("define or update a network filter from an XML file")}, - {"desc", N_("Define a new network filter or update an existing one.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_nwfilter_define[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing an XML network filter description")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNWFilterDefine(vshControl *ctl, const vshCmd *cmd) -{ - virNWFilterPtr nwfilter; - const char *from = NULL; - bool ret = true; - char *buffer; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - nwfilter = virNWFilterDefineXML(ctl->conn, buffer); - VIR_FREE(buffer); - - if (nwfilter != NULL) { - vshPrint(ctl, _("Network filter %s defined from %s\n"), - virNWFilterGetName(nwfilter), from); - virNWFilterFree(nwfilter); - } else { - vshError(ctl, _("Failed to define network filter from %s"), from); - ret = false; - } - return ret; -} - - -/* - * "nwfilter-undefine" command - */ -static const vshCmdInfo info_nwfilter_undefine[] = { - {"help", N_("undefine a network filter")}, - {"desc", N_("Undefine a given network filter.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_nwfilter_undefine[] = { - {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNWFilterUndefine(vshControl *ctl, const vshCmd *cmd) -{ - virNWFilterPtr nwfilter; - bool ret = true; - const char *name; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, &name))) - return false; - - if (virNWFilterUndefine(nwfilter) == 0) { - vshPrint(ctl, _("Network filter %s undefined\n"), name); - } else { - vshError(ctl, _("Failed to undefine network filter %s"), name); - ret = false; - } - - virNWFilterFree(nwfilter); - return ret; -} - - -/* - * "nwfilter-dumpxml" command - */ -static const vshCmdInfo info_nwfilter_dumpxml[] = { - {"help", N_("network filter information in XML")}, - {"desc", N_("Output the network filter information as an XML dump to stdout.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_nwfilter_dumpxml[] = { - {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNWFilterDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - virNWFilterPtr nwfilter; - bool ret = true; - char *dump; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (!(nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL))) - return false; - - dump = virNWFilterGetXMLDesc(nwfilter, 0); - if (dump != NULL) { - vshPrint(ctl, "%s", dump); - VIR_FREE(dump); - } else { - ret = false; - } - - virNWFilterFree(nwfilter); - return ret; -} - -/* - * "nwfilter-list" command - */ -static const vshCmdInfo info_nwfilter_list[] = { - {"help", N_("list network filters")}, - {"desc", N_("Returns list of network filters.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_nwfilter_list[] = { - {NULL, 0, 0, NULL} -}; - -static bool -cmdNWFilterList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - int numfilters, i; - char **names; - char uuid[VIR_UUID_STRING_BUFLEN]; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - numfilters = virConnectNumOfNWFilters(ctl->conn); - if (numfilters < 0) { - vshError(ctl, "%s", _("Failed to list network filters")); - return false; - } - - names = vshMalloc(ctl, sizeof(char *) * numfilters); - - if ((numfilters = virConnectListNWFilters(ctl->conn, names, - numfilters)) < 0) { - vshError(ctl, "%s", _("Failed to list network filters")); - VIR_FREE(names); - return false; - } - - qsort(&names[0], numfilters, sizeof(char *), vshNameSorter); - - vshPrintExtra(ctl, "%-36s %-20s \n", _("UUID"), _("Name")); - vshPrintExtra(ctl, - "----------------------------------------------------------------\n"); - - for (i = 0; i < numfilters; i++) { - virNWFilterPtr nwfilter = - virNWFilterLookupByName(ctl->conn, names[i]); - - /* this kind of work with networks is not atomic operation */ - if (!nwfilter) { - VIR_FREE(names[i]); - continue; - } - - virNWFilterGetUUIDString(nwfilter, uuid); - vshPrint(ctl, "%-36s %-20s\n", - uuid, - virNWFilterGetName(nwfilter)); - virNWFilterFree(nwfilter); - VIR_FREE(names[i]); - } - - VIR_FREE(names); - return true; -} - - -/* - * "nwfilter-edit" command - */ -static const vshCmdInfo info_nwfilter_edit[] = { - {"help", N_("edit XML configuration for a network filter")}, - {"desc", N_("Edit the XML configuration for a network filter.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_nwfilter_edit[] = { - {"nwfilter", VSH_OT_DATA, VSH_OFLAG_REQ, N_("network filter name or uuid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNWFilterEdit(vshControl *ctl, const vshCmd *cmd) -{ - bool ret = false; - virNWFilterPtr nwfilter = NULL; - virNWFilterPtr nwfilter_edited = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - nwfilter = vshCommandOptNWFilter(ctl, cmd, NULL); - if (nwfilter == NULL) - goto cleanup; - -#define EDIT_GET_XML virNWFilterGetXMLDesc(nwfilter, 0) -#define EDIT_NOT_CHANGED \ - vshPrint(ctl, _("Network filter %s XML " \ - "configuration not changed.\n"), \ - virNWFilterGetName(nwfilter)); \ - ret = true; goto edit_cleanup; -#define EDIT_DEFINE \ - (nwfilter_edited = virNWFilterDefineXML(ctl->conn, doc_edited)) -#define EDIT_FREE \ - if (nwfilter_edited) \ - virNWFilterFree(nwfilter); -#include "virsh-edit.c" - - vshPrint(ctl, _("Network filter %s XML configuration edited.\n"), - virNWFilterGetName(nwfilter_edited)); - - ret = true; - -cleanup: - if (nwfilter) - virNWFilterFree(nwfilter); - if (nwfilter_edited) - virNWFilterFree(nwfilter_edited); - - return ret; -} - -/* * "nodedev-create" command */ static const vshCmdInfo info_node_device_create[] = { @@ -5135,44 +4881,6 @@ vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, return dom; } -static virNWFilterPtr -vshCommandOptNWFilterBy(vshControl *ctl, const vshCmd *cmd, - const char **name, int flag) -{ - virNWFilterPtr nwfilter = NULL; - const char *n = NULL; - const char *optname = "nwfilter"; - if (!cmd_has_option(ctl, cmd, optname)) - return NULL; - - if (vshCommandOptString(cmd, optname, &n) <= 0) - return NULL; - - vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n", - cmd->def->name, optname, n); - - if (name) - *name = n; - - /* try it by UUID */ - if ((flag & VSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter UUID\n", - cmd->def->name, optname); - nwfilter = virNWFilterLookupByUUIDString(ctl->conn, n); - } - /* try it by NAME */ - if (nwfilter == NULL && (flag & VSH_BYNAME)) { - vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as nwfilter NAME\n", - cmd->def->name, optname); - nwfilter = virNWFilterLookupByName(ctl->conn, n); - } - - if (!nwfilter) - vshError(ctl, _("failed to get nwfilter '%s'"), n); - - return nwfilter; -} - static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name) { @@ -6770,6 +6478,8 @@ static const vshCmdDef ifaceCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-nwfilter.c" + static const vshCmdDef nwfilterCmds[] = { {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define, info_nwfilter_define, 0}, -- 1.7.7.3

Commands to manage secret are moved from virsh.c to virsh-secret.c, with a few helpers for secret command use. * virsh.c: Remove secret commands and a few helpers. * virsh-secret.c: New file, filled with secret commands and its helpers. --- tools/virsh-secret.c | 358 ++++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 340 +----------------------------------------------- 2 files changed, 360 insertions(+), 338 deletions(-) create mode 100644 tools/virsh-secret.c diff --git a/tools/virsh-secret.c b/tools/virsh-secret.c new file mode 100644 index 0000000..9ec3186 --- /dev/null +++ b/tools/virsh-secret.c @@ -0,0 +1,358 @@ +/* + * virsh-domain.c: Commands to manage secret + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +static virSecretPtr +vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name) +{ + virSecretPtr secret = NULL; + const char *n = NULL; + const char *optname = "secret"; + + if (!cmd_has_option(ctl, cmd, optname)) + return NULL; + + if (vshCommandOptString(cmd, optname, &n) <= 0) + return NULL; + + vshDebug(ctl, VSH_ERR_DEBUG, + "%s: found option <%s>: %s\n", cmd->def->name, optname, n); + + if (name != NULL) + *name = n; + + secret = virSecretLookupByUUIDString(ctl->conn, n); + + if (secret == NULL) + vshError(ctl, _("failed to get secret '%s'"), n); + + return secret; +} + +/* + * "secret-define" command + */ +static const vshCmdInfo info_secret_define[] = { + {"help", N_("define or modify a secret from an XML file")}, + {"desc", N_("Define or modify a secret.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_secret_define[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing secret attributes in XML")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSecretDefine(vshControl *ctl, const vshCmd *cmd) +{ + const char *from = NULL; + char *buffer; + virSecretPtr res; + char uuid[VIR_UUID_STRING_BUFLEN]; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + res = virSecretDefineXML(ctl->conn, buffer, 0); + VIR_FREE(buffer); + + if (res == NULL) { + vshError(ctl, _("Failed to set attributes from %s"), from); + return false; + } + if (virSecretGetUUIDString(res, &(uuid[0])) < 0) { + vshError(ctl, "%s", _("Failed to get UUID of created secret")); + virSecretFree(res); + return false; + } + vshPrint(ctl, _("Secret %s created\n"), uuid); + virSecretFree(res); + return true; +} + +/* + * "secret-dumpxml" command + */ +static const vshCmdInfo info_secret_dumpxml[] = { + {"help", N_("secret attributes in XML")}, + {"desc", N_("Output attributes of a secret as an XML dump to stdout.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_secret_dumpxml[] = { + {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSecretDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + virSecretPtr secret; + bool ret = false; + char *xml; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + secret = vshCommandOptSecret(ctl, cmd, NULL); + if (secret == NULL) + return false; + + xml = virSecretGetXMLDesc(secret, 0); + if (xml == NULL) + goto cleanup; + vshPrint(ctl, "%s", xml); + VIR_FREE(xml); + ret = true; + +cleanup: + virSecretFree(secret); + return ret; +} + +/* + * "secret-set-value" command + */ +static const vshCmdInfo info_secret_set_value[] = { + {"help", N_("set a secret value")}, + {"desc", N_("Set a secret value.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_secret_set_value[] = { + {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, + {"base64", VSH_OT_DATA, VSH_OFLAG_REQ, N_("base64-encoded secret value")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSecretSetValue(vshControl *ctl, const vshCmd *cmd) +{ + virSecretPtr secret; + size_t value_size; + const char *base64 = NULL; + char *value; + int res; + bool ret = false; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + secret = vshCommandOptSecret(ctl, cmd, NULL); + if (secret == NULL) + return false; + + if (vshCommandOptString(cmd, "base64", &base64) <= 0) + goto cleanup; + + if (!base64_decode_alloc(base64, strlen(base64), &value, &value_size)) { + vshError(ctl, "%s", _("Invalid base64 data")); + goto cleanup; + } + if (value == NULL) { + vshError(ctl, "%s", _("Failed to allocate memory")); + return false; + } + + res = virSecretSetValue(secret, (unsigned char *)value, value_size, 0); + memset(value, 0, value_size); + VIR_FREE(value); + + if (res != 0) { + vshError(ctl, "%s", _("Failed to set secret value")); + goto cleanup; + } + vshPrint(ctl, "%s", _("Secret value set\n")); + ret = true; + +cleanup: + virSecretFree(secret); + return ret; +} + +/* + * "secret-get-value" command + */ +static const vshCmdInfo info_secret_get_value[] = { + {"help", N_("Output a secret value")}, + {"desc", N_("Output a secret value to stdout.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_secret_get_value[] = { + {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSecretGetValue(vshControl *ctl, const vshCmd *cmd) +{ + virSecretPtr secret; + char *base64; + unsigned char *value; + size_t value_size; + bool ret = false; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + secret = vshCommandOptSecret(ctl, cmd, NULL); + if (secret == NULL) + return false; + + value = virSecretGetValue(secret, &value_size, 0); + if (value == NULL) + goto cleanup; + + base64_encode_alloc((char *)value, value_size, &base64); + memset(value, 0, value_size); + VIR_FREE(value); + + if (base64 == NULL) { + vshError(ctl, "%s", _("Failed to allocate memory")); + goto cleanup; + } + vshPrint(ctl, "%s", base64); + memset(base64, 0, strlen(base64)); + VIR_FREE(base64); + ret = true; + +cleanup: + virSecretFree(secret); + return ret; +} + +/* + * "secret-undefine" command + */ +static const vshCmdInfo info_secret_undefine[] = { + {"help", N_("undefine a secret")}, + {"desc", N_("Undefine a secret.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_secret_undefine[] = { + {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSecretUndefine(vshControl *ctl, const vshCmd *cmd) +{ + virSecretPtr secret; + bool ret = false; + const char *uuid; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + secret = vshCommandOptSecret(ctl, cmd, &uuid); + if (secret == NULL) + return false; + + if (virSecretUndefine(secret) < 0) { + vshError(ctl, _("Failed to delete secret %s"), uuid); + goto cleanup; + } + vshPrint(ctl, _("Secret %s deleted\n"), uuid); + ret = true; + +cleanup: + virSecretFree(secret); + return ret; +} + +/* + * "secret-list" command + */ +static const vshCmdInfo info_secret_list[] = { + {"help", N_("list secrets")}, + {"desc", N_("Returns a list of secrets")}, + {NULL, NULL} +}; + +static bool +cmdSecretList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + int maxuuids = 0, i; + char **uuids = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + maxuuids = virConnectNumOfSecrets(ctl->conn); + if (maxuuids < 0) { + vshError(ctl, "%s", _("Failed to list secrets")); + return false; + } + uuids = vshMalloc(ctl, sizeof(*uuids) * maxuuids); + + maxuuids = virConnectListSecrets(ctl->conn, uuids, maxuuids); + if (maxuuids < 0) { + vshError(ctl, "%s", _("Failed to list secrets")); + VIR_FREE(uuids); + return false; + } + + qsort(uuids, maxuuids, sizeof(char *), vshNameSorter); + + vshPrintExtra(ctl, "%-36s %s\n", _("UUID"), _("Usage")); + vshPrintExtra(ctl, "-----------------------------------------------------------\n"); + + for (i = 0; i < maxuuids; i++) { + virSecretPtr sec = virSecretLookupByUUIDString(ctl->conn, uuids[i]); + const char *usageType = NULL; + + if (!sec) { + VIR_FREE(uuids[i]); + continue; + } + + switch (virSecretGetUsageType(sec)) { + case VIR_SECRET_USAGE_TYPE_VOLUME: + usageType = _("Volume"); + break; + } + + if (usageType) { + vshPrint(ctl, "%-36s %s %s\n", + uuids[i], usageType, + virSecretGetUsageID(sec)); + } else { + vshPrint(ctl, "%-36s %s\n", + uuids[i], _("Unused")); + } + virSecretFree(sec); + VIR_FREE(uuids[i]); + } + VIR_FREE(uuids); + return true; +} diff --git a/tools/virsh.c b/tools/virsh.c index 4844e31..cddb6e3 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -339,9 +339,6 @@ static virDomainPtr vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, #define vshCommandOptDomain(_ctl, _cmd, _name) \ vshCommandOptDomainBy(_ctl, _cmd, _name, VSH_BYID|VSH_BYUUID|VSH_BYNAME) -static virSecretPtr vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, - const char **name); - static void vshPrintExtra(vshControl *ctl, const char *format, ...) ATTRIBUTE_FMT_PRINTF(2, 3); static void vshDebug(vshControl *ctl, int level, const char *format, ...) @@ -1342,314 +1339,6 @@ cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd) } /* - * "secret-define" command - */ -static const vshCmdInfo info_secret_define[] = { - {"help", N_("define or modify a secret from an XML file")}, - {"desc", N_("Define or modify a secret.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_secret_define[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, N_("file containing secret attributes in XML")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSecretDefine(vshControl *ctl, const vshCmd *cmd) -{ - const char *from = NULL; - char *buffer; - virSecretPtr res; - char uuid[VIR_UUID_STRING_BUFLEN]; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - res = virSecretDefineXML(ctl->conn, buffer, 0); - VIR_FREE(buffer); - - if (res == NULL) { - vshError(ctl, _("Failed to set attributes from %s"), from); - return false; - } - if (virSecretGetUUIDString(res, &(uuid[0])) < 0) { - vshError(ctl, "%s", _("Failed to get UUID of created secret")); - virSecretFree(res); - return false; - } - vshPrint(ctl, _("Secret %s created\n"), uuid); - virSecretFree(res); - return true; -} - -/* - * "secret-dumpxml" command - */ -static const vshCmdInfo info_secret_dumpxml[] = { - {"help", N_("secret attributes in XML")}, - {"desc", N_("Output attributes of a secret as an XML dump to stdout.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_secret_dumpxml[] = { - {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSecretDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - virSecretPtr secret; - bool ret = false; - char *xml; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - secret = vshCommandOptSecret(ctl, cmd, NULL); - if (secret == NULL) - return false; - - xml = virSecretGetXMLDesc(secret, 0); - if (xml == NULL) - goto cleanup; - vshPrint(ctl, "%s", xml); - VIR_FREE(xml); - ret = true; - -cleanup: - virSecretFree(secret); - return ret; -} - -/* - * "secret-set-value" command - */ -static const vshCmdInfo info_secret_set_value[] = { - {"help", N_("set a secret value")}, - {"desc", N_("Set a secret value.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_secret_set_value[] = { - {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, - {"base64", VSH_OT_DATA, VSH_OFLAG_REQ, N_("base64-encoded secret value")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSecretSetValue(vshControl *ctl, const vshCmd *cmd) -{ - virSecretPtr secret; - size_t value_size; - const char *base64 = NULL; - char *value; - int res; - bool ret = false; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - secret = vshCommandOptSecret(ctl, cmd, NULL); - if (secret == NULL) - return false; - - if (vshCommandOptString(cmd, "base64", &base64) <= 0) - goto cleanup; - - if (!base64_decode_alloc(base64, strlen(base64), &value, &value_size)) { - vshError(ctl, "%s", _("Invalid base64 data")); - goto cleanup; - } - if (value == NULL) { - vshError(ctl, "%s", _("Failed to allocate memory")); - return false; - } - - res = virSecretSetValue(secret, (unsigned char *)value, value_size, 0); - memset(value, 0, value_size); - VIR_FREE(value); - - if (res != 0) { - vshError(ctl, "%s", _("Failed to set secret value")); - goto cleanup; - } - vshPrint(ctl, "%s", _("Secret value set\n")); - ret = true; - -cleanup: - virSecretFree(secret); - return ret; -} - -/* - * "secret-get-value" command - */ -static const vshCmdInfo info_secret_get_value[] = { - {"help", N_("Output a secret value")}, - {"desc", N_("Output a secret value to stdout.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_secret_get_value[] = { - {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSecretGetValue(vshControl *ctl, const vshCmd *cmd) -{ - virSecretPtr secret; - char *base64; - unsigned char *value; - size_t value_size; - bool ret = false; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - secret = vshCommandOptSecret(ctl, cmd, NULL); - if (secret == NULL) - return false; - - value = virSecretGetValue(secret, &value_size, 0); - if (value == NULL) - goto cleanup; - - base64_encode_alloc((char *)value, value_size, &base64); - memset(value, 0, value_size); - VIR_FREE(value); - - if (base64 == NULL) { - vshError(ctl, "%s", _("Failed to allocate memory")); - goto cleanup; - } - vshPrint(ctl, "%s", base64); - memset(base64, 0, strlen(base64)); - VIR_FREE(base64); - ret = true; - -cleanup: - virSecretFree(secret); - return ret; -} - -/* - * "secret-undefine" command - */ -static const vshCmdInfo info_secret_undefine[] = { - {"help", N_("undefine a secret")}, - {"desc", N_("Undefine a secret.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_secret_undefine[] = { - {"secret", VSH_OT_DATA, VSH_OFLAG_REQ, N_("secret UUID")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSecretUndefine(vshControl *ctl, const vshCmd *cmd) -{ - virSecretPtr secret; - bool ret = false; - const char *uuid; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - secret = vshCommandOptSecret(ctl, cmd, &uuid); - if (secret == NULL) - return false; - - if (virSecretUndefine(secret) < 0) { - vshError(ctl, _("Failed to delete secret %s"), uuid); - goto cleanup; - } - vshPrint(ctl, _("Secret %s deleted\n"), uuid); - ret = true; - -cleanup: - virSecretFree(secret); - return ret; -} - -/* - * "secret-list" command - */ -static const vshCmdInfo info_secret_list[] = { - {"help", N_("list secrets")}, - {"desc", N_("Returns a list of secrets")}, - {NULL, NULL} -}; - -static bool -cmdSecretList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - int maxuuids = 0, i; - char **uuids = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - maxuuids = virConnectNumOfSecrets(ctl->conn); - if (maxuuids < 0) { - vshError(ctl, "%s", _("Failed to list secrets")); - return false; - } - uuids = vshMalloc(ctl, sizeof(*uuids) * maxuuids); - - maxuuids = virConnectListSecrets(ctl->conn, uuids, maxuuids); - if (maxuuids < 0) { - vshError(ctl, "%s", _("Failed to list secrets")); - VIR_FREE(uuids); - return false; - } - - qsort(uuids, maxuuids, sizeof(char *), vshNameSorter); - - vshPrintExtra(ctl, "%-36s %s\n", _("UUID"), _("Usage")); - vshPrintExtra(ctl, "-----------------------------------------------------------\n"); - - for (i = 0; i < maxuuids; i++) { - virSecretPtr sec = virSecretLookupByUUIDString(ctl->conn, uuids[i]); - const char *usageType = NULL; - - if (!sec) { - VIR_FREE(uuids[i]); - continue; - } - - switch (virSecretGetUsageType(sec)) { - case VIR_SECRET_USAGE_TYPE_VOLUME: - usageType = _("Volume"); - break; - } - - if (usageType) { - vshPrint(ctl, "%-36s %s %s\n", - uuids[i], usageType, - virSecretGetUsageID(sec)); - } else { - vshPrint(ctl, "%-36s %s\n", - uuids[i], _("Unused")); - } - virSecretFree(sec); - VIR_FREE(uuids[i]); - } - VIR_FREE(uuids); - return true; -} - - -/* * "version" command */ static const vshCmdInfo info_version[] = { @@ -4881,33 +4570,6 @@ vshCommandOptDomainBy(vshControl *ctl, const vshCmd *cmd, return dom; } -static virSecretPtr -vshCommandOptSecret(vshControl *ctl, const vshCmd *cmd, const char **name) -{ - virSecretPtr secret = NULL; - const char *n = NULL; - const char *optname = "secret"; - - if (!cmd_has_option(ctl, cmd, optname)) - return NULL; - - if (vshCommandOptString(cmd, optname, &n) <= 0) - return NULL; - - vshDebug(ctl, VSH_ERR_DEBUG, - "%s: found option <%s>: %s\n", cmd->def->name, optname, n); - - if (name != NULL) - *name = n; - - secret = virSecretLookupByUUIDString(ctl->conn, n); - - if (secret == NULL) - vshError(ctl, _("failed to get secret '%s'"), n); - - return secret; -} - /* * Executes command(s) and returns return code from last command */ @@ -6494,6 +6156,8 @@ static const vshCmdDef nwfilterCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-secret.c" + static const vshCmdDef secretCmds[] = { {"secret-define", cmdSecretDefine, opts_secret_define, info_secret_define, 0}, -- 1.7.7.3

Commands to manage domain snapshot are moved from virsh.c to virsh-snapshot.c, with a few helpers for domain snapshot commands use. * virsh.c: Remove domain snapshot commands and a few helpers. * virsh-snapshot.c: New file, filled with domain snapshot commands and its helpers. --- tools/virsh-snapshot.c | 1604 ++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 1582 +----------------------------------------------- 2 files changed, 1606 insertions(+), 1580 deletions(-) create mode 100644 tools/virsh-snapshot.c diff --git a/tools/virsh-snapshot.c b/tools/virsh-snapshot.c new file mode 100644 index 0000000..c0a2d9d --- /dev/null +++ b/tools/virsh-snapshot.c @@ -0,0 +1,1604 @@ +/* + * virsh-domain.c: Commands to manage domain snapshot + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* Helper for snapshot-create and snapshot-create-as */ +static bool +vshSnapshotCreate(vshControl *ctl, virDomainPtr dom, const char *buffer, + unsigned int flags, const char *from) +{ + bool ret = false; + virDomainSnapshotPtr snapshot; + bool halt = false; + char *doc = NULL; + xmlDocPtr xml = NULL; + xmlXPathContextPtr ctxt = NULL; + const char *name = NULL; + + snapshot = virDomainSnapshotCreateXML(dom, buffer, flags); + + /* Emulate --halt on older servers. */ + if (!snapshot && last_error->code == VIR_ERR_INVALID_ARG && + (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) { + int persistent; + + virFreeError(last_error); + last_error = NULL; + persistent = virDomainIsPersistent(dom); + if (persistent < 0) { + virshReportError(ctl); + goto cleanup; + } + if (!persistent) { + vshError(ctl, "%s", + _("cannot halt after snapshot of transient domain")); + goto cleanup; + } + if (virDomainIsActive(dom) == 1) + halt = true; + flags &= ~VIR_DOMAIN_SNAPSHOT_CREATE_HALT; + snapshot = virDomainSnapshotCreateXML(dom, buffer, flags); + } + + if (snapshot == NULL) + goto cleanup; + + if (halt && virDomainDestroy(dom) < 0) { + virshReportError(ctl); + goto cleanup; + } + + name = virDomainSnapshotGetName(snapshot); + if (!name) { + vshError(ctl, "%s", _("Could not get snapshot name")); + goto cleanup; + } + + if (from) + vshPrint(ctl, _("Domain snapshot %s created from '%s'"), name, from); + else + vshPrint(ctl, _("Domain snapshot %s created"), name); + + ret = true; + +cleanup: + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml); + if (snapshot) + virDomainSnapshotFree(snapshot); + VIR_FREE(doc); + return ret; +} + +/* + * "snapshot-create" command + */ +static const vshCmdInfo info_snapshot_create[] = { + {"help", N_("Create a snapshot from XML")}, + {"desc", N_("Create a snapshot (disk and RAM) from XML")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_create[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"xmlfile", VSH_OT_DATA, 0, N_("domain snapshot XML")}, + {"redefine", VSH_OT_BOOL, 0, N_("redefine metadata for existing snapshot")}, + {"current", VSH_OT_BOOL, 0, N_("with redefine, set current snapshot")}, + {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")}, + {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")}, + {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")}, + {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")}, + {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")}, + {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotCreate(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + const char *from = NULL; + char *buffer = NULL; + unsigned int flags = 0; + + if (vshCommandOptBool(cmd, "redefine")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE; + if (vshCommandOptBool(cmd, "current")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT; + if (vshCommandOptBool(cmd, "no-metadata")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA; + if (vshCommandOptBool(cmd, "halt")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT; + if (vshCommandOptBool(cmd, "disk-only")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; + if (vshCommandOptBool(cmd, "reuse-external")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT; + if (vshCommandOptBool(cmd, "quiesce")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE; + if (vshCommandOptBool(cmd, "atomic")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshCommandOptString(cmd, "xmlfile", &from) <= 0) + buffer = vshStrdup(ctl, "<domainsnapshot/>"); + else { + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) { + /* we have to report the error here because during cleanup + * we'll run through virDomainFree(), which loses the + * last error + */ + virshReportError(ctl); + goto cleanup; + } + } + if (buffer == NULL) { + vshError(ctl, "%s", _("Out of memory")); + goto cleanup; + } + + ret = vshSnapshotCreate(ctl, dom, buffer, flags, from); + +cleanup: + VIR_FREE(buffer); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "snapshot-create-as" command + */ +static int +vshParseSnapshotDiskspec(vshControl *ctl, virBufferPtr buf, const char *str) +{ + int ret = -1; + char *name = NULL; + char *snapshot = NULL; + char *driver = NULL; + char *file = NULL; + char *spec = vshStrdup(ctl, str); + char *tmp = spec; + size_t len = strlen(str); + + if (*str == ',') + goto cleanup; + name = tmp; + while ((tmp = strchr(tmp, ','))) { + if (tmp[1] == ',') { + /* Recognize ,, as an escape for a literal comma */ + memmove(&tmp[1], &tmp[2], len - (tmp - spec) - 2 + 1); + len--; + tmp++; + continue; + } + /* Terminate previous string, look for next recognized one */ + *tmp++ = '\0'; + if (!snapshot && STRPREFIX(tmp, "snapshot=")) + snapshot = tmp + strlen("snapshot="); + else if (!driver && STRPREFIX(tmp, "driver=")) + driver = tmp + strlen("driver="); + else if (!file && STRPREFIX(tmp, "file=")) + file = tmp + strlen("file="); + else + goto cleanup; + } + + virBufferEscapeString(buf, " <disk name='%s'", name); + if (snapshot) + virBufferAsprintf(buf, " snapshot='%s'", snapshot); + if (driver || file) { + virBufferAddLit(buf, ">\n"); + if (driver) + virBufferAsprintf(buf, " <driver type='%s'/>\n", driver); + if (file) + virBufferEscapeString(buf, " <source file='%s'/>\n", file); + virBufferAddLit(buf, " </disk>\n"); + } else { + virBufferAddLit(buf, "/>\n"); + } + ret = 0; +cleanup: + if (ret < 0) + vshError(ctl, _("unable to parse diskspec: %s"), str); + VIR_FREE(spec); + return ret; +} + +static const vshCmdInfo info_snapshot_create_as[] = { + {"help", N_("Create a snapshot from a set of args")}, + {"desc", N_("Create a snapshot (disk and RAM) from arguments")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_create_as[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"name", VSH_OT_DATA, 0, N_("name of snapshot")}, + {"description", VSH_OT_DATA, 0, N_("description of snapshot")}, + {"print-xml", VSH_OT_BOOL, 0, N_("print XML document rather than create")}, + {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")}, + {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")}, + {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")}, + {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")}, + {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")}, + {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")}, + {"diskspec", VSH_OT_ARGV, 0, + N_("disk attributes: disk[,snapshot=type][,driver=type][,file=name]")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotCreateAs(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + char *buffer = NULL; + const char *name = NULL; + const char *desc = NULL; + virBuffer buf = VIR_BUFFER_INITIALIZER; + unsigned int flags = 0; + const vshCmdOpt *opt = NULL; + + if (vshCommandOptBool(cmd, "no-metadata")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA; + if (vshCommandOptBool(cmd, "halt")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT; + if (vshCommandOptBool(cmd, "disk-only")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; + if (vshCommandOptBool(cmd, "reuse-external")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT; + if (vshCommandOptBool(cmd, "quiesce")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE; + if (vshCommandOptBool(cmd, "atomic")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshCommandOptString(cmd, "name", &name) < 0 || + vshCommandOptString(cmd, "description", &desc) < 0) { + vshError(ctl, _("argument must not be empty")); + goto cleanup; + } + + virBufferAddLit(&buf, "<domainsnapshot>\n"); + if (name) + virBufferEscapeString(&buf, " <name>%s</name>\n", name); + if (desc) + virBufferEscapeString(&buf, " <description>%s</description>\n", desc); + if (vshCommandOptBool(cmd, "diskspec")) { + virBufferAddLit(&buf, " <disks>\n"); + while ((opt = vshCommandOptArgv(cmd, opt))) { + if (vshParseSnapshotDiskspec(ctl, &buf, opt->data) < 0) { + virBufferFreeAndReset(&buf); + goto cleanup; + } + } + virBufferAddLit(&buf, " </disks>\n"); + } + virBufferAddLit(&buf, "</domainsnapshot>\n"); + + buffer = virBufferContentAndReset(&buf); + if (buffer == NULL) { + vshError(ctl, "%s", _("Out of memory")); + goto cleanup; + } + + if (vshCommandOptBool(cmd, "print-xml")) { + vshPrint(ctl, "%s\n", buffer); + ret = true; + goto cleanup; + } + + ret = vshSnapshotCreate(ctl, dom, buffer, flags, NULL); + +cleanup: + VIR_FREE(buffer); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* Helper for resolving {--current | --ARG name} into a snapshot + * belonging to DOM. If EXCLUSIVE, fail if both --current and arg are + * present. On success, populate *SNAP and *NAME, before returning 0. + * On failure, return -1 after issuing an error message. */ +static int +vshLookupSnapshot(vshControl *ctl, const vshCmd *cmd, + const char *arg, bool exclusive, virDomainPtr dom, + virDomainSnapshotPtr *snap, const char **name) +{ + bool current = vshCommandOptBool(cmd, "current"); + const char *snapname = NULL; + + if (vshCommandOptString(cmd, arg, &snapname) < 0) { + vshError(ctl, _("invalid argument for --%s"), arg); + return -1; + } + + if (exclusive && current && snapname) { + vshError(ctl, _("--%s and --current are mutually exclusive"), arg); + return -1; + } + + if (snapname) { + *snap = virDomainSnapshotLookupByName(dom, snapname, 0); + } else if (current) { + *snap = virDomainSnapshotCurrent(dom, 0); + } else { + vshError(ctl, _("--%s or --current is required"), arg); + return -1; + } + if (!*snap) { + virshReportError(ctl); + return -1; + } + + *name = virDomainSnapshotGetName(*snap); + return 0; +} + +/* + * "snapshot-edit" command + */ +static const vshCmdInfo info_snapshot_edit[] = { + {"help", N_("edit XML for a snapshot")}, + {"desc", N_("Edit the domain snapshot XML for a named snapshot")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_edit[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, + {"current", VSH_OT_BOOL, 0, N_("also set edited snapshot as current")}, + {"rename", VSH_OT_BOOL, 0, N_("allow renaming an existing snapshot")}, + {"clone", VSH_OT_BOOL, 0, N_("allow cloning to new name")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotEdit(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + virDomainSnapshotPtr snapshot = NULL; + virDomainSnapshotPtr edited = NULL; + const char *name; + const char *edited_name; + bool ret = false; + unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE; + unsigned int define_flags = VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE; + bool rename_okay = vshCommandOptBool(cmd, "rename"); + bool clone_okay = vshCommandOptBool(cmd, "clone"); + + if (rename_okay && clone_okay) { + vshError(ctl, "%s", + _("--rename and --clone are mutually exclusive")); + return false; + } + + if (vshCommandOptBool(cmd, "current") && + vshCommandOptBool(cmd, "snapshotname")) + define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshLookupSnapshot(ctl, cmd, "snapshotname", false, dom, + &snapshot, &name) < 0) + goto cleanup; + +#define EDIT_GET_XML \ + virDomainSnapshotGetXMLDesc(snapshot, getxml_flags) +#define EDIT_NOT_CHANGED \ + /* Depending on flags, we re-edit even if XML is unchanged. */ \ + if (!(define_flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) { \ + vshPrint(ctl, \ + _("Snapshot %s XML configuration not changed.\n"), \ + name); \ + ret = true; \ + goto cleanup; \ + } +#define EDIT_DEFINE \ + (strstr(doc, "<state>disk-snapshot</state>") ? \ + define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY : 0), \ + edited = virDomainSnapshotCreateXML(dom, doc_edited, define_flags) +#define EDIT_FREE \ + if (edited) \ + virDomainSnapshotFree(edited); +#include "virsh-edit.c" + + edited_name = virDomainSnapshotGetName(edited); + if (STREQ(name, edited_name)) { + vshPrint(ctl, _("Snapshot %s edited.\n"), name); + } else if (clone_okay) { + vshPrint(ctl, _("Snapshot %s cloned to %s.\n"), name, + edited_name); + } else { + unsigned int delete_flags; + + delete_flags = VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY; + if (virDomainSnapshotDelete(rename_okay ? snapshot : edited, + delete_flags) < 0) { + virshReportError(ctl); + vshError(ctl, _("Failed to clean up %s"), + rename_okay ? name : edited_name); + goto cleanup; + } + if (!rename_okay) { + vshError(ctl, _("Must use --rename or --clone to change %s to %s"), + name, edited_name); + goto cleanup; + } + } + + ret = true; + +cleanup: + if (edited) + virDomainSnapshotFree(edited); + else + vshError(ctl, _("Failed to update %s"), name); + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + return ret; +} + +/* + * "snapshot-current" command + */ +static const vshCmdInfo info_snapshot_current[] = { + {"help", N_("Get or set the current snapshot")}, + {"desc", N_("Get or set the current snapshot")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_current[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"name", VSH_OT_BOOL, 0, N_("list the name, rather than the full xml")}, + {"security-info", VSH_OT_BOOL, 0, + N_("include security sensitive information in XML dump")}, + {"snapshotname", VSH_OT_DATA, 0, + N_("name of existing snapshot to make current")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotCurrent(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + int current; + virDomainSnapshotPtr snapshot = NULL; + char *xml = NULL; + const char *snapshotname = NULL; + unsigned int flags = 0; + const char *domname; + + if (vshCommandOptBool(cmd, "security-info")) + flags |= VIR_DOMAIN_XML_SECURE; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, &domname); + if (dom == NULL) + goto cleanup; + + if (vshCommandOptString(cmd, "snapshotname", &snapshotname) < 0) { + vshError(ctl, _("invalid snapshotname argument '%s'"), snapshotname); + goto cleanup; + } + if (snapshotname) { + virDomainSnapshotPtr snapshot2 = NULL; + flags = (VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE | + VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT); + + if (vshCommandOptBool(cmd, "name")) { + vshError(ctl, "%s", + _("--name and snapshotname are mutually exclusive")); + goto cleanup; + } + snapshot = virDomainSnapshotLookupByName(dom, snapshotname, 0); + if (snapshot == NULL) + goto cleanup; + xml = virDomainSnapshotGetXMLDesc(snapshot, VIR_DOMAIN_XML_SECURE); + if (!xml) + goto cleanup; + /* strstr is safe here, since xml came from libvirt API and not user */ + if (strstr(xml, "<state>disk-snapshot</state>")) + flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; + snapshot2 = virDomainSnapshotCreateXML(dom, xml, flags); + if (snapshot2 == NULL) + goto cleanup; + virDomainSnapshotFree(snapshot2); + vshPrint(ctl, _("Snapshot %s set as current"), snapshotname); + ret = true; + goto cleanup; + } + + current = virDomainHasCurrentSnapshot(dom, 0); + if (current < 0) { + goto cleanup; + } else if (!current) { + vshError(ctl, _("domain '%s' has no current snapshot"), domname); + goto cleanup; + } else { + const char *name = NULL; + + if (!(snapshot = virDomainSnapshotCurrent(dom, 0))) + goto cleanup; + + if (vshCommandOptBool(cmd, "name")) { + name = virDomainSnapshotGetName(snapshot); + if (!name) + goto cleanup; + } else { + xml = virDomainSnapshotGetXMLDesc(snapshot, flags); + if (!xml) + goto cleanup; + } + + vshPrint(ctl, "%s", name ? name : xml); + } + + ret = true; + +cleanup: + if (!ret) + virshReportError(ctl); + VIR_FREE(xml); + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* Helper function to get the name of a snapshot's parent. Caller + * must free the result. Returns 0 on success (including when it was + * proven no parent exists), and -1 on failure with error reported + * (such as no snapshot support or domain deleted in meantime). */ +static int +vshGetSnapshotParent(vshControl *ctl, virDomainSnapshotPtr snapshot, + char **parent_name) +{ + virDomainSnapshotPtr parent = NULL; + char *xml = NULL; + xmlDocPtr xmldoc = NULL; + xmlXPathContextPtr ctxt = NULL; + int ret = -1; + + *parent_name = NULL; + + /* Try new API, since it is faster. */ + if (!ctl->useSnapshotOld) { + parent = virDomainSnapshotGetParent(snapshot, 0); + if (parent) { + /* API works, and virDomainSnapshotGetName will succeed */ + *parent_name = vshStrdup(ctl, virDomainSnapshotGetName(parent)); + ret = 0; + goto cleanup; + } + if (last_error->code == VIR_ERR_NO_DOMAIN_SNAPSHOT) { + /* API works, and we found a root with no parent */ + ret = 0; + goto cleanup; + } + /* API didn't work, fall back to XML scraping. */ + ctl->useSnapshotOld = true; + } + + xml = virDomainSnapshotGetXMLDesc(snapshot, 0); + if (!xml) + goto cleanup; + + xmldoc = virXMLParseStringCtxt(xml, _("(domain_snapshot)"), &ctxt); + if (!xmldoc) + goto cleanup; + + *parent_name = virXPathString("string(/domainsnapshot/parent/name)", ctxt); + ret = 0; + +cleanup: + if (ret < 0) { + virshReportError(ctl); + vshError(ctl, "%s", _("unable to determine if snapshot has parent")); + } else { + virFreeError(last_error); + last_error = NULL; + } + if (parent) + virDomainSnapshotFree(parent); + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xmldoc); + VIR_FREE(xml); + return ret; +} + +/* + * "snapshot-info" command + */ +static const vshCmdInfo info_snapshot_info[] = { + {"help", N_("snapshot information")}, + {"desc", N_("Returns basic information about a snapshot.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_info[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, + {"current", VSH_OT_BOOL, 0, N_("info on current snapshot")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotInfo(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom; + virDomainSnapshotPtr snapshot = NULL; + const char *name; + char *doc = NULL; + char *tmp; + char *parent = NULL; + bool ret = false; + int count; + unsigned int flags; + int current; + int metadata; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + return false; + + if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, + &snapshot, &name) < 0) + goto cleanup; + + vshPrint(ctl, "%-15s %s\n", _("Name:"), name); + vshPrint(ctl, "%-15s %s\n", _("Domain:"), virDomainGetName(dom)); + + /* Determine if snapshot is current; this is useful enough that we + * attempt a fallback. */ + current = virDomainSnapshotIsCurrent(snapshot, 0); + if (current < 0) { + virDomainSnapshotPtr other = virDomainSnapshotCurrent(dom, 0); + + virResetLastError(); + current = 0; + if (other) { + if (STREQ(name, virDomainSnapshotGetName(other))) + current = 1; + virDomainSnapshotFree(other); + } + } + vshPrint(ctl, "%-15s %s\n", _("Current:"), + current > 0 ? _("yes") : _("no")); + + /* Get the XML configuration of the snapshot to determine the + * state of the machine at the time of the snapshot. */ + doc = virDomainSnapshotGetXMLDesc(snapshot, 0); + if (!doc) + goto cleanup; + + tmp = strstr(doc, "<state>"); + if (!tmp) { + vshError(ctl, "%s", + _("unexpected problem reading snapshot xml")); + goto cleanup; + } + tmp += strlen("<state>"); + vshPrint(ctl, "%-15s %.*s\n", _("State:"), + (int) (strchr(tmp, '<') - tmp), tmp); + + if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0) + goto cleanup; + vshPrint(ctl, "%-15s %s\n", _("Parent:"), parent ? parent : "-"); + + /* Children, Descendants. After this point, the fallback to + * compute children is too expensive, so we gracefully quit if the + * APIs don't exist. */ + if (ctl->useSnapshotOld) { + ret = true; + goto cleanup; + } + flags = 0; + count = virDomainSnapshotNumChildren(snapshot, flags); + if (count < 0) + goto cleanup; + vshPrint(ctl, "%-15s %d\n", _("Children:"), count); + flags = VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; + count = virDomainSnapshotNumChildren(snapshot, flags); + if (count < 0) + goto cleanup; + vshPrint(ctl, "%-15s %d\n", _("Descendants:"), count); + + /* Metadata; the fallback here relies on the fact that metadata + * used to have an all-or-nothing effect on snapshot count. */ + metadata = virDomainSnapshotHasMetadata(snapshot, 0); + if (metadata < 0) { + metadata = virDomainSnapshotNum(dom, + VIR_DOMAIN_SNAPSHOT_LIST_METADATA); + virResetLastError(); + } + if (metadata >= 0) + vshPrint(ctl, "%-15s %s\n", _("Metadata:"), + metadata ? _("yes") : _("no")); + + ret = true; + +cleanup: + VIR_FREE(doc); + VIR_FREE(parent); + if (snapshot) + virDomainSnapshotFree(snapshot); + virDomainFree(dom); + return ret; +} + +/* Helpers for collecting a list of snapshots. */ +struct vshSnap { + virDomainSnapshotPtr snap; + char *parent; +}; +struct vshSnapshotList { + struct vshSnap *snaps; + int nsnaps; +}; +typedef struct vshSnapshotList *vshSnapshotListPtr; + +static void +vshSnapshotListFree(vshSnapshotListPtr snaplist) +{ + int i; + + if (!snaplist) + return; + if (snaplist->snaps) { + for (i = 0; i < snaplist->nsnaps; i++) { + if (snaplist->snaps[i].snap) + virDomainSnapshotFree(snaplist->snaps[i].snap); + VIR_FREE(snaplist->snaps[i].parent); + } + VIR_FREE(snaplist->snaps); + } + VIR_FREE(snaplist); +} + +static int +vshSnapSorter(const void *a, const void *b) +{ + const struct vshSnap *sa = a; + const struct vshSnap *sb = b; + + if (sa->snap && !sb->snap) + return -1; + if (!sa->snap) + return sb->snap != NULL; + + /* User visible sort, so we want locale-specific case comparison. */ + return strcasecmp(virDomainSnapshotGetName(sa->snap), + virDomainSnapshotGetName(sb->snap)); +} + +/* Compute a list of snapshots from DOM. If FROM is provided, the + * list is limited to descendants of the given snapshot. If FLAGS is + * given, the list is filtered. If TREE is specified, then all but + * FROM or the roots will also have parent information. */ +static vshSnapshotListPtr +vshSnapshotListCollect(vshControl *ctl, virDomainPtr dom, + virDomainSnapshotPtr from, + unsigned int flags, bool tree) +{ + int i; + char **names = NULL; + int count = -1; + bool descendants = false; + bool roots = false; + virDomainSnapshotPtr *snaps; + vshSnapshotListPtr snaplist = vshMalloc(ctl, sizeof(*snaplist)); + vshSnapshotListPtr ret = NULL; + const char *fromname = NULL; + int start_index = -1; + int deleted = 0; + + /* Try the interface available in 0.9.13 and newer. */ + if (!ctl->useSnapshotOld) { + if (from) + count = virDomainSnapshotListAllChildren(from, &snaps, flags); + else + count = virDomainListAllSnapshots(dom, &snaps, flags); + } + if (count >= 0) { + /* When mixing --from and --tree, we also want a copy of from + * in the list, but with no parent for that one entry. */ + snaplist->snaps = vshCalloc(ctl, count + (tree && from), + sizeof(*snaplist->snaps)); + snaplist->nsnaps = count; + for (i = 0; i < count; i++) + snaplist->snaps[i].snap = snaps[i]; + VIR_FREE(snaps); + if (tree) { + for (i = 0; i < count; i++) { + if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap, + &snaplist->snaps[i].parent) < 0) + goto cleanup; + } + if (from) { + snaps[snaplist->nsnaps++] = from; + virDomainSnapshotRef(from); + } + } + goto success; + } + + /* Assume that if we got this far, then the --no-leaves and + * --no-metadata flags were not supported. Disable groups that + * have no impact. */ + /* XXX should we emulate --no-leaves? */ + if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES && + flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) + flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES | + VIR_DOMAIN_SNAPSHOT_LIST_LEAVES); + if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA && + flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) + flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA | + VIR_DOMAIN_SNAPSHOT_LIST_METADATA); + if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA) { + /* We can emulate --no-metadata if --metadata was supported, + * since it was an all-or-none attribute on old servers. */ + count = virDomainSnapshotNum(dom, + VIR_DOMAIN_SNAPSHOT_LIST_METADATA); + if (count < 0) + goto cleanup; + if (count > 0) + return snaplist; + flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA; + } + + /* This uses the interfaces available in 0.8.0-0.9.6 + * (virDomainSnapshotListNames, global list only) and in + * 0.9.7-0.9.12 (addition of virDomainSnapshotListChildrenNames + * for child listing, and new flags), as follows, with [*] by the + * combinations that need parent info (either for filtering + * purposes or for the resulting tree listing): + * old new + * list global as-is global as-is + * list --roots *global + filter global + flags + * list --from *global + filter child as-is + * list --from --descendants *global + filter child + flags + * list --tree *global as-is *global as-is + * list --tree --from *global + filter *child + flags + * + * Additionally, when --tree and --from are both used, from is + * added to the final list as the only element without a parent. + * Otherwise, --from does not appear in the final list. + */ + if (from) { + fromname = virDomainSnapshotGetName(from); + if (!fromname) { + vshError(ctl, "%s", _("Could not get snapshot name")); + goto cleanup; + } + descendants = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) || tree; + if (tree) + flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; + + /* Determine if we can use the new child listing API. */ + if (ctl->useSnapshotOld || + ((count = virDomainSnapshotNumChildren(from, flags)) < 0 && + last_error->code == VIR_ERR_NO_SUPPORT)) { + /* We can emulate --from. */ + /* XXX can we also emulate --leaves? */ + virFreeError(last_error); + last_error = NULL; + ctl->useSnapshotOld = true; + flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; + goto global; + } + if (tree && count >= 0) + count++; + } else { + global: + /* Global listing (including fallback when --from failed with + * child listing). */ + count = virDomainSnapshotNum(dom, flags); + + /* Fall back to simulation if --roots was unsupported. */ + /* XXX can we also emulate --leaves? */ + if (!from && count < 0 && last_error->code == VIR_ERR_INVALID_ARG && + (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS)) { + virFreeError(last_error); + last_error = NULL; + roots = true; + flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_ROOTS; + count = virDomainSnapshotNum(dom, flags); + } + } + + if (count < 0) { + if (!last_error) + vshError(ctl, _("failed to collect snapshot list")); + goto cleanup; + } + + if (!count) + goto success; + + names = vshCalloc(ctl, sizeof(*names), count); + + /* Now that we have a count, collect the list. */ + if (from && !ctl->useSnapshotOld) { + if (tree) { + if (count) + count = virDomainSnapshotListChildrenNames(from, names + 1, + count - 1, flags); + if (count >= 0) { + count++; + names[0] = vshStrdup(ctl, fromname); + } + } else { + count = virDomainSnapshotListChildrenNames(from, names, + count, flags); + } + } else { + count = virDomainSnapshotListNames(dom, names, count, flags); + } + if (count < 0) + goto cleanup; + + snaplist->snaps = vshCalloc(ctl, sizeof(*snaplist->snaps), count); + snaplist->nsnaps = count; + for (i = 0; i < count; i++) { + snaplist->snaps[i].snap = virDomainSnapshotLookupByName(dom, + names[i], 0); + if (!snaplist->snaps[i].snap) + goto cleanup; + } + + /* Collect parents when needed. With the new API, --tree and + * --from together put from as the first element without a parent; + * with the old API we still need to do a post-process filtering + * based on all parent information. */ + if (tree || (from && ctl->useSnapshotOld) || roots) { + for (i = (from && !ctl->useSnapshotOld); i < count; i++) { + if (from && ctl->useSnapshotOld && STREQ(names[i], fromname)) { + start_index = i; + if (tree) + continue; + } + if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap, + &snaplist->snaps[i].parent) < 0) + goto cleanup; + if ((from && ((tree && !snaplist->snaps[i].parent) || + (!descendants && + STRNEQ_NULLABLE(fromname, + snaplist->snaps[i].parent)))) || + (roots && snaplist->snaps[i].parent)) { + virDomainSnapshotFree(snaplist->snaps[i].snap); + snaplist->snaps[i].snap = NULL; + VIR_FREE(snaplist->snaps[i].parent); + deleted++; + } + } + } + if (tree) + goto success; + + if (ctl->useSnapshotOld && descendants) { + bool changed = false; + bool remaining = false; + + /* Make multiple passes over the list - first pass finds + * direct children and NULLs out all roots and from, remaining + * passes NULL out any undecided entry whose parent is not + * still in list. We mark known descendants by clearing + * snaps[i].parents. Sorry, this is O(n^3) - hope your + * hierarchy isn't huge. XXX Is it worth making O(n^2 log n) + * by using qsort and bsearch? */ + if (start_index < 0) { + vshError(ctl, _("snapshot %s disappeared from list"), fromname); + goto cleanup; + } + for (i = 0; i < count; i++) { + if (i == start_index || !snaplist->snaps[i].parent) { + VIR_FREE(names[i]); + virDomainSnapshotFree(snaplist->snaps[i].snap); + snaplist->snaps[i].snap = NULL; + VIR_FREE(snaplist->snaps[i].parent); + deleted++; + } else if (STREQ(snaplist->snaps[i].parent, fromname)) { + VIR_FREE(snaplist->snaps[i].parent); + changed = true; + } else { + remaining = true; + } + } + if (!changed) { + ret = vshMalloc(ctl, sizeof(*snaplist)); + goto cleanup; + } + while (changed && remaining) { + changed = remaining = false; + for (i = 0; i < count; i++) { + bool found_parent = false; + int j; + + if (!names[i] || !snaplist->snaps[i].parent) + continue; + for (j = 0; j < count; j++) { + if (!names[j] || i == j) + continue; + if (STREQ(snaplist->snaps[i].parent, names[j])) { + found_parent = true; + if (!snaplist->snaps[j].parent) + VIR_FREE(snaplist->snaps[i].parent); + else + remaining = true; + break; + } + } + if (!found_parent) { + changed = true; + VIR_FREE(names[i]); + virDomainSnapshotFree(snaplist->snaps[i].snap); + snaplist->snaps[i].snap = NULL; + VIR_FREE(snaplist->snaps[i].parent); + deleted++; + } + } + } + } + +success: + qsort(snaplist->snaps, snaplist->nsnaps, sizeof(*snaplist->snaps), + vshSnapSorter); + snaplist->nsnaps -= deleted; + + ret = snaplist; + snaplist = NULL; + +cleanup: + vshSnapshotListFree(snaplist); + if (names) + for (i = 0; i < count; i++) + VIR_FREE(names[i]); + VIR_FREE(names); + return ret; +} + +static const char * +vshSnapshotListLookup(int id, bool parent, void *opaque) +{ + vshSnapshotListPtr snaplist = opaque; + if (parent) + return snaplist->snaps[id].parent; + return virDomainSnapshotGetName(snaplist->snaps[id].snap); +} + +/* + * "snapshot-list" command + */ +static const vshCmdInfo info_snapshot_list[] = { + {"help", N_("List snapshots for a domain")}, + {"desc", N_("Snapshot List")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_list[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"parent", VSH_OT_BOOL, 0, N_("add a column showing parent snapshot")}, + {"roots", VSH_OT_BOOL, 0, N_("list only snapshots without parents")}, + {"leaves", VSH_OT_BOOL, 0, N_("list only snapshots without children")}, + {"no-leaves", VSH_OT_BOOL, 0, + N_("list only snapshots that are not leaves (with children)")}, + {"metadata", VSH_OT_BOOL, 0, + N_("list only snapshots that have metadata that would prevent undefine")}, + {"no-metadata", VSH_OT_BOOL, 0, + N_("list only snapshots that have no metadata managed by libvirt")}, + {"tree", VSH_OT_BOOL, 0, N_("list snapshots in a tree")}, + {"from", VSH_OT_DATA, 0, N_("limit list to children of given snapshot")}, + {"current", VSH_OT_BOOL, 0, + N_("limit list to children of current snapshot")}, + {"descendants", VSH_OT_BOOL, 0, N_("with --from, list all descendants")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotList(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + unsigned int flags = 0; + bool show_parent = false; + int i; + xmlDocPtr xml = NULL; + xmlXPathContextPtr ctxt = NULL; + char *doc = NULL; + virDomainSnapshotPtr snapshot = NULL; + char *state = NULL; + char *parent = NULL; + long long creation_longlong; + time_t creation_time_t; + char timestr[100]; + struct tm time_info; + bool tree = vshCommandOptBool(cmd, "tree"); + bool leaves = vshCommandOptBool(cmd, "leaves"); + bool no_leaves = vshCommandOptBool(cmd, "no-leaves"); + const char *from = NULL; + virDomainSnapshotPtr start = NULL; + vshSnapshotListPtr snaplist = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if ((vshCommandOptBool(cmd, "from") || + vshCommandOptBool(cmd, "current")) && + vshLookupSnapshot(ctl, cmd, "from", true, dom, &start, &from) < 0) + goto cleanup; + + if (vshCommandOptBool(cmd, "parent")) { + if (vshCommandOptBool(cmd, "roots")) { + vshError(ctl, "%s", + _("--parent and --roots are mutually exclusive")); + goto cleanup; + } + if (tree) { + vshError(ctl, "%s", + _("--parent and --tree are mutually exclusive")); + goto cleanup; + } + show_parent = true; + } else if (vshCommandOptBool(cmd, "roots")) { + if (tree) { + vshError(ctl, "%s", + _("--roots and --tree are mutually exclusive")); + goto cleanup; + } + if (from) { + vshError(ctl, "%s", + _("--roots and --from are mutually exclusive")); + goto cleanup; + } + flags |= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS; + } + if (leaves) { + if (tree) { + vshError(ctl, "%s", + _("--leaves and --tree are mutually exclusive")); + goto cleanup; + } + flags |= VIR_DOMAIN_SNAPSHOT_LIST_LEAVES; + } + if (no_leaves) { + if (tree) { + vshError(ctl, "%s", + _("--no-leaves and --tree are mutually exclusive")); + goto cleanup; + } + flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES; + } + + if (vshCommandOptBool(cmd, "metadata")) { + flags |= VIR_DOMAIN_SNAPSHOT_LIST_METADATA; + } + if (vshCommandOptBool(cmd, "no-metadata")) { + flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA; + } + + if (vshCommandOptBool(cmd, "descendants")) { + if (!from) { + vshError(ctl, "%s", + _("--descendants requires either --from or --current")); + goto cleanup; + } + flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; + } + + if ((snaplist = vshSnapshotListCollect(ctl, dom, start, flags, + tree)) == NULL) + goto cleanup; + + if (!tree) { + if (show_parent) + vshPrintExtra(ctl, " %-20s %-25s %-15s %s", + _("Name"), _("Creation Time"), _("State"), + _("Parent")); + else + vshPrintExtra(ctl, " %-20s %-25s %s", + _("Name"), _("Creation Time"), _("State")); + vshPrintExtra(ctl, "\n" +"------------------------------------------------------------\n"); + } + + if (!snaplist->nsnaps) { + ret = true; + goto cleanup; + } + + if (tree) { + for (i = 0; i < snaplist->nsnaps; i++) { + if (!snaplist->snaps[i].parent && + vshTreePrint(ctl, vshSnapshotListLookup, snaplist, + snaplist->nsnaps, i) < 0) + goto cleanup; + } + ret = true; + goto cleanup; + } + + for (i = 0; i < snaplist->nsnaps; i++) { + const char *name; + + /* free up memory from previous iterations of the loop */ + VIR_FREE(parent); + VIR_FREE(state); + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml); + VIR_FREE(doc); + + snapshot = snaplist->snaps[i].snap; + name = virDomainSnapshotGetName(snapshot); + assert(name); + + doc = virDomainSnapshotGetXMLDesc(snapshot, 0); + if (!doc) + continue; + + xml = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt); + if (!xml) + continue; + + if (show_parent) + parent = virXPathString("string(/domainsnapshot/parent/name)", + ctxt); + + state = virXPathString("string(/domainsnapshot/state)", ctxt); + if (state == NULL) + continue; + if (virXPathLongLong("string(/domainsnapshot/creationTime)", ctxt, + &creation_longlong) < 0) + continue; + creation_time_t = creation_longlong; + if (creation_time_t != creation_longlong) { + vshError(ctl, "%s", _("time_t overflow")); + continue; + } + localtime_r(&creation_time_t, &time_info); + strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S %z", + &time_info); + + if (parent) + vshPrint(ctl, " %-20s %-25s %-15s %s\n", + name, timestr, state, parent); + else + vshPrint(ctl, " %-20s %-25s %s\n", name, timestr, state); + } + + ret = true; + +cleanup: + /* this frees up memory from the last iteration of the loop */ + vshSnapshotListFree(snaplist); + VIR_FREE(parent); + VIR_FREE(state); + if (start) + virDomainSnapshotFree(start); + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml); + VIR_FREE(doc); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "snapshot-dumpxml" command + */ +static const vshCmdInfo info_snapshot_dumpxml[] = { + {"help", N_("Dump XML for a domain snapshot")}, + {"desc", N_("Snapshot Dump XML")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_dumpxml[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, VSH_OFLAG_REQ, N_("snapshot name")}, + {"security-info", VSH_OT_BOOL, 0, + N_("include security sensitive information in XML dump")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + const char *name = NULL; + virDomainSnapshotPtr snapshot = NULL; + char *xml = NULL; + unsigned int flags = 0; + + if (vshCommandOptBool(cmd, "security-info")) + flags |= VIR_DOMAIN_XML_SECURE; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshCommandOptString(cmd, "snapshotname", &name) <= 0) + goto cleanup; + + snapshot = virDomainSnapshotLookupByName(dom, name, 0); + if (snapshot == NULL) + goto cleanup; + + xml = virDomainSnapshotGetXMLDesc(snapshot, flags); + if (!xml) + goto cleanup; + + vshPrint(ctl, "%s", xml); + + ret = true; + +cleanup: + VIR_FREE(xml); + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "snapshot-parent" command + */ +static const vshCmdInfo info_snapshot_parent[] = { + {"help", N_("Get the name of the parent of a snapshot")}, + {"desc", N_("Extract the snapshot's parent, if any")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_parent[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, 0, N_("find parent of snapshot name")}, + {"current", VSH_OT_BOOL, 0, N_("find parent of current snapshot")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotParent(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + const char *name = NULL; + virDomainSnapshotPtr snapshot = NULL; + char *parent = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, + &snapshot, &name) < 0) + goto cleanup; + + if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0) + goto cleanup; + if (!parent) { + vshError(ctl, _("snapshot '%s' has no parent"), name); + goto cleanup; + } + + vshPrint(ctl, "%s", parent); + + ret = true; + +cleanup: + VIR_FREE(parent); + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "snapshot-revert" command + */ +static const vshCmdInfo info_snapshot_revert[] = { + {"help", N_("Revert a domain to a snapshot")}, + {"desc", N_("Revert domain to snapshot")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_revert[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, + {"current", VSH_OT_BOOL, 0, N_("revert to current snapshot")}, + {"running", VSH_OT_BOOL, 0, N_("after reverting, change state to running")}, + {"paused", VSH_OT_BOOL, 0, N_("after reverting, change state to paused")}, + {"force", VSH_OT_BOOL, 0, N_("try harder on risky reverts")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdDomainSnapshotRevert(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + const char *name = NULL; + virDomainSnapshotPtr snapshot = NULL; + unsigned int flags = 0; + bool force = false; + int result; + + if (vshCommandOptBool(cmd, "running")) + flags |= VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING; + if (vshCommandOptBool(cmd, "paused")) + flags |= VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED; + /* We want virsh snapshot-revert --force to work even when talking + * to older servers that did the unsafe revert by default but + * reject the flag, so we probe without the flag, and only use it + * when the error says it will make a difference. */ + if (vshCommandOptBool(cmd, "force")) + force = true; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, + &snapshot, &name) < 0) + goto cleanup; + + result = virDomainRevertToSnapshot(snapshot, flags); + if (result < 0 && force && + last_error->code == VIR_ERR_SNAPSHOT_REVERT_RISKY) { + flags |= VIR_DOMAIN_SNAPSHOT_REVERT_FORCE; + virFreeError(last_error); + last_error = NULL; + result = virDomainRevertToSnapshot(snapshot, flags); + } + if (result < 0) + goto cleanup; + + ret = true; + +cleanup: + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "snapshot-delete" command + */ +static const vshCmdInfo info_snapshot_delete[] = { + {"help", N_("Delete a domain snapshot")}, + {"desc", N_("Snapshot Delete")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_snapshot_delete[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, + {"current", VSH_OT_BOOL, 0, N_("delete current snapshot")}, + {"children", VSH_OT_BOOL, 0, N_("delete snapshot and all children")}, + {"children-only", VSH_OT_BOOL, 0, N_("delete children but not snapshot")}, + {"metadata", VSH_OT_BOOL, 0, + N_("delete only libvirt metadata, leaving snapshot contents behind")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdSnapshotDelete(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + const char *name = NULL; + virDomainSnapshotPtr snapshot = NULL; + unsigned int flags = 0; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, + &snapshot, &name) < 0) + goto cleanup; + + if (vshCommandOptBool(cmd, "children")) + flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN; + if (vshCommandOptBool(cmd, "children-only")) + flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY; + if (vshCommandOptBool(cmd, "metadata")) + flags |= VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY; + + /* XXX If we wanted, we could emulate DELETE_CHILDREN_ONLY even on + * older servers that reject the flag, by manually computing the + * list of descendants. But that's a lot of code to maintain. */ + if (virDomainSnapshotDelete(snapshot, flags) == 0) { + if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) + vshPrint(ctl, _("Domain snapshot %s children deleted\n"), name); + else + vshPrint(ctl, _("Domain snapshot %s deleted\n"), name); + } else { + vshError(ctl, _("Failed to delete snapshot %s"), name); + goto cleanup; + } + + ret = true; + +cleanup: + if (snapshot) + virDomainSnapshotFree(snapshot); + if (dom) + virDomainFree(dom); + + return ret; +} diff --git a/tools/virsh.c b/tools/virsh.c index cddb6e3..96e9b34 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -2149,1586 +2149,6 @@ cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) return true; } -/* Helper for snapshot-create and snapshot-create-as */ -static bool -vshSnapshotCreate(vshControl *ctl, virDomainPtr dom, const char *buffer, - unsigned int flags, const char *from) -{ - bool ret = false; - virDomainSnapshotPtr snapshot; - bool halt = false; - char *doc = NULL; - xmlDocPtr xml = NULL; - xmlXPathContextPtr ctxt = NULL; - const char *name = NULL; - - snapshot = virDomainSnapshotCreateXML(dom, buffer, flags); - - /* Emulate --halt on older servers. */ - if (!snapshot && last_error->code == VIR_ERR_INVALID_ARG && - (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) { - int persistent; - - virFreeError(last_error); - last_error = NULL; - persistent = virDomainIsPersistent(dom); - if (persistent < 0) { - virshReportError(ctl); - goto cleanup; - } - if (!persistent) { - vshError(ctl, "%s", - _("cannot halt after snapshot of transient domain")); - goto cleanup; - } - if (virDomainIsActive(dom) == 1) - halt = true; - flags &= ~VIR_DOMAIN_SNAPSHOT_CREATE_HALT; - snapshot = virDomainSnapshotCreateXML(dom, buffer, flags); - } - - if (snapshot == NULL) - goto cleanup; - - if (halt && virDomainDestroy(dom) < 0) { - virshReportError(ctl); - goto cleanup; - } - - name = virDomainSnapshotGetName(snapshot); - if (!name) { - vshError(ctl, "%s", _("Could not get snapshot name")); - goto cleanup; - } - - if (from) - vshPrint(ctl, _("Domain snapshot %s created from '%s'"), name, from); - else - vshPrint(ctl, _("Domain snapshot %s created"), name); - - ret = true; - -cleanup: - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml); - if (snapshot) - virDomainSnapshotFree(snapshot); - VIR_FREE(doc); - return ret; -} - -/* - * "snapshot-create" command - */ -static const vshCmdInfo info_snapshot_create[] = { - {"help", N_("Create a snapshot from XML")}, - {"desc", N_("Create a snapshot (disk and RAM) from XML")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_create[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"xmlfile", VSH_OT_DATA, 0, N_("domain snapshot XML")}, - {"redefine", VSH_OT_BOOL, 0, N_("redefine metadata for existing snapshot")}, - {"current", VSH_OT_BOOL, 0, N_("with redefine, set current snapshot")}, - {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")}, - {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")}, - {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")}, - {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")}, - {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")}, - {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotCreate(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - const char *from = NULL; - char *buffer = NULL; - unsigned int flags = 0; - - if (vshCommandOptBool(cmd, "redefine")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE; - if (vshCommandOptBool(cmd, "current")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT; - if (vshCommandOptBool(cmd, "no-metadata")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA; - if (vshCommandOptBool(cmd, "halt")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT; - if (vshCommandOptBool(cmd, "disk-only")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; - if (vshCommandOptBool(cmd, "reuse-external")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT; - if (vshCommandOptBool(cmd, "quiesce")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE; - if (vshCommandOptBool(cmd, "atomic")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshCommandOptString(cmd, "xmlfile", &from) <= 0) - buffer = vshStrdup(ctl, "<domainsnapshot/>"); - else { - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) { - /* we have to report the error here because during cleanup - * we'll run through virDomainFree(), which loses the - * last error - */ - virshReportError(ctl); - goto cleanup; - } - } - if (buffer == NULL) { - vshError(ctl, "%s", _("Out of memory")); - goto cleanup; - } - - ret = vshSnapshotCreate(ctl, dom, buffer, flags, from); - -cleanup: - VIR_FREE(buffer); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "snapshot-create-as" command - */ -static int -vshParseSnapshotDiskspec(vshControl *ctl, virBufferPtr buf, const char *str) -{ - int ret = -1; - char *name = NULL; - char *snapshot = NULL; - char *driver = NULL; - char *file = NULL; - char *spec = vshStrdup(ctl, str); - char *tmp = spec; - size_t len = strlen(str); - - if (*str == ',') - goto cleanup; - name = tmp; - while ((tmp = strchr(tmp, ','))) { - if (tmp[1] == ',') { - /* Recognize ,, as an escape for a literal comma */ - memmove(&tmp[1], &tmp[2], len - (tmp - spec) - 2 + 1); - len--; - tmp++; - continue; - } - /* Terminate previous string, look for next recognized one */ - *tmp++ = '\0'; - if (!snapshot && STRPREFIX(tmp, "snapshot=")) - snapshot = tmp + strlen("snapshot="); - else if (!driver && STRPREFIX(tmp, "driver=")) - driver = tmp + strlen("driver="); - else if (!file && STRPREFIX(tmp, "file=")) - file = tmp + strlen("file="); - else - goto cleanup; - } - - virBufferEscapeString(buf, " <disk name='%s'", name); - if (snapshot) - virBufferAsprintf(buf, " snapshot='%s'", snapshot); - if (driver || file) { - virBufferAddLit(buf, ">\n"); - if (driver) - virBufferAsprintf(buf, " <driver type='%s'/>\n", driver); - if (file) - virBufferEscapeString(buf, " <source file='%s'/>\n", file); - virBufferAddLit(buf, " </disk>\n"); - } else { - virBufferAddLit(buf, "/>\n"); - } - ret = 0; -cleanup: - if (ret < 0) - vshError(ctl, _("unable to parse diskspec: %s"), str); - VIR_FREE(spec); - return ret; -} - -static const vshCmdInfo info_snapshot_create_as[] = { - {"help", N_("Create a snapshot from a set of args")}, - {"desc", N_("Create a snapshot (disk and RAM) from arguments")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_create_as[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"name", VSH_OT_DATA, 0, N_("name of snapshot")}, - {"description", VSH_OT_DATA, 0, N_("description of snapshot")}, - {"print-xml", VSH_OT_BOOL, 0, N_("print XML document rather than create")}, - {"no-metadata", VSH_OT_BOOL, 0, N_("take snapshot but create no metadata")}, - {"halt", VSH_OT_BOOL, 0, N_("halt domain after snapshot is created")}, - {"disk-only", VSH_OT_BOOL, 0, N_("capture disk state but not vm state")}, - {"reuse-external", VSH_OT_BOOL, 0, N_("reuse any existing external files")}, - {"quiesce", VSH_OT_BOOL, 0, N_("quiesce guest's file systems")}, - {"atomic", VSH_OT_BOOL, 0, N_("require atomic operation")}, - {"diskspec", VSH_OT_ARGV, 0, - N_("disk attributes: disk[,snapshot=type][,driver=type][,file=name]")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotCreateAs(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - char *buffer = NULL; - const char *name = NULL; - const char *desc = NULL; - virBuffer buf = VIR_BUFFER_INITIALIZER; - unsigned int flags = 0; - const vshCmdOpt *opt = NULL; - - if (vshCommandOptBool(cmd, "no-metadata")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA; - if (vshCommandOptBool(cmd, "halt")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT; - if (vshCommandOptBool(cmd, "disk-only")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; - if (vshCommandOptBool(cmd, "reuse-external")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT; - if (vshCommandOptBool(cmd, "quiesce")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE; - if (vshCommandOptBool(cmd, "atomic")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshCommandOptString(cmd, "name", &name) < 0 || - vshCommandOptString(cmd, "description", &desc) < 0) { - vshError(ctl, _("argument must not be empty")); - goto cleanup; - } - - virBufferAddLit(&buf, "<domainsnapshot>\n"); - if (name) - virBufferEscapeString(&buf, " <name>%s</name>\n", name); - if (desc) - virBufferEscapeString(&buf, " <description>%s</description>\n", desc); - if (vshCommandOptBool(cmd, "diskspec")) { - virBufferAddLit(&buf, " <disks>\n"); - while ((opt = vshCommandOptArgv(cmd, opt))) { - if (vshParseSnapshotDiskspec(ctl, &buf, opt->data) < 0) { - virBufferFreeAndReset(&buf); - goto cleanup; - } - } - virBufferAddLit(&buf, " </disks>\n"); - } - virBufferAddLit(&buf, "</domainsnapshot>\n"); - - buffer = virBufferContentAndReset(&buf); - if (buffer == NULL) { - vshError(ctl, "%s", _("Out of memory")); - goto cleanup; - } - - if (vshCommandOptBool(cmd, "print-xml")) { - vshPrint(ctl, "%s\n", buffer); - ret = true; - goto cleanup; - } - - ret = vshSnapshotCreate(ctl, dom, buffer, flags, NULL); - -cleanup: - VIR_FREE(buffer); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* Helper for resolving {--current | --ARG name} into a snapshot - * belonging to DOM. If EXCLUSIVE, fail if both --current and arg are - * present. On success, populate *SNAP and *NAME, before returning 0. - * On failure, return -1 after issuing an error message. */ -static int -vshLookupSnapshot(vshControl *ctl, const vshCmd *cmd, - const char *arg, bool exclusive, virDomainPtr dom, - virDomainSnapshotPtr *snap, const char **name) -{ - bool current = vshCommandOptBool(cmd, "current"); - const char *snapname = NULL; - - if (vshCommandOptString(cmd, arg, &snapname) < 0) { - vshError(ctl, _("invalid argument for --%s"), arg); - return -1; - } - - if (exclusive && current && snapname) { - vshError(ctl, _("--%s and --current are mutually exclusive"), arg); - return -1; - } - - if (snapname) { - *snap = virDomainSnapshotLookupByName(dom, snapname, 0); - } else if (current) { - *snap = virDomainSnapshotCurrent(dom, 0); - } else { - vshError(ctl, _("--%s or --current is required"), arg); - return -1; - } - if (!*snap) { - virshReportError(ctl); - return -1; - } - - *name = virDomainSnapshotGetName(*snap); - return 0; -} - -/* - * "snapshot-edit" command - */ -static const vshCmdInfo info_snapshot_edit[] = { - {"help", N_("edit XML for a snapshot")}, - {"desc", N_("Edit the domain snapshot XML for a named snapshot")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_edit[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, - {"current", VSH_OT_BOOL, 0, N_("also set edited snapshot as current")}, - {"rename", VSH_OT_BOOL, 0, N_("allow renaming an existing snapshot")}, - {"clone", VSH_OT_BOOL, 0, N_("allow cloning to new name")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotEdit(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - virDomainSnapshotPtr snapshot = NULL; - virDomainSnapshotPtr edited = NULL; - const char *name; - const char *edited_name; - bool ret = false; - unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE; - unsigned int define_flags = VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE; - bool rename_okay = vshCommandOptBool(cmd, "rename"); - bool clone_okay = vshCommandOptBool(cmd, "clone"); - - if (rename_okay && clone_okay) { - vshError(ctl, "%s", - _("--rename and --clone are mutually exclusive")); - return false; - } - - if (vshCommandOptBool(cmd, "current") && - vshCommandOptBool(cmd, "snapshotname")) - define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshLookupSnapshot(ctl, cmd, "snapshotname", false, dom, - &snapshot, &name) < 0) - goto cleanup; - -#define EDIT_GET_XML \ - virDomainSnapshotGetXMLDesc(snapshot, getxml_flags) -#define EDIT_NOT_CHANGED \ - /* Depending on flags, we re-edit even if XML is unchanged. */ \ - if (!(define_flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) { \ - vshPrint(ctl, \ - _("Snapshot %s XML configuration not changed.\n"), \ - name); \ - ret = true; \ - goto cleanup; \ - } -#define EDIT_DEFINE \ - (strstr(doc, "<state>disk-snapshot</state>") ? \ - define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY : 0), \ - edited = virDomainSnapshotCreateXML(dom, doc_edited, define_flags) -#define EDIT_FREE \ - if (edited) \ - virDomainSnapshotFree(edited); -#include "virsh-edit.c" - - edited_name = virDomainSnapshotGetName(edited); - if (STREQ(name, edited_name)) { - vshPrint(ctl, _("Snapshot %s edited.\n"), name); - } else if (clone_okay) { - vshPrint(ctl, _("Snapshot %s cloned to %s.\n"), name, - edited_name); - } else { - unsigned int delete_flags; - - delete_flags = VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY; - if (virDomainSnapshotDelete(rename_okay ? snapshot : edited, - delete_flags) < 0) { - virshReportError(ctl); - vshError(ctl, _("Failed to clean up %s"), - rename_okay ? name : edited_name); - goto cleanup; - } - if (!rename_okay) { - vshError(ctl, _("Must use --rename or --clone to change %s to %s"), - name, edited_name); - goto cleanup; - } - } - - ret = true; - -cleanup: - if (edited) - virDomainSnapshotFree(edited); - else - vshError(ctl, _("Failed to update %s"), name); - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - return ret; -} - -/* - * "snapshot-current" command - */ -static const vshCmdInfo info_snapshot_current[] = { - {"help", N_("Get or set the current snapshot")}, - {"desc", N_("Get or set the current snapshot")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_current[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"name", VSH_OT_BOOL, 0, N_("list the name, rather than the full xml")}, - {"security-info", VSH_OT_BOOL, 0, - N_("include security sensitive information in XML dump")}, - {"snapshotname", VSH_OT_DATA, 0, - N_("name of existing snapshot to make current")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotCurrent(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - int current; - virDomainSnapshotPtr snapshot = NULL; - char *xml = NULL; - const char *snapshotname = NULL; - unsigned int flags = 0; - const char *domname; - - if (vshCommandOptBool(cmd, "security-info")) - flags |= VIR_DOMAIN_XML_SECURE; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, &domname); - if (dom == NULL) - goto cleanup; - - if (vshCommandOptString(cmd, "snapshotname", &snapshotname) < 0) { - vshError(ctl, _("invalid snapshotname argument '%s'"), snapshotname); - goto cleanup; - } - if (snapshotname) { - virDomainSnapshotPtr snapshot2 = NULL; - flags = (VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE | - VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT); - - if (vshCommandOptBool(cmd, "name")) { - vshError(ctl, "%s", - _("--name and snapshotname are mutually exclusive")); - goto cleanup; - } - snapshot = virDomainSnapshotLookupByName(dom, snapshotname, 0); - if (snapshot == NULL) - goto cleanup; - xml = virDomainSnapshotGetXMLDesc(snapshot, VIR_DOMAIN_XML_SECURE); - if (!xml) - goto cleanup; - /* strstr is safe here, since xml came from libvirt API and not user */ - if (strstr(xml, "<state>disk-snapshot</state>")) - flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY; - snapshot2 = virDomainSnapshotCreateXML(dom, xml, flags); - if (snapshot2 == NULL) - goto cleanup; - virDomainSnapshotFree(snapshot2); - vshPrint(ctl, _("Snapshot %s set as current"), snapshotname); - ret = true; - goto cleanup; - } - - current = virDomainHasCurrentSnapshot(dom, 0); - if (current < 0) { - goto cleanup; - } else if (!current) { - vshError(ctl, _("domain '%s' has no current snapshot"), domname); - goto cleanup; - } else { - const char *name = NULL; - - if (!(snapshot = virDomainSnapshotCurrent(dom, 0))) - goto cleanup; - - if (vshCommandOptBool(cmd, "name")) { - name = virDomainSnapshotGetName(snapshot); - if (!name) - goto cleanup; - } else { - xml = virDomainSnapshotGetXMLDesc(snapshot, flags); - if (!xml) - goto cleanup; - } - - vshPrint(ctl, "%s", name ? name : xml); - } - - ret = true; - -cleanup: - if (!ret) - virshReportError(ctl); - VIR_FREE(xml); - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* Helper function to get the name of a snapshot's parent. Caller - * must free the result. Returns 0 on success (including when it was - * proven no parent exists), and -1 on failure with error reported - * (such as no snapshot support or domain deleted in meantime). */ -static int -vshGetSnapshotParent(vshControl *ctl, virDomainSnapshotPtr snapshot, - char **parent_name) -{ - virDomainSnapshotPtr parent = NULL; - char *xml = NULL; - xmlDocPtr xmldoc = NULL; - xmlXPathContextPtr ctxt = NULL; - int ret = -1; - - *parent_name = NULL; - - /* Try new API, since it is faster. */ - if (!ctl->useSnapshotOld) { - parent = virDomainSnapshotGetParent(snapshot, 0); - if (parent) { - /* API works, and virDomainSnapshotGetName will succeed */ - *parent_name = vshStrdup(ctl, virDomainSnapshotGetName(parent)); - ret = 0; - goto cleanup; - } - if (last_error->code == VIR_ERR_NO_DOMAIN_SNAPSHOT) { - /* API works, and we found a root with no parent */ - ret = 0; - goto cleanup; - } - /* API didn't work, fall back to XML scraping. */ - ctl->useSnapshotOld = true; - } - - xml = virDomainSnapshotGetXMLDesc(snapshot, 0); - if (!xml) - goto cleanup; - - xmldoc = virXMLParseStringCtxt(xml, _("(domain_snapshot)"), &ctxt); - if (!xmldoc) - goto cleanup; - - *parent_name = virXPathString("string(/domainsnapshot/parent/name)", ctxt); - ret = 0; - -cleanup: - if (ret < 0) { - virshReportError(ctl); - vshError(ctl, "%s", _("unable to determine if snapshot has parent")); - } else { - virFreeError(last_error); - last_error = NULL; - } - if (parent) - virDomainSnapshotFree(parent); - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xmldoc); - VIR_FREE(xml); - return ret; -} - -/* - * "snapshot-info" command - */ -static const vshCmdInfo info_snapshot_info[] = { - {"help", N_("snapshot information")}, - {"desc", N_("Returns basic information about a snapshot.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_info[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, - {"current", VSH_OT_BOOL, 0, N_("info on current snapshot")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotInfo(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom; - virDomainSnapshotPtr snapshot = NULL; - const char *name; - char *doc = NULL; - char *tmp; - char *parent = NULL; - bool ret = false; - int count; - unsigned int flags; - int current; - int metadata; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - return false; - - if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, - &snapshot, &name) < 0) - goto cleanup; - - vshPrint(ctl, "%-15s %s\n", _("Name:"), name); - vshPrint(ctl, "%-15s %s\n", _("Domain:"), virDomainGetName(dom)); - - /* Determine if snapshot is current; this is useful enough that we - * attempt a fallback. */ - current = virDomainSnapshotIsCurrent(snapshot, 0); - if (current < 0) { - virDomainSnapshotPtr other = virDomainSnapshotCurrent(dom, 0); - - virResetLastError(); - current = 0; - if (other) { - if (STREQ(name, virDomainSnapshotGetName(other))) - current = 1; - virDomainSnapshotFree(other); - } - } - vshPrint(ctl, "%-15s %s\n", _("Current:"), - current > 0 ? _("yes") : _("no")); - - /* Get the XML configuration of the snapshot to determine the - * state of the machine at the time of the snapshot. */ - doc = virDomainSnapshotGetXMLDesc(snapshot, 0); - if (!doc) - goto cleanup; - - tmp = strstr(doc, "<state>"); - if (!tmp) { - vshError(ctl, "%s", - _("unexpected problem reading snapshot xml")); - goto cleanup; - } - tmp += strlen("<state>"); - vshPrint(ctl, "%-15s %.*s\n", _("State:"), - (int) (strchr(tmp, '<') - tmp), tmp); - - if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0) - goto cleanup; - vshPrint(ctl, "%-15s %s\n", _("Parent:"), parent ? parent : "-"); - - /* Children, Descendants. After this point, the fallback to - * compute children is too expensive, so we gracefully quit if the - * APIs don't exist. */ - if (ctl->useSnapshotOld) { - ret = true; - goto cleanup; - } - flags = 0; - count = virDomainSnapshotNumChildren(snapshot, flags); - if (count < 0) - goto cleanup; - vshPrint(ctl, "%-15s %d\n", _("Children:"), count); - flags = VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; - count = virDomainSnapshotNumChildren(snapshot, flags); - if (count < 0) - goto cleanup; - vshPrint(ctl, "%-15s %d\n", _("Descendants:"), count); - - /* Metadata; the fallback here relies on the fact that metadata - * used to have an all-or-nothing effect on snapshot count. */ - metadata = virDomainSnapshotHasMetadata(snapshot, 0); - if (metadata < 0) { - metadata = virDomainSnapshotNum(dom, - VIR_DOMAIN_SNAPSHOT_LIST_METADATA); - virResetLastError(); - } - if (metadata >= 0) - vshPrint(ctl, "%-15s %s\n", _("Metadata:"), - metadata ? _("yes") : _("no")); - - ret = true; - -cleanup: - VIR_FREE(doc); - VIR_FREE(parent); - if (snapshot) - virDomainSnapshotFree(snapshot); - virDomainFree(dom); - return ret; -} - -/* Helpers for collecting a list of snapshots. */ -struct vshSnap { - virDomainSnapshotPtr snap; - char *parent; -}; -struct vshSnapshotList { - struct vshSnap *snaps; - int nsnaps; -}; -typedef struct vshSnapshotList *vshSnapshotListPtr; - -static void -vshSnapshotListFree(vshSnapshotListPtr snaplist) -{ - int i; - - if (!snaplist) - return; - if (snaplist->snaps) { - for (i = 0; i < snaplist->nsnaps; i++) { - if (snaplist->snaps[i].snap) - virDomainSnapshotFree(snaplist->snaps[i].snap); - VIR_FREE(snaplist->snaps[i].parent); - } - VIR_FREE(snaplist->snaps); - } - VIR_FREE(snaplist); -} - -static int -vshSnapSorter(const void *a, const void *b) -{ - const struct vshSnap *sa = a; - const struct vshSnap *sb = b; - - if (sa->snap && !sb->snap) - return -1; - if (!sa->snap) - return sb->snap != NULL; - - /* User visible sort, so we want locale-specific case comparison. */ - return strcasecmp(virDomainSnapshotGetName(sa->snap), - virDomainSnapshotGetName(sb->snap)); -} - -/* Compute a list of snapshots from DOM. If FROM is provided, the - * list is limited to descendants of the given snapshot. If FLAGS is - * given, the list is filtered. If TREE is specified, then all but - * FROM or the roots will also have parent information. */ -static vshSnapshotListPtr -vshSnapshotListCollect(vshControl *ctl, virDomainPtr dom, - virDomainSnapshotPtr from, - unsigned int flags, bool tree) -{ - int i; - char **names = NULL; - int count = -1; - bool descendants = false; - bool roots = false; - virDomainSnapshotPtr *snaps; - vshSnapshotListPtr snaplist = vshMalloc(ctl, sizeof(*snaplist)); - vshSnapshotListPtr ret = NULL; - const char *fromname = NULL; - int start_index = -1; - int deleted = 0; - - /* Try the interface available in 0.9.13 and newer. */ - if (!ctl->useSnapshotOld) { - if (from) - count = virDomainSnapshotListAllChildren(from, &snaps, flags); - else - count = virDomainListAllSnapshots(dom, &snaps, flags); - } - if (count >= 0) { - /* When mixing --from and --tree, we also want a copy of from - * in the list, but with no parent for that one entry. */ - snaplist->snaps = vshCalloc(ctl, count + (tree && from), - sizeof(*snaplist->snaps)); - snaplist->nsnaps = count; - for (i = 0; i < count; i++) - snaplist->snaps[i].snap = snaps[i]; - VIR_FREE(snaps); - if (tree) { - for (i = 0; i < count; i++) { - if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap, - &snaplist->snaps[i].parent) < 0) - goto cleanup; - } - if (from) { - snaps[snaplist->nsnaps++] = from; - virDomainSnapshotRef(from); - } - } - goto success; - } - - /* Assume that if we got this far, then the --no-leaves and - * --no-metadata flags were not supported. Disable groups that - * have no impact. */ - /* XXX should we emulate --no-leaves? */ - if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES && - flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) - flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES | - VIR_DOMAIN_SNAPSHOT_LIST_LEAVES); - if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA && - flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) - flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA | - VIR_DOMAIN_SNAPSHOT_LIST_METADATA); - if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA) { - /* We can emulate --no-metadata if --metadata was supported, - * since it was an all-or-none attribute on old servers. */ - count = virDomainSnapshotNum(dom, - VIR_DOMAIN_SNAPSHOT_LIST_METADATA); - if (count < 0) - goto cleanup; - if (count > 0) - return snaplist; - flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA; - } - - /* This uses the interfaces available in 0.8.0-0.9.6 - * (virDomainSnapshotListNames, global list only) and in - * 0.9.7-0.9.12 (addition of virDomainSnapshotListChildrenNames - * for child listing, and new flags), as follows, with [*] by the - * combinations that need parent info (either for filtering - * purposes or for the resulting tree listing): - * old new - * list global as-is global as-is - * list --roots *global + filter global + flags - * list --from *global + filter child as-is - * list --from --descendants *global + filter child + flags - * list --tree *global as-is *global as-is - * list --tree --from *global + filter *child + flags - * - * Additionally, when --tree and --from are both used, from is - * added to the final list as the only element without a parent. - * Otherwise, --from does not appear in the final list. - */ - if (from) { - fromname = virDomainSnapshotGetName(from); - if (!fromname) { - vshError(ctl, "%s", _("Could not get snapshot name")); - goto cleanup; - } - descendants = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) || tree; - if (tree) - flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; - - /* Determine if we can use the new child listing API. */ - if (ctl->useSnapshotOld || - ((count = virDomainSnapshotNumChildren(from, flags)) < 0 && - last_error->code == VIR_ERR_NO_SUPPORT)) { - /* We can emulate --from. */ - /* XXX can we also emulate --leaves? */ - virFreeError(last_error); - last_error = NULL; - ctl->useSnapshotOld = true; - flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; - goto global; - } - if (tree && count >= 0) - count++; - } else { - global: - /* Global listing (including fallback when --from failed with - * child listing). */ - count = virDomainSnapshotNum(dom, flags); - - /* Fall back to simulation if --roots was unsupported. */ - /* XXX can we also emulate --leaves? */ - if (!from && count < 0 && last_error->code == VIR_ERR_INVALID_ARG && - (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS)) { - virFreeError(last_error); - last_error = NULL; - roots = true; - flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_ROOTS; - count = virDomainSnapshotNum(dom, flags); - } - } - - if (count < 0) { - if (!last_error) - vshError(ctl, _("failed to collect snapshot list")); - goto cleanup; - } - - if (!count) - goto success; - - names = vshCalloc(ctl, sizeof(*names), count); - - /* Now that we have a count, collect the list. */ - if (from && !ctl->useSnapshotOld) { - if (tree) { - if (count) - count = virDomainSnapshotListChildrenNames(from, names + 1, - count - 1, flags); - if (count >= 0) { - count++; - names[0] = vshStrdup(ctl, fromname); - } - } else { - count = virDomainSnapshotListChildrenNames(from, names, - count, flags); - } - } else { - count = virDomainSnapshotListNames(dom, names, count, flags); - } - if (count < 0) - goto cleanup; - - snaplist->snaps = vshCalloc(ctl, sizeof(*snaplist->snaps), count); - snaplist->nsnaps = count; - for (i = 0; i < count; i++) { - snaplist->snaps[i].snap = virDomainSnapshotLookupByName(dom, - names[i], 0); - if (!snaplist->snaps[i].snap) - goto cleanup; - } - - /* Collect parents when needed. With the new API, --tree and - * --from together put from as the first element without a parent; - * with the old API we still need to do a post-process filtering - * based on all parent information. */ - if (tree || (from && ctl->useSnapshotOld) || roots) { - for (i = (from && !ctl->useSnapshotOld); i < count; i++) { - if (from && ctl->useSnapshotOld && STREQ(names[i], fromname)) { - start_index = i; - if (tree) - continue; - } - if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap, - &snaplist->snaps[i].parent) < 0) - goto cleanup; - if ((from && ((tree && !snaplist->snaps[i].parent) || - (!descendants && - STRNEQ_NULLABLE(fromname, - snaplist->snaps[i].parent)))) || - (roots && snaplist->snaps[i].parent)) { - virDomainSnapshotFree(snaplist->snaps[i].snap); - snaplist->snaps[i].snap = NULL; - VIR_FREE(snaplist->snaps[i].parent); - deleted++; - } - } - } - if (tree) - goto success; - - if (ctl->useSnapshotOld && descendants) { - bool changed = false; - bool remaining = false; - - /* Make multiple passes over the list - first pass finds - * direct children and NULLs out all roots and from, remaining - * passes NULL out any undecided entry whose parent is not - * still in list. We mark known descendants by clearing - * snaps[i].parents. Sorry, this is O(n^3) - hope your - * hierarchy isn't huge. XXX Is it worth making O(n^2 log n) - * by using qsort and bsearch? */ - if (start_index < 0) { - vshError(ctl, _("snapshot %s disappeared from list"), fromname); - goto cleanup; - } - for (i = 0; i < count; i++) { - if (i == start_index || !snaplist->snaps[i].parent) { - VIR_FREE(names[i]); - virDomainSnapshotFree(snaplist->snaps[i].snap); - snaplist->snaps[i].snap = NULL; - VIR_FREE(snaplist->snaps[i].parent); - deleted++; - } else if (STREQ(snaplist->snaps[i].parent, fromname)) { - VIR_FREE(snaplist->snaps[i].parent); - changed = true; - } else { - remaining = true; - } - } - if (!changed) { - ret = vshMalloc(ctl, sizeof(*snaplist)); - goto cleanup; - } - while (changed && remaining) { - changed = remaining = false; - for (i = 0; i < count; i++) { - bool found_parent = false; - int j; - - if (!names[i] || !snaplist->snaps[i].parent) - continue; - for (j = 0; j < count; j++) { - if (!names[j] || i == j) - continue; - if (STREQ(snaplist->snaps[i].parent, names[j])) { - found_parent = true; - if (!snaplist->snaps[j].parent) - VIR_FREE(snaplist->snaps[i].parent); - else - remaining = true; - break; - } - } - if (!found_parent) { - changed = true; - VIR_FREE(names[i]); - virDomainSnapshotFree(snaplist->snaps[i].snap); - snaplist->snaps[i].snap = NULL; - VIR_FREE(snaplist->snaps[i].parent); - deleted++; - } - } - } - } - -success: - qsort(snaplist->snaps, snaplist->nsnaps, sizeof(*snaplist->snaps), - vshSnapSorter); - snaplist->nsnaps -= deleted; - - ret = snaplist; - snaplist = NULL; - -cleanup: - vshSnapshotListFree(snaplist); - if (names) - for (i = 0; i < count; i++) - VIR_FREE(names[i]); - VIR_FREE(names); - return ret; -} - -static const char * -vshSnapshotListLookup(int id, bool parent, void *opaque) -{ - vshSnapshotListPtr snaplist = opaque; - if (parent) - return snaplist->snaps[id].parent; - return virDomainSnapshotGetName(snaplist->snaps[id].snap); -} - -/* - * "snapshot-list" command - */ -static const vshCmdInfo info_snapshot_list[] = { - {"help", N_("List snapshots for a domain")}, - {"desc", N_("Snapshot List")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_list[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"parent", VSH_OT_BOOL, 0, N_("add a column showing parent snapshot")}, - {"roots", VSH_OT_BOOL, 0, N_("list only snapshots without parents")}, - {"leaves", VSH_OT_BOOL, 0, N_("list only snapshots without children")}, - {"no-leaves", VSH_OT_BOOL, 0, - N_("list only snapshots that are not leaves (with children)")}, - {"metadata", VSH_OT_BOOL, 0, - N_("list only snapshots that have metadata that would prevent undefine")}, - {"no-metadata", VSH_OT_BOOL, 0, - N_("list only snapshots that have no metadata managed by libvirt")}, - {"tree", VSH_OT_BOOL, 0, N_("list snapshots in a tree")}, - {"from", VSH_OT_DATA, 0, N_("limit list to children of given snapshot")}, - {"current", VSH_OT_BOOL, 0, - N_("limit list to children of current snapshot")}, - {"descendants", VSH_OT_BOOL, 0, N_("with --from, list all descendants")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotList(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - unsigned int flags = 0; - bool show_parent = false; - int i; - xmlDocPtr xml = NULL; - xmlXPathContextPtr ctxt = NULL; - char *doc = NULL; - virDomainSnapshotPtr snapshot = NULL; - char *state = NULL; - char *parent = NULL; - long long creation_longlong; - time_t creation_time_t; - char timestr[100]; - struct tm time_info; - bool tree = vshCommandOptBool(cmd, "tree"); - bool leaves = vshCommandOptBool(cmd, "leaves"); - bool no_leaves = vshCommandOptBool(cmd, "no-leaves"); - const char *from = NULL; - virDomainSnapshotPtr start = NULL; - vshSnapshotListPtr snaplist = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if ((vshCommandOptBool(cmd, "from") || - vshCommandOptBool(cmd, "current")) && - vshLookupSnapshot(ctl, cmd, "from", true, dom, &start, &from) < 0) - goto cleanup; - - if (vshCommandOptBool(cmd, "parent")) { - if (vshCommandOptBool(cmd, "roots")) { - vshError(ctl, "%s", - _("--parent and --roots are mutually exclusive")); - goto cleanup; - } - if (tree) { - vshError(ctl, "%s", - _("--parent and --tree are mutually exclusive")); - goto cleanup; - } - show_parent = true; - } else if (vshCommandOptBool(cmd, "roots")) { - if (tree) { - vshError(ctl, "%s", - _("--roots and --tree are mutually exclusive")); - goto cleanup; - } - if (from) { - vshError(ctl, "%s", - _("--roots and --from are mutually exclusive")); - goto cleanup; - } - flags |= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS; - } - if (leaves) { - if (tree) { - vshError(ctl, "%s", - _("--leaves and --tree are mutually exclusive")); - goto cleanup; - } - flags |= VIR_DOMAIN_SNAPSHOT_LIST_LEAVES; - } - if (no_leaves) { - if (tree) { - vshError(ctl, "%s", - _("--no-leaves and --tree are mutually exclusive")); - goto cleanup; - } - flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES; - } - - if (vshCommandOptBool(cmd, "metadata")) { - flags |= VIR_DOMAIN_SNAPSHOT_LIST_METADATA; - } - if (vshCommandOptBool(cmd, "no-metadata")) { - flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA; - } - - if (vshCommandOptBool(cmd, "descendants")) { - if (!from) { - vshError(ctl, "%s", - _("--descendants requires either --from or --current")); - goto cleanup; - } - flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS; - } - - if ((snaplist = vshSnapshotListCollect(ctl, dom, start, flags, - tree)) == NULL) - goto cleanup; - - if (!tree) { - if (show_parent) - vshPrintExtra(ctl, " %-20s %-25s %-15s %s", - _("Name"), _("Creation Time"), _("State"), - _("Parent")); - else - vshPrintExtra(ctl, " %-20s %-25s %s", - _("Name"), _("Creation Time"), _("State")); - vshPrintExtra(ctl, "\n" -"------------------------------------------------------------\n"); - } - - if (!snaplist->nsnaps) { - ret = true; - goto cleanup; - } - - if (tree) { - for (i = 0; i < snaplist->nsnaps; i++) { - if (!snaplist->snaps[i].parent && - vshTreePrint(ctl, vshSnapshotListLookup, snaplist, - snaplist->nsnaps, i) < 0) - goto cleanup; - } - ret = true; - goto cleanup; - } - - for (i = 0; i < snaplist->nsnaps; i++) { - const char *name; - - /* free up memory from previous iterations of the loop */ - VIR_FREE(parent); - VIR_FREE(state); - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml); - VIR_FREE(doc); - - snapshot = snaplist->snaps[i].snap; - name = virDomainSnapshotGetName(snapshot); - assert(name); - - doc = virDomainSnapshotGetXMLDesc(snapshot, 0); - if (!doc) - continue; - - xml = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt); - if (!xml) - continue; - - if (show_parent) - parent = virXPathString("string(/domainsnapshot/parent/name)", - ctxt); - - state = virXPathString("string(/domainsnapshot/state)", ctxt); - if (state == NULL) - continue; - if (virXPathLongLong("string(/domainsnapshot/creationTime)", ctxt, - &creation_longlong) < 0) - continue; - creation_time_t = creation_longlong; - if (creation_time_t != creation_longlong) { - vshError(ctl, "%s", _("time_t overflow")); - continue; - } - localtime_r(&creation_time_t, &time_info); - strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S %z", - &time_info); - - if (parent) - vshPrint(ctl, " %-20s %-25s %-15s %s\n", - name, timestr, state, parent); - else - vshPrint(ctl, " %-20s %-25s %s\n", name, timestr, state); - } - - ret = true; - -cleanup: - /* this frees up memory from the last iteration of the loop */ - vshSnapshotListFree(snaplist); - VIR_FREE(parent); - VIR_FREE(state); - if (start) - virDomainSnapshotFree(start); - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml); - VIR_FREE(doc); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "snapshot-dumpxml" command - */ -static const vshCmdInfo info_snapshot_dumpxml[] = { - {"help", N_("Dump XML for a domain snapshot")}, - {"desc", N_("Snapshot Dump XML")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_dumpxml[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, VSH_OFLAG_REQ, N_("snapshot name")}, - {"security-info", VSH_OT_BOOL, 0, - N_("include security sensitive information in XML dump")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - const char *name = NULL; - virDomainSnapshotPtr snapshot = NULL; - char *xml = NULL; - unsigned int flags = 0; - - if (vshCommandOptBool(cmd, "security-info")) - flags |= VIR_DOMAIN_XML_SECURE; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshCommandOptString(cmd, "snapshotname", &name) <= 0) - goto cleanup; - - snapshot = virDomainSnapshotLookupByName(dom, name, 0); - if (snapshot == NULL) - goto cleanup; - - xml = virDomainSnapshotGetXMLDesc(snapshot, flags); - if (!xml) - goto cleanup; - - vshPrint(ctl, "%s", xml); - - ret = true; - -cleanup: - VIR_FREE(xml); - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "snapshot-parent" command - */ -static const vshCmdInfo info_snapshot_parent[] = { - {"help", N_("Get the name of the parent of a snapshot")}, - {"desc", N_("Extract the snapshot's parent, if any")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_parent[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, 0, N_("find parent of snapshot name")}, - {"current", VSH_OT_BOOL, 0, N_("find parent of current snapshot")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotParent(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - const char *name = NULL; - virDomainSnapshotPtr snapshot = NULL; - char *parent = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, - &snapshot, &name) < 0) - goto cleanup; - - if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0) - goto cleanup; - if (!parent) { - vshError(ctl, _("snapshot '%s' has no parent"), name); - goto cleanup; - } - - vshPrint(ctl, "%s", parent); - - ret = true; - -cleanup: - VIR_FREE(parent); - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "snapshot-revert" command - */ -static const vshCmdInfo info_snapshot_revert[] = { - {"help", N_("Revert a domain to a snapshot")}, - {"desc", N_("Revert domain to snapshot")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_revert[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, - {"current", VSH_OT_BOOL, 0, N_("revert to current snapshot")}, - {"running", VSH_OT_BOOL, 0, N_("after reverting, change state to running")}, - {"paused", VSH_OT_BOOL, 0, N_("after reverting, change state to paused")}, - {"force", VSH_OT_BOOL, 0, N_("try harder on risky reverts")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdDomainSnapshotRevert(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - const char *name = NULL; - virDomainSnapshotPtr snapshot = NULL; - unsigned int flags = 0; - bool force = false; - int result; - - if (vshCommandOptBool(cmd, "running")) - flags |= VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING; - if (vshCommandOptBool(cmd, "paused")) - flags |= VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED; - /* We want virsh snapshot-revert --force to work even when talking - * to older servers that did the unsafe revert by default but - * reject the flag, so we probe without the flag, and only use it - * when the error says it will make a difference. */ - if (vshCommandOptBool(cmd, "force")) - force = true; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, - &snapshot, &name) < 0) - goto cleanup; - - result = virDomainRevertToSnapshot(snapshot, flags); - if (result < 0 && force && - last_error->code == VIR_ERR_SNAPSHOT_REVERT_RISKY) { - flags |= VIR_DOMAIN_SNAPSHOT_REVERT_FORCE; - virFreeError(last_error); - last_error = NULL; - result = virDomainRevertToSnapshot(snapshot, flags); - } - if (result < 0) - goto cleanup; - - ret = true; - -cleanup: - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "snapshot-delete" command - */ -static const vshCmdInfo info_snapshot_delete[] = { - {"help", N_("Delete a domain snapshot")}, - {"desc", N_("Snapshot Delete")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_snapshot_delete[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"snapshotname", VSH_OT_DATA, 0, N_("snapshot name")}, - {"current", VSH_OT_BOOL, 0, N_("delete current snapshot")}, - {"children", VSH_OT_BOOL, 0, N_("delete snapshot and all children")}, - {"children-only", VSH_OT_BOOL, 0, N_("delete children but not snapshot")}, - {"metadata", VSH_OT_BOOL, 0, - N_("delete only libvirt metadata, leaving snapshot contents behind")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdSnapshotDelete(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - const char *name = NULL; - virDomainSnapshotPtr snapshot = NULL; - unsigned int flags = 0; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom, - &snapshot, &name) < 0) - goto cleanup; - - if (vshCommandOptBool(cmd, "children")) - flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN; - if (vshCommandOptBool(cmd, "children-only")) - flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY; - if (vshCommandOptBool(cmd, "metadata")) - flags |= VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY; - - /* XXX If we wanted, we could emulate DELETE_CHILDREN_ONLY even on - * older servers that reject the flag, by manually computing the - * list of descendants. But that's a lot of code to maintain. */ - if (virDomainSnapshotDelete(snapshot, flags) == 0) { - if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY) - vshPrint(ctl, _("Domain snapshot %s children deleted\n"), name); - else - vshPrint(ctl, _("Domain snapshot %s deleted\n"), name); - } else { - vshError(ctl, _("Failed to delete snapshot %s"), name); - goto cleanup; - } - - ret = true; - -cleanup: - if (snapshot) - virDomainSnapshotFree(snapshot); - if (dom) - virDomainFree(dom); - - return ret; -} - /* * "qemu-monitor-command" command */ @@ -6183,6 +4603,8 @@ static const vshCmdDef virshCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-snapshot.c" + static const vshCmdDef snapshotCmds[] = { {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create, info_snapshot_create, 0}, -- 1.7.7.3

Commands in host group moved from virsh.c to virsh-host.c, * virsh.c: Remove commands in host group. * virsh-host.c: New file, filled with commands in host group --- tools/virsh-host.c | 820 ++++++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 799 +-------------------------------------------------- 2 files changed, 822 insertions(+), 797 deletions(-) create mode 100644 tools/virsh-host.c diff --git a/tools/virsh-host.c b/tools/virsh-host.c new file mode 100644 index 0000000..c6296d3 --- /dev/null +++ b/tools/virsh-host.c @@ -0,0 +1,820 @@ +/* + * virsh-host.c: Commands in "Host and Hypervisor" group. + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* + * "capabilities" command + */ +static const vshCmdInfo info_capabilities[] = { + {"help", N_("capabilities")}, + {"desc", N_("Returns capabilities of hypervisor/driver.")}, + {NULL, NULL} +}; + +static bool +cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + char *caps; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if ((caps = virConnectGetCapabilities(ctl->conn)) == NULL) { + vshError(ctl, "%s", _("failed to get capabilities")); + return false; + } + vshPrint(ctl, "%s\n", caps); + VIR_FREE(caps); + + return true; +} + +/* + * "connect" command + */ +static const vshCmdInfo info_connect[] = { + {"help", N_("(re)connect to hypervisor")}, + {"desc", + N_("Connect to local hypervisor. This is built-in command after shell start up.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_connect[] = { + {"name", VSH_OT_DATA, VSH_OFLAG_EMPTY_OK, + N_("hypervisor connection URI")}, + {"readonly", VSH_OT_BOOL, 0, N_("read-only connection")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdConnect(vshControl *ctl, const vshCmd *cmd) +{ + bool ro = vshCommandOptBool(cmd, "readonly"); + const char *name = NULL; + + if (ctl->conn) { + int ret; + if ((ret = virConnectClose(ctl->conn)) != 0) { + vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret); + return false; + } + ctl->conn = NULL; + } + + VIR_FREE(ctl->name); + if (vshCommandOptString(cmd, "name", &name) < 0) { + vshError(ctl, "%s", _("Please specify valid connection URI")); + return false; + } + ctl->name = vshStrdup(ctl, name); + + ctl->useGetInfo = false; + ctl->useSnapshotOld = false; + ctl->readonly = ro; + + ctl->conn = virConnectOpenAuth(ctl->name, virConnectAuthPtrDefault, + ctl->readonly ? VIR_CONNECT_RO : 0); + + if (!ctl->conn) + vshError(ctl, "%s", _("Failed to connect to the hypervisor")); + + return !!ctl->conn; +} + +/* + * "freecell" command + */ +static const vshCmdInfo info_freecell[] = { + {"help", N_("NUMA free memory")}, + {"desc", N_("display available free memory for the NUMA cell.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_freecell[] = { + {"cellno", VSH_OT_INT, 0, N_("NUMA cell number")}, + {"all", VSH_OT_BOOL, 0, N_("show free memory for all NUMA cells")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdFreecell(vshControl *ctl, const vshCmd *cmd) +{ + bool func_ret = false; + int ret; + int cell = -1, cell_given; + unsigned long long memory; + xmlNodePtr *nodes = NULL; + unsigned long nodes_cnt; + unsigned long *nodes_id = NULL; + unsigned long long *nodes_free = NULL; + int all_given; + int i; + char *cap_xml = NULL; + xmlDocPtr xml = NULL; + xmlXPathContextPtr ctxt = NULL; + + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if ( (cell_given = vshCommandOptInt(cmd, "cellno", &cell)) < 0) { + vshError(ctl, "%s", _("cell number has to be a number")); + goto cleanup; + } + all_given = vshCommandOptBool(cmd, "all"); + + if (all_given && cell_given) { + vshError(ctl, "%s", _("--cellno and --all are mutually exclusive. " + "Please choose only one.")); + goto cleanup; + } + + if (all_given) { + cap_xml = virConnectGetCapabilities(ctl->conn); + if (!cap_xml) { + vshError(ctl, "%s", _("unable to get node capabilities")); + goto cleanup; + } + + xml = virXMLParseStringCtxt(cap_xml, _("(capabilities)"), &ctxt); + if (!xml) { + vshError(ctl, "%s", _("unable to get node capabilities")); + goto cleanup; + } + nodes_cnt = virXPathNodeSet("/capabilities/host/topology/cells/cell", + ctxt, &nodes); + + if (nodes_cnt == -1) { + vshError(ctl, "%s", _("could not get information about " + "NUMA topology")); + goto cleanup; + } + + nodes_free = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_free)); + nodes_id = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_id)); + + for (i = 0; i < nodes_cnt; i++) { + unsigned long id; + char *val = virXMLPropString(nodes[i], "id"); + if (virStrToLong_ul(val, NULL, 10, &id)) { + vshError(ctl, "%s", _("conversion from string failed")); + VIR_FREE(val); + goto cleanup; + } + VIR_FREE(val); + nodes_id[i]=id; + ret = virNodeGetCellsFreeMemory(ctl->conn, &(nodes_free[i]), id, 1); + if (ret != 1) { + vshError(ctl, _("failed to get free memory for NUMA node " + "number: %lu"), id); + goto cleanup; + } + } + + memory = 0; + for (cell = 0; cell < nodes_cnt; cell++) { + vshPrint(ctl, "%5lu: %10llu KiB\n", nodes_id[cell], + (nodes_free[cell]/1024)); + memory += nodes_free[cell]; + } + + vshPrintExtra(ctl, "--------------------\n"); + vshPrintExtra(ctl, "%5s: %10llu KiB\n", _("Total"), memory/1024); + } else { + if (!cell_given) { + memory = virNodeGetFreeMemory(ctl->conn); + if (memory == 0) + goto cleanup; + } else { + ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1); + if (ret != 1) + goto cleanup; + } + + if (cell == -1) + vshPrint(ctl, "%s: %llu KiB\n", _("Total"), (memory/1024)); + else + vshPrint(ctl, "%d: %llu KiB\n", cell, (memory/1024)); + } + + func_ret = true; + +cleanup: + xmlXPathFreeContext(ctxt); + xmlFreeDoc(xml); + VIR_FREE(nodes); + VIR_FREE(nodes_free); + VIR_FREE(nodes_id); + VIR_FREE(cap_xml); + return func_ret; +} + +/* + * "nodeinfo" command + */ +static const vshCmdInfo info_nodeinfo[] = { + {"help", N_("node information")}, + {"desc", N_("Returns basic information about the node.")}, + {NULL, NULL} +}; + +static bool +cmdNodeinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + virNodeInfo info; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (virNodeGetInfo(ctl->conn, &info) < 0) { + vshError(ctl, "%s", _("failed to get node information")); + return false; + } + vshPrint(ctl, "%-20s %s\n", _("CPU model:"), info.model); + vshPrint(ctl, "%-20s %d\n", _("CPU(s):"), info.cpus); + vshPrint(ctl, "%-20s %d MHz\n", _("CPU frequency:"), info.mhz); + vshPrint(ctl, "%-20s %d\n", _("CPU socket(s):"), info.sockets); + vshPrint(ctl, "%-20s %d\n", _("Core(s) per socket:"), info.cores); + vshPrint(ctl, "%-20s %d\n", _("Thread(s) per core:"), info.threads); + vshPrint(ctl, "%-20s %d\n", _("NUMA cell(s):"), info.nodes); + vshPrint(ctl, "%-20s %lu KiB\n", _("Memory size:"), info.memory); + + return true; +} + +/* + * "nodecpustats" command + */ +static const vshCmdInfo info_nodecpustats[] = { + {"help", N_("Prints cpu stats of the node.")}, + {"desc", N_("Returns cpu stats of the node, in nanoseconds.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_cpustats[] = { + {"cpu", VSH_OT_INT, 0, N_("prints specified cpu statistics only.")}, + {"percent", VSH_OT_BOOL, 0, N_("prints by percentage during 1 second.")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeCpuStats(vshControl *ctl, const vshCmd *cmd) +{ + int i, j; + bool flag_utilization = false; + bool flag_percent = vshCommandOptBool(cmd, "percent"); + int cpuNum = VIR_NODE_CPU_STATS_ALL_CPUS; + virNodeCPUStatsPtr params; + int nparams = 0; + bool ret = false; + struct cpu_stats { + unsigned long long user; + unsigned long long sys; + unsigned long long idle; + unsigned long long iowait; + unsigned long long util; + } cpu_stats[2]; + double user_time, sys_time, idle_time, iowait_time, total_time; + double usage; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptInt(cmd, "cpu", &cpuNum) < 0) { + vshError(ctl, "%s", _("Invalid value of cpuNum")); + return false; + } + + if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) { + vshError(ctl, "%s", + _("Unable to get number of cpu stats")); + return false; + } + if (nparams == 0) { + /* nothing to output */ + return true; + } + + memset(cpu_stats, 0, sizeof(cpu_stats)); + params = vshCalloc(ctl, nparams, sizeof(*params)); + + for (i = 0; i < 2; i++) { + if (i > 0) + sleep(1); + + if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) { + vshError(ctl, "%s", _("Unable to get node cpu stats")); + goto cleanup; + } + + for (j = 0; j < nparams; j++) { + unsigned long long value = params[j].value; + + if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) { + cpu_stats[i].sys = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) { + cpu_stats[i].user = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) { + cpu_stats[i].idle = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) { + cpu_stats[i].iowait = value; + } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) { + cpu_stats[i].util = value; + flag_utilization = true; + } + } + + if (flag_utilization || !flag_percent) + break; + } + + if (!flag_percent) { + if (!flag_utilization) { + vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user); + vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys); + vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle); + vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait); + } + } else { + if (flag_utilization) { + usage = cpu_stats[0].util; + + vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage); + vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage); + } else { + user_time = cpu_stats[1].user - cpu_stats[0].user; + sys_time = cpu_stats[1].sys - cpu_stats[0].sys; + idle_time = cpu_stats[1].idle - cpu_stats[0].idle; + iowait_time = cpu_stats[1].iowait - cpu_stats[0].iowait; + total_time = user_time + sys_time + idle_time + iowait_time; + + usage = (user_time + sys_time) / total_time * 100; + + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("usage:"), usage); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("user:"), user_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("system:"), sys_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("idle:"), idle_time / total_time * 100); + vshPrint(ctl, "%-15s %5.1lf%%\n", + _("iowait:"), iowait_time / total_time * 100); + } + } + + ret = true; + + cleanup: + VIR_FREE(params); + return ret; +} + +/* + * "nodememstats" command + */ +static const vshCmdInfo info_nodememstats[] = { + {"help", N_("Prints memory stats of the node.")}, + {"desc", N_("Returns memory stats of the node, in kilobytes.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_memstats[] = { + {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd) +{ + int nparams = 0; + unsigned int i = 0; + int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS; + virNodeMemoryStatsPtr params = NULL; + bool ret = false; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) { + vshError(ctl, "%s", _("Invalid value of cellNum")); + return false; + } + + /* get the number of memory parameters */ + if (virNodeGetMemoryStats(ctl->conn, cellNum, NULL, &nparams, 0) != 0) { + vshError(ctl, "%s", + _("Unable to get number of memory stats")); + goto cleanup; + } + + if (nparams == 0) { + /* nothing to output */ + ret = true; + goto cleanup; + } + + /* now go get all the memory parameters */ + params = vshCalloc(ctl, nparams, sizeof(*params)); + if (virNodeGetMemoryStats(ctl->conn, cellNum, params, &nparams, 0) != 0) { + vshError(ctl, "%s", _("Unable to get memory stats")); + goto cleanup; + } + + for (i = 0; i < nparams; i++) + vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value); + + ret = true; + + cleanup: + VIR_FREE(params); + return ret; +} + +/* + * "nodesuspend" command + */ +static const vshCmdInfo info_nodesuspend[] = { + {"help", N_("suspend the host node for a given time duration")}, + {"desc", N_("Suspend the host node for a given time duration " + "and attempt to resume thereafter.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_suspend[] = { + {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), " + "disk(Suspend-to-Disk), hybrid(Hybrid-Suspend)")}, + {"duration", VSH_OT_INT, VSH_OFLAG_REQ, N_("Suspend duration in seconds")}, + {"flags", VSH_OT_INT, VSH_OFLAG_NONE, N_("Suspend flags, 0 for default")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd) +{ + const char *target = NULL; + unsigned int suspendTarget; + long long duration; + unsigned int flags = 0; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "target", &target) < 0) { + vshError(ctl, _("Invalid target argument")); + return false; + } + + if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) { + vshError(ctl, _("Invalid duration argument")); + return false; + } + + if (vshCommandOptUInt(cmd, "flags", &flags) < 0) { + vshError(ctl, _("Invalid flags argument")); + return false; + } + + if (STREQ(target, "mem")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM; + else if (STREQ(target, "disk")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK; + else if (STREQ(target, "hybrid")) + suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID; + else { + vshError(ctl, "%s", _("Invalid target")); + return false; + } + + if (duration <= 0) { + vshError(ctl, "%s", _("Invalid duration")); + return false; + } + + if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration, + flags) < 0) { + vshError(ctl, "%s", _("The host was not suspended")); + return false; + } + return true; +} + +/* + * "qemu-monitor-command" command + */ +static const vshCmdInfo info_qemu_monitor_command[] = { + {"help", N_("QEMU Monitor Command")}, + {"desc", N_("QEMU Monitor Command")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_qemu_monitor_command[] = { + {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, + {"hmp", VSH_OT_BOOL, 0, N_("command is in human monitor protocol")}, + {"cmd", VSH_OT_ARGV, VSH_OFLAG_REQ, N_("command")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdQemuMonitorCommand(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + char *monitor_cmd = NULL; + char *result = NULL; + unsigned int flags = 0; + const vshCmdOpt *opt = NULL; + virBuffer buf = VIR_BUFFER_INITIALIZER; + bool pad = false; + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + dom = vshCommandOptDomain(ctl, cmd, NULL); + if (dom == NULL) + goto cleanup; + + while ((opt = vshCommandOptArgv(cmd, opt))) { + if (pad) + virBufferAddChar(&buf, ' '); + pad = true; + virBufferAdd(&buf, opt->data, -1); + } + if (virBufferError(&buf)) { + vshPrint(ctl, "%s", _("Failed to collect command")); + goto cleanup; + } + monitor_cmd = virBufferContentAndReset(&buf); + + if (vshCommandOptBool(cmd, "hmp")) + flags |= VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP; + + if (virDomainQemuMonitorCommand(dom, monitor_cmd, &result, flags) < 0) + goto cleanup; + + printf("%s\n", result); + + ret = true; + +cleanup: + VIR_FREE(result); + VIR_FREE(monitor_cmd); + if (dom) + virDomainFree(dom); + + return ret; +} + +/* + * "qemu-attach" command + */ +static const vshCmdInfo info_qemu_attach[] = { + {"help", N_("QEMU Attach")}, + {"desc", N_("QEMU Attach")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_qemu_attach[] = { + {"pid", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pid")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdQemuAttach(vshControl *ctl, const vshCmd *cmd) +{ + virDomainPtr dom = NULL; + bool ret = false; + unsigned int flags = 0; + unsigned int pid_value; /* API uses unsigned int, not pid_t */ + + if (!vshConnectionUsability(ctl, ctl->conn)) + goto cleanup; + + if (vshCommandOptUInt(cmd, "pid", &pid_value) <= 0) { + vshError(ctl, "%s", _("missing pid value")); + goto cleanup; + } + + if (!(dom = virDomainQemuAttach(ctl->conn, pid_value, flags))) + goto cleanup; + + if (dom != NULL) { + vshPrint(ctl, _("Domain %s attached to pid %u\n"), + virDomainGetName(dom), pid_value); + virDomainFree(dom); + ret = true; + } else { + vshError(ctl, _("Failed to attach to pid %u"), pid_value); + } + +cleanup: + return ret; +} + +/* + * "sysinfo" command + */ +static const vshCmdInfo info_sysinfo[] = { + {"help", N_("print the hypervisor sysinfo")}, + {"desc", + N_("output an XML string for the hypervisor sysinfo, if available")}, + {NULL, NULL} +}; + +static bool +cmdSysinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + char *sysinfo; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + sysinfo = virConnectGetSysinfo(ctl->conn, 0); + if (sysinfo == NULL) { + vshError(ctl, "%s", _("failed to get sysinfo")); + return false; + } + + vshPrint(ctl, "%s", sysinfo); + VIR_FREE(sysinfo); + + return true; +} + +/* + * "hostname" command + */ +static const vshCmdInfo info_hostname[] = { + {"help", N_("print the hypervisor hostname")}, + {"desc", ""}, + {NULL, NULL} +}; + +static bool +cmdHostname(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + char *hostname; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + hostname = virConnectGetHostname(ctl->conn); + if (hostname == NULL) { + vshError(ctl, "%s", _("failed to get hostname")); + return false; + } + + vshPrint (ctl, "%s\n", hostname); + VIR_FREE(hostname); + + return true; +} + +/* + * "uri" command + */ +static const vshCmdInfo info_uri[] = { + {"help", N_("print the hypervisor canonical URI")}, + {"desc", ""}, + {NULL, NULL} +}; + +static bool +cmdURI(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + char *uri; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + uri = virConnectGetURI(ctl->conn); + if (uri == NULL) { + vshError(ctl, "%s", _("failed to get URI")); + return false; + } + + vshPrint(ctl, "%s\n", uri); + VIR_FREE(uri); + + return true; +} + +/* + * "version" command + */ +static const vshCmdInfo info_version[] = { + {"help", N_("show version")}, + {"desc", N_("Display the system version information.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_version[] = { + {"daemon", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("report daemon version too")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + unsigned long hvVersion; + const char *hvType; + unsigned long libVersion; + unsigned long includeVersion; + unsigned long apiVersion; + unsigned long daemonVersion; + int ret; + unsigned int major; + unsigned int minor; + unsigned int rel; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + hvType = virConnectGetType(ctl->conn); + if (hvType == NULL) { + vshError(ctl, "%s", _("failed to get hypervisor type")); + return false; + } + + includeVersion = LIBVIR_VERSION_NUMBER; + major = includeVersion / 1000000; + includeVersion %= 1000000; + minor = includeVersion / 1000; + rel = includeVersion % 1000; + vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"), + major, minor, rel); + + ret = virGetVersion(&libVersion, hvType, &apiVersion); + if (ret < 0) { + vshError(ctl, "%s", _("failed to get the library version")); + return false; + } + major = libVersion / 1000000; + libVersion %= 1000000; + minor = libVersion / 1000; + rel = libVersion % 1000; + vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"), + major, minor, rel); + + major = apiVersion / 1000000; + apiVersion %= 1000000; + minor = apiVersion / 1000; + rel = apiVersion % 1000; + vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType, + major, minor, rel); + + ret = virConnectGetVersion(ctl->conn, &hvVersion); + if (ret < 0) { + vshError(ctl, "%s", _("failed to get the hypervisor version")); + return false; + } + if (hvVersion == 0) { + vshPrint(ctl, + _("Cannot extract running %s hypervisor version\n"), hvType); + } else { + major = hvVersion / 1000000; + hvVersion %= 1000000; + minor = hvVersion / 1000; + rel = hvVersion % 1000; + + vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"), + hvType, major, minor, rel); + } + + if (vshCommandOptBool(cmd, "daemon")) { + ret = virConnectGetLibVersion(ctl->conn, &daemonVersion); + if (ret < 0) { + vshError(ctl, "%s", _("failed to get the daemon version")); + } else { + major = daemonVersion / 1000000; + daemonVersion %= 1000000; + minor = daemonVersion / 1000; + rel = daemonVersion % 1000; + vshPrint(ctl, _("Running against daemon: %d.%d.%d\n"), + major, minor, rel); + } + } + + return true; +} diff --git a/tools/virsh.c b/tools/virsh.c index 96e9b34..1d878b9 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -747,504 +747,6 @@ cmdHelp(vshControl *ctl, const vshCmd *cmd) } /* - * "connect" command - */ -static const vshCmdInfo info_connect[] = { - {"help", N_("(re)connect to hypervisor")}, - {"desc", - N_("Connect to local hypervisor. This is built-in command after shell start up.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_connect[] = { - {"name", VSH_OT_DATA, VSH_OFLAG_EMPTY_OK, - N_("hypervisor connection URI")}, - {"readonly", VSH_OT_BOOL, 0, N_("read-only connection")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdConnect(vshControl *ctl, const vshCmd *cmd) -{ - bool ro = vshCommandOptBool(cmd, "readonly"); - const char *name = NULL; - - if (ctl->conn) { - int ret; - if ((ret = virConnectClose(ctl->conn)) != 0) { - vshError(ctl, _("Failed to disconnect from the hypervisor, %d leaked reference(s)"), ret); - return false; - } - ctl->conn = NULL; - } - - VIR_FREE(ctl->name); - if (vshCommandOptString(cmd, "name", &name) < 0) { - vshError(ctl, "%s", _("Please specify valid connection URI")); - return false; - } - ctl->name = vshStrdup(ctl, name); - - ctl->useGetInfo = false; - ctl->useSnapshotOld = false; - ctl->readonly = ro; - - ctl->conn = virConnectOpenAuth(ctl->name, virConnectAuthPtrDefault, - ctl->readonly ? VIR_CONNECT_RO : 0); - - if (!ctl->conn) - vshError(ctl, "%s", _("Failed to connect to the hypervisor")); - - return !!ctl->conn; -} - -/* - * "freecell" command - */ -static const vshCmdInfo info_freecell[] = { - {"help", N_("NUMA free memory")}, - {"desc", N_("display available free memory for the NUMA cell.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_freecell[] = { - {"cellno", VSH_OT_INT, 0, N_("NUMA cell number")}, - {"all", VSH_OT_BOOL, 0, N_("show free memory for all NUMA cells")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdFreecell(vshControl *ctl, const vshCmd *cmd) -{ - bool func_ret = false; - int ret; - int cell = -1, cell_given; - unsigned long long memory; - xmlNodePtr *nodes = NULL; - unsigned long nodes_cnt; - unsigned long *nodes_id = NULL; - unsigned long long *nodes_free = NULL; - int all_given; - int i; - char *cap_xml = NULL; - xmlDocPtr xml = NULL; - xmlXPathContextPtr ctxt = NULL; - - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if ( (cell_given = vshCommandOptInt(cmd, "cellno", &cell)) < 0) { - vshError(ctl, "%s", _("cell number has to be a number")); - goto cleanup; - } - all_given = vshCommandOptBool(cmd, "all"); - - if (all_given && cell_given) { - vshError(ctl, "%s", _("--cellno and --all are mutually exclusive. " - "Please choose only one.")); - goto cleanup; - } - - if (all_given) { - cap_xml = virConnectGetCapabilities(ctl->conn); - if (!cap_xml) { - vshError(ctl, "%s", _("unable to get node capabilities")); - goto cleanup; - } - - xml = virXMLParseStringCtxt(cap_xml, _("(capabilities)"), &ctxt); - if (!xml) { - vshError(ctl, "%s", _("unable to get node capabilities")); - goto cleanup; - } - nodes_cnt = virXPathNodeSet("/capabilities/host/topology/cells/cell", - ctxt, &nodes); - - if (nodes_cnt == -1) { - vshError(ctl, "%s", _("could not get information about " - "NUMA topology")); - goto cleanup; - } - - nodes_free = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_free)); - nodes_id = vshCalloc(ctl, nodes_cnt, sizeof(*nodes_id)); - - for (i = 0; i < nodes_cnt; i++) { - unsigned long id; - char *val = virXMLPropString(nodes[i], "id"); - if (virStrToLong_ul(val, NULL, 10, &id)) { - vshError(ctl, "%s", _("conversion from string failed")); - VIR_FREE(val); - goto cleanup; - } - VIR_FREE(val); - nodes_id[i]=id; - ret = virNodeGetCellsFreeMemory(ctl->conn, &(nodes_free[i]), id, 1); - if (ret != 1) { - vshError(ctl, _("failed to get free memory for NUMA node " - "number: %lu"), id); - goto cleanup; - } - } - - memory = 0; - for (cell = 0; cell < nodes_cnt; cell++) { - vshPrint(ctl, "%5lu: %10llu KiB\n", nodes_id[cell], - (nodes_free[cell]/1024)); - memory += nodes_free[cell]; - } - - vshPrintExtra(ctl, "--------------------\n"); - vshPrintExtra(ctl, "%5s: %10llu KiB\n", _("Total"), memory/1024); - } else { - if (!cell_given) { - memory = virNodeGetFreeMemory(ctl->conn); - if (memory == 0) - goto cleanup; - } else { - ret = virNodeGetCellsFreeMemory(ctl->conn, &memory, cell, 1); - if (ret != 1) - goto cleanup; - } - - if (cell == -1) - vshPrint(ctl, "%s: %llu KiB\n", _("Total"), (memory/1024)); - else - vshPrint(ctl, "%d: %llu KiB\n", cell, (memory/1024)); - } - - func_ret = true; - -cleanup: - xmlXPathFreeContext(ctxt); - xmlFreeDoc(xml); - VIR_FREE(nodes); - VIR_FREE(nodes_free); - VIR_FREE(nodes_id); - VIR_FREE(cap_xml); - return func_ret; -} - -/* - * "nodeinfo" command - */ -static const vshCmdInfo info_nodeinfo[] = { - {"help", N_("node information")}, - {"desc", N_("Returns basic information about the node.")}, - {NULL, NULL} -}; - -static bool -cmdNodeinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - virNodeInfo info; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (virNodeGetInfo(ctl->conn, &info) < 0) { - vshError(ctl, "%s", _("failed to get node information")); - return false; - } - vshPrint(ctl, "%-20s %s\n", _("CPU model:"), info.model); - vshPrint(ctl, "%-20s %d\n", _("CPU(s):"), info.cpus); - vshPrint(ctl, "%-20s %d MHz\n", _("CPU frequency:"), info.mhz); - vshPrint(ctl, "%-20s %d\n", _("CPU socket(s):"), info.sockets); - vshPrint(ctl, "%-20s %d\n", _("Core(s) per socket:"), info.cores); - vshPrint(ctl, "%-20s %d\n", _("Thread(s) per core:"), info.threads); - vshPrint(ctl, "%-20s %d\n", _("NUMA cell(s):"), info.nodes); - vshPrint(ctl, "%-20s %lu KiB\n", _("Memory size:"), info.memory); - - return true; -} - -/* - * "nodecpustats" command - */ -static const vshCmdInfo info_nodecpustats[] = { - {"help", N_("Prints cpu stats of the node.")}, - {"desc", N_("Returns cpu stats of the node, in nanoseconds.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_cpustats[] = { - {"cpu", VSH_OT_INT, 0, N_("prints specified cpu statistics only.")}, - {"percent", VSH_OT_BOOL, 0, N_("prints by percentage during 1 second.")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeCpuStats(vshControl *ctl, const vshCmd *cmd) -{ - int i, j; - bool flag_utilization = false; - bool flag_percent = vshCommandOptBool(cmd, "percent"); - int cpuNum = VIR_NODE_CPU_STATS_ALL_CPUS; - virNodeCPUStatsPtr params; - int nparams = 0; - bool ret = false; - struct cpu_stats { - unsigned long long user; - unsigned long long sys; - unsigned long long idle; - unsigned long long iowait; - unsigned long long util; - } cpu_stats[2]; - double user_time, sys_time, idle_time, iowait_time, total_time; - double usage; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptInt(cmd, "cpu", &cpuNum) < 0) { - vshError(ctl, "%s", _("Invalid value of cpuNum")); - return false; - } - - if (virNodeGetCPUStats(ctl->conn, cpuNum, NULL, &nparams, 0) != 0) { - vshError(ctl, "%s", - _("Unable to get number of cpu stats")); - return false; - } - if (nparams == 0) { - /* nothing to output */ - return true; - } - - memset(cpu_stats, 0, sizeof(cpu_stats)); - params = vshCalloc(ctl, nparams, sizeof(*params)); - - for (i = 0; i < 2; i++) { - if (i > 0) - sleep(1); - - if (virNodeGetCPUStats(ctl->conn, cpuNum, params, &nparams, 0) != 0) { - vshError(ctl, "%s", _("Unable to get node cpu stats")); - goto cleanup; - } - - for (j = 0; j < nparams; j++) { - unsigned long long value = params[j].value; - - if (STREQ(params[j].field, VIR_NODE_CPU_STATS_KERNEL)) { - cpu_stats[i].sys = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_USER)) { - cpu_stats[i].user = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IDLE)) { - cpu_stats[i].idle = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_IOWAIT)) { - cpu_stats[i].iowait = value; - } else if (STREQ(params[j].field, VIR_NODE_CPU_STATS_UTILIZATION)) { - cpu_stats[i].util = value; - flag_utilization = true; - } - } - - if (flag_utilization || !flag_percent) - break; - } - - if (!flag_percent) { - if (!flag_utilization) { - vshPrint(ctl, "%-15s %20llu\n", _("user:"), cpu_stats[0].user); - vshPrint(ctl, "%-15s %20llu\n", _("system:"), cpu_stats[0].sys); - vshPrint(ctl, "%-15s %20llu\n", _("idle:"), cpu_stats[0].idle); - vshPrint(ctl, "%-15s %20llu\n", _("iowait:"), cpu_stats[0].iowait); - } - } else { - if (flag_utilization) { - usage = cpu_stats[0].util; - - vshPrint(ctl, "%-15s %5.1lf%%\n", _("usage:"), usage); - vshPrint(ctl, "%-15s %5.1lf%%\n", _("idle:"), 100 - usage); - } else { - user_time = cpu_stats[1].user - cpu_stats[0].user; - sys_time = cpu_stats[1].sys - cpu_stats[0].sys; - idle_time = cpu_stats[1].idle - cpu_stats[0].idle; - iowait_time = cpu_stats[1].iowait - cpu_stats[0].iowait; - total_time = user_time + sys_time + idle_time + iowait_time; - - usage = (user_time + sys_time) / total_time * 100; - - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("usage:"), usage); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("user:"), user_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("system:"), sys_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("idle:"), idle_time / total_time * 100); - vshPrint(ctl, "%-15s %5.1lf%%\n", - _("iowait:"), iowait_time / total_time * 100); - } - } - - ret = true; - - cleanup: - VIR_FREE(params); - return ret; -} - -/* - * "nodememstats" command - */ -static const vshCmdInfo info_nodememstats[] = { - {"help", N_("Prints memory stats of the node.")}, - {"desc", N_("Returns memory stats of the node, in kilobytes.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_memstats[] = { - {"cell", VSH_OT_INT, 0, N_("prints specified cell statistics only.")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeMemStats(vshControl *ctl, const vshCmd *cmd) -{ - int nparams = 0; - unsigned int i = 0; - int cellNum = VIR_NODE_MEMORY_STATS_ALL_CELLS; - virNodeMemoryStatsPtr params = NULL; - bool ret = false; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptInt(cmd, "cell", &cellNum) < 0) { - vshError(ctl, "%s", _("Invalid value of cellNum")); - return false; - } - - /* get the number of memory parameters */ - if (virNodeGetMemoryStats(ctl->conn, cellNum, NULL, &nparams, 0) != 0) { - vshError(ctl, "%s", - _("Unable to get number of memory stats")); - goto cleanup; - } - - if (nparams == 0) { - /* nothing to output */ - ret = true; - goto cleanup; - } - - /* now go get all the memory parameters */ - params = vshCalloc(ctl, nparams, sizeof(*params)); - if (virNodeGetMemoryStats(ctl->conn, cellNum, params, &nparams, 0) != 0) { - vshError(ctl, "%s", _("Unable to get memory stats")); - goto cleanup; - } - - for (i = 0; i < nparams; i++) - vshPrint(ctl, "%-7s: %20llu KiB\n", params[i].field, params[i].value); - - ret = true; - - cleanup: - VIR_FREE(params); - return ret; -} - -/* - * "nodesuspend" command - */ -static const vshCmdInfo info_nodesuspend[] = { - {"help", N_("suspend the host node for a given time duration")}, - {"desc", N_("Suspend the host node for a given time duration " - "and attempt to resume thereafter.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_suspend[] = { - {"target", VSH_OT_DATA, VSH_OFLAG_REQ, N_("mem(Suspend-to-RAM), " - "disk(Suspend-to-Disk), hybrid(Hybrid-Suspend)")}, - {"duration", VSH_OT_INT, VSH_OFLAG_REQ, N_("Suspend duration in seconds")}, - {"flags", VSH_OT_INT, VSH_OFLAG_NONE, N_("Suspend flags, 0 for default")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeSuspend(vshControl *ctl, const vshCmd *cmd) -{ - const char *target = NULL; - unsigned int suspendTarget; - long long duration; - unsigned int flags = 0; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "target", &target) < 0) { - vshError(ctl, _("Invalid target argument")); - return false; - } - - if (vshCommandOptLongLong(cmd, "duration", &duration) < 0) { - vshError(ctl, _("Invalid duration argument")); - return false; - } - - if (vshCommandOptUInt(cmd, "flags", &flags) < 0) { - vshError(ctl, _("Invalid flags argument")); - return false; - } - - if (STREQ(target, "mem")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_MEM; - else if (STREQ(target, "disk")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_DISK; - else if (STREQ(target, "hybrid")) - suspendTarget = VIR_NODE_SUSPEND_TARGET_HYBRID; - else { - vshError(ctl, "%s", _("Invalid target")); - return false; - } - - if (duration <= 0) { - vshError(ctl, "%s", _("Invalid duration")); - return false; - } - - if (virNodeSuspendForDuration(ctl->conn, suspendTarget, duration, - flags) < 0) { - vshError(ctl, "%s", _("The host was not suspended")); - return false; - } - return true; -} - - -/* - * "capabilities" command - */ -static const vshCmdInfo info_capabilities[] = { - {"help", N_("capabilities")}, - {"desc", N_("Returns capabilities of hypervisor/driver.")}, - {NULL, NULL} -}; - -static bool -cmdCapabilities(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - char *caps; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if ((caps = virConnectGetCapabilities(ctl->conn)) == NULL) { - vshError(ctl, "%s", _("failed to get capabilities")); - return false; - } - vshPrint(ctl, "%s\n", caps); - VIR_FREE(caps); - - return true; -} - -/* * "nodedev-create" command */ static const vshCmdInfo info_node_device_create[] = { @@ -1338,105 +840,6 @@ cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd) return ret; } -/* - * "version" command - */ -static const vshCmdInfo info_version[] = { - {"help", N_("show version")}, - {"desc", N_("Display the system version information.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_version[] = { - {"daemon", VSH_OT_BOOL, VSH_OFLAG_NONE, N_("report daemon version too")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - unsigned long hvVersion; - const char *hvType; - unsigned long libVersion; - unsigned long includeVersion; - unsigned long apiVersion; - unsigned long daemonVersion; - int ret; - unsigned int major; - unsigned int minor; - unsigned int rel; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - hvType = virConnectGetType(ctl->conn); - if (hvType == NULL) { - vshError(ctl, "%s", _("failed to get hypervisor type")); - return false; - } - - includeVersion = LIBVIR_VERSION_NUMBER; - major = includeVersion / 1000000; - includeVersion %= 1000000; - minor = includeVersion / 1000; - rel = includeVersion % 1000; - vshPrint(ctl, _("Compiled against library: libvir %d.%d.%d\n"), - major, minor, rel); - - ret = virGetVersion(&libVersion, hvType, &apiVersion); - if (ret < 0) { - vshError(ctl, "%s", _("failed to get the library version")); - return false; - } - major = libVersion / 1000000; - libVersion %= 1000000; - minor = libVersion / 1000; - rel = libVersion % 1000; - vshPrint(ctl, _("Using library: libvir %d.%d.%d\n"), - major, minor, rel); - - major = apiVersion / 1000000; - apiVersion %= 1000000; - minor = apiVersion / 1000; - rel = apiVersion % 1000; - vshPrint(ctl, _("Using API: %s %d.%d.%d\n"), hvType, - major, minor, rel); - - ret = virConnectGetVersion(ctl->conn, &hvVersion); - if (ret < 0) { - vshError(ctl, "%s", _("failed to get the hypervisor version")); - return false; - } - if (hvVersion == 0) { - vshPrint(ctl, - _("Cannot extract running %s hypervisor version\n"), hvType); - } else { - major = hvVersion / 1000000; - hvVersion %= 1000000; - minor = hvVersion / 1000; - rel = hvVersion % 1000; - - vshPrint(ctl, _("Running hypervisor: %s %d.%d.%d\n"), - hvType, major, minor, rel); - } - - if (vshCommandOptBool(cmd, "daemon")) { - ret = virConnectGetLibVersion(ctl->conn, &daemonVersion); - if (ret < 0) { - vshError(ctl, "%s", _("failed to get the daemon version")); - } else { - major = daemonVersion / 1000000; - daemonVersion %= 1000000; - minor = daemonVersion / 1000; - rel = daemonVersion % 1000; - vshPrint(ctl, _("Running against daemon: %d.%d.%d\n"), - major, minor, rel); - } - } - - return true; -} - /* Tree listing helpers. */ /* Given an index, return either the name of that device (non-NULL) or @@ -1789,94 +1192,6 @@ cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd) return ret; } -/* - * "hostname" command - */ -static const vshCmdInfo info_hostname[] = { - {"help", N_("print the hypervisor hostname")}, - {"desc", ""}, - {NULL, NULL} -}; - -static bool -cmdHostname(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - char *hostname; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - hostname = virConnectGetHostname(ctl->conn); - if (hostname == NULL) { - vshError(ctl, "%s", _("failed to get hostname")); - return false; - } - - vshPrint (ctl, "%s\n", hostname); - VIR_FREE(hostname); - - return true; -} - -/* - * "uri" command - */ -static const vshCmdInfo info_uri[] = { - {"help", N_("print the hypervisor canonical URI")}, - {"desc", ""}, - {NULL, NULL} -}; - -static bool -cmdURI(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - char *uri; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - uri = virConnectGetURI(ctl->conn); - if (uri == NULL) { - vshError(ctl, "%s", _("failed to get URI")); - return false; - } - - vshPrint(ctl, "%s\n", uri); - VIR_FREE(uri); - - return true; -} - -/* - * "sysinfo" command - */ -static const vshCmdInfo info_sysinfo[] = { - {"help", N_("print the hypervisor sysinfo")}, - {"desc", - N_("output an XML string for the hypervisor sysinfo, if available")}, - {NULL, NULL} -}; - -static bool -cmdSysinfo(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - char *sysinfo; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - sysinfo = virConnectGetSysinfo(ctl->conn, 0); - if (sysinfo == NULL) { - vshError(ctl, "%s", _("failed to get sysinfo")); - return false; - } - - vshPrint(ctl, "%s", sysinfo); - VIR_FREE(sysinfo); - - return true; -} - /* Common code for the edit / net-edit / pool-edit functions which follow. */ static char * editWriteToTempFile(vshControl *ctl, const char *doc) @@ -2149,118 +1464,6 @@ cmdQuit(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) return true; } -/* - * "qemu-monitor-command" command - */ -static const vshCmdInfo info_qemu_monitor_command[] = { - {"help", N_("QEMU Monitor Command")}, - {"desc", N_("QEMU Monitor Command")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_qemu_monitor_command[] = { - {"domain", VSH_OT_DATA, VSH_OFLAG_REQ, N_("domain name, id or uuid")}, - {"hmp", VSH_OT_BOOL, 0, N_("command is in human monitor protocol")}, - {"cmd", VSH_OT_ARGV, VSH_OFLAG_REQ, N_("command")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdQemuMonitorCommand(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - char *monitor_cmd = NULL; - char *result = NULL; - unsigned int flags = 0; - const vshCmdOpt *opt = NULL; - virBuffer buf = VIR_BUFFER_INITIALIZER; - bool pad = false; - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - dom = vshCommandOptDomain(ctl, cmd, NULL); - if (dom == NULL) - goto cleanup; - - while ((opt = vshCommandOptArgv(cmd, opt))) { - if (pad) - virBufferAddChar(&buf, ' '); - pad = true; - virBufferAdd(&buf, opt->data, -1); - } - if (virBufferError(&buf)) { - vshPrint(ctl, "%s", _("Failed to collect command")); - goto cleanup; - } - monitor_cmd = virBufferContentAndReset(&buf); - - if (vshCommandOptBool(cmd, "hmp")) - flags |= VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP; - - if (virDomainQemuMonitorCommand(dom, monitor_cmd, &result, flags) < 0) - goto cleanup; - - printf("%s\n", result); - - ret = true; - -cleanup: - VIR_FREE(result); - VIR_FREE(monitor_cmd); - if (dom) - virDomainFree(dom); - - return ret; -} - -/* - * "qemu-attach" command - */ -static const vshCmdInfo info_qemu_attach[] = { - {"help", N_("QEMU Attach")}, - {"desc", N_("QEMU Attach")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_qemu_attach[] = { - {"pid", VSH_OT_DATA, VSH_OFLAG_REQ, N_("pid")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdQemuAttach(vshControl *ctl, const vshCmd *cmd) -{ - virDomainPtr dom = NULL; - bool ret = false; - unsigned int flags = 0; - unsigned int pid_value; /* API uses unsigned int, not pid_t */ - - if (!vshConnectionUsability(ctl, ctl->conn)) - goto cleanup; - - if (vshCommandOptUInt(cmd, "pid", &pid_value) <= 0) { - vshError(ctl, "%s", _("missing pid value")); - goto cleanup; - } - - if (!(dom = virDomainQemuAttach(ctl->conn, pid_value, flags))) - goto cleanup; - - if (dom != NULL) { - vshPrint(ctl, _("Domain %s attached to pid %u\n"), - virDomainGetName(dom), pid_value); - virDomainFree(dom); - ret = true; - } else { - vshError(ctl, _("Failed to attach to pid %u"), pid_value); - } - -cleanup: - return ret; -} - /* --------------- * Utils for work with command definition * --------------- @@ -4629,6 +3832,8 @@ static const vshCmdDef snapshotCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-host.c" + static const vshCmdDef hostAndHypervisorCmds[] = { {"capabilities", cmdCapabilities, NULL, info_capabilities, 0}, {"connect", cmdConnect, opts_connect, info_connect, -- 1.7.7.3

Commands in node device group moved from virsh.c to virsh-nodedev.c, * virsh.c: Remove commands in node device group. * virsh-nodedev.c: New file, filled with commands in node device group --- tools/virsh-nodedev.c | 383 +++++++++++++++++++++++++++++++++++++++++++++++++ tools/virsh.c | 360 +--------------------------------------------- 2 files changed, 385 insertions(+), 358 deletions(-) create mode 100644 tools/virsh-nodedev.c diff --git a/tools/virsh-nodedev.c b/tools/virsh-nodedev.c new file mode 100644 index 0000000..ee9a6fd --- /dev/null +++ b/tools/virsh-nodedev.c @@ -0,0 +1,383 @@ +/* + * virsh-nodedev.c: Commands in node device group + * + * Copyright (C) 2005, 2007-2012 Red Hat, Inc + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; If not, see + * <http://www.gnu.org/licenses/>. + * + * Daniel Veillard <veillard@redhat.com> + * Karel Zak <kzak@redhat.com> + * Daniel P. Berrange <berrange@redhat.com> + * + */ + +/* + * "nodedev-create" command + */ +static const vshCmdInfo info_node_device_create[] = { + {"help", N_("create a device defined " + "by an XML file on the node")}, + {"desc", N_("Create a device on the node. Note that this " + "command creates devices on the physical host " + "that can then be assigned to a virtual machine.")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_device_create[] = { + {"file", VSH_OT_DATA, VSH_OFLAG_REQ, + N_("file containing an XML description of the device")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd) +{ + virNodeDevicePtr dev = NULL; + const char *from = NULL; + bool ret = true; + char *buffer; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "file", &from) <= 0) + return false; + + if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) + return false; + + dev = virNodeDeviceCreateXML(ctl->conn, buffer, 0); + VIR_FREE(buffer); + + if (dev != NULL) { + vshPrint(ctl, _("Node device %s created from %s\n"), + virNodeDeviceGetName(dev), from); + virNodeDeviceFree(dev); + } else { + vshError(ctl, _("Failed to create node device from %s"), from); + ret = false; + } + + return ret; +} + + +/* + * "nodedev-destroy" command + */ +static const vshCmdInfo info_node_device_destroy[] = { + {"help", N_("destroy (stop) a device on the node")}, + {"desc", N_("Destroy a device on the node. Note that this " + "command destroys devices on the physical host")}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_device_destroy[] = { + {"name", VSH_OT_DATA, VSH_OFLAG_REQ, + N_("name of the device to be destroyed")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd) +{ + virNodeDevicePtr dev = NULL; + bool ret = true; + const char *name = NULL; + + if (!vshConnectionUsability(ctl, ctl->conn)) { + return false; + } + + if (vshCommandOptString(cmd, "name", &name) <= 0) + return false; + + dev = virNodeDeviceLookupByName(ctl->conn, name); + + if (virNodeDeviceDestroy(dev) == 0) { + vshPrint(ctl, _("Destroyed node device '%s'\n"), name); + } else { + vshError(ctl, _("Failed to destroy node device '%s'"), name); + ret = false; + } + + virNodeDeviceFree(dev); + return ret; +} + +struct vshNodeList { + char **names; + char **parents; +}; + +static const char * +vshNodeListLookup(int devid, bool parent, void *opaque) +{ + struct vshNodeList *arrays = opaque; + if (parent) + return arrays->parents[devid]; + return arrays->names[devid]; +} + +/* + * "nodedev-list" command + */ +static const vshCmdInfo info_node_list_devices[] = { + {"help", N_("enumerate devices on this host")}, + {"desc", ""}, + {NULL, NULL} +}; + +static const vshCmdOptDef opts_node_list_devices[] = { + {"tree", VSH_OT_BOOL, 0, N_("list devices in a tree")}, + {"cap", VSH_OT_STRING, VSH_OFLAG_NONE, N_("capability name")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) +{ + const char *cap = NULL; + char **devices; + int num_devices, i; + bool tree = vshCommandOptBool(cmd, "tree"); + bool ret = true; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + + if (vshCommandOptString(cmd, "cap", &cap) <= 0) + cap = NULL; + + num_devices = virNodeNumOfDevices(ctl->conn, cap, 0); + if (num_devices < 0) { + vshError(ctl, "%s", _("Failed to count node devices")); + return false; + } else if (num_devices == 0) { + return true; + } + + devices = vshMalloc(ctl, sizeof(char *) * num_devices); + num_devices = + virNodeListDevices(ctl->conn, cap, devices, num_devices, 0); + if (num_devices < 0) { + vshError(ctl, "%s", _("Failed to list node devices")); + VIR_FREE(devices); + return false; + } + qsort(&devices[0], num_devices, sizeof(char*), vshNameSorter); + if (tree) { + char **parents = vshMalloc(ctl, sizeof(char *) * num_devices); + struct vshNodeList arrays = { devices, parents }; + + for (i = 0; i < num_devices; i++) { + virNodeDevicePtr dev = virNodeDeviceLookupByName(ctl->conn, devices[i]); + if (dev && STRNEQ(devices[i], "computer")) { + const char *parent = virNodeDeviceGetParent(dev); + parents[i] = parent ? vshStrdup(ctl, parent) : NULL; + } else { + parents[i] = NULL; + } + virNodeDeviceFree(dev); + } + for (i = 0 ; i < num_devices ; i++) { + if (parents[i] == NULL && + vshTreePrint(ctl, vshNodeListLookup, &arrays, num_devices, + i) < 0) + ret = false; + } + for (i = 0 ; i < num_devices ; i++) { + VIR_FREE(devices[i]); + VIR_FREE(parents[i]); + } + VIR_FREE(parents); + } else { + for (i = 0; i < num_devices; i++) { + vshPrint(ctl, "%s\n", devices[i]); + VIR_FREE(devices[i]); + } + } + VIR_FREE(devices); + return ret; +} + +/* + * "nodedev-dumpxml" command + */ +static const vshCmdInfo info_node_device_dumpxml[] = { + {"help", N_("node device details in XML")}, + {"desc", N_("Output the node device details as an XML dump to stdout.")}, + {NULL, NULL} +}; + + +static const vshCmdOptDef opts_node_device_dumpxml[] = { + {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd) +{ + const char *name = NULL; + virNodeDevicePtr device; + char *xml; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (vshCommandOptString(cmd, "device", &name) <= 0) + return false; + if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { + vshError(ctl, "%s '%s'", _("Could not find matching device"), name); + return false; + } + + xml = virNodeDeviceGetXMLDesc(device, 0); + if (!xml) { + virNodeDeviceFree(device); + return false; + } + + vshPrint(ctl, "%s\n", xml); + VIR_FREE(xml); + virNodeDeviceFree(device); + return true; +} + +/* + * "nodedev-detach" command + */ +static const vshCmdInfo info_node_device_detach[] = { + {"help", N_("detach node device from its device driver")}, + {"desc", N_("Detach node device from its device driver before assigning to a domain.")}, + {NULL, NULL} +}; + + +static const vshCmdOptDef opts_node_device_detach[] = { + {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceDetach(vshControl *ctl, const vshCmd *cmd) +{ + const char *name = NULL; + virNodeDevicePtr device; + bool ret = true; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (vshCommandOptString(cmd, "device", &name) <= 0) + return false; + if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { + vshError(ctl, "%s '%s'", _("Could not find matching device"), name); + return false; + } + + /* Yes, our public API is misspelled. At least virsh can accept + * either spelling. */ + if (virNodeDeviceDettach(device) == 0) { + vshPrint(ctl, _("Device %s detached\n"), name); + } else { + vshError(ctl, _("Failed to detach device %s"), name); + ret = false; + } + virNodeDeviceFree(device); + return ret; +} + +/* + * "nodedev-reattach" command + */ +static const vshCmdInfo info_node_device_reattach[] = { + {"help", N_("reattach node device to its device driver")}, + {"desc", N_("Reattach node device to its device driver once released by the domain.")}, + {NULL, NULL} +}; + + +static const vshCmdOptDef opts_node_device_reattach[] = { + {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceReAttach(vshControl *ctl, const vshCmd *cmd) +{ + const char *name = NULL; + virNodeDevicePtr device; + bool ret = true; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (vshCommandOptString(cmd, "device", &name) <= 0) + return false; + if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { + vshError(ctl, "%s '%s'", _("Could not find matching device"), name); + return false; + } + + if (virNodeDeviceReAttach(device) == 0) { + vshPrint(ctl, _("Device %s re-attached\n"), name); + } else { + vshError(ctl, _("Failed to re-attach device %s"), name); + ret = false; + } + virNodeDeviceFree(device); + return ret; +} + +/* + * "nodedev-reset" command + */ +static const vshCmdInfo info_node_device_reset[] = { + {"help", N_("reset node device")}, + {"desc", N_("Reset node device before or after assigning to a domain.")}, + {NULL, NULL} +}; + + +static const vshCmdOptDef opts_node_device_reset[] = { + {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, + {NULL, 0, 0, NULL} +}; + +static bool +cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd) +{ + const char *name = NULL; + virNodeDevicePtr device; + bool ret = true; + + if (!vshConnectionUsability(ctl, ctl->conn)) + return false; + if (vshCommandOptString(cmd, "device", &name) <= 0) + return false; + if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { + vshError(ctl, "%s '%s'", _("Could not find matching device"), name); + return false; + } + + if (virNodeDeviceReset(device) == 0) { + vshPrint(ctl, _("Device %s reset\n"), name); + } else { + vshError(ctl, _("Failed to reset device %s"), name); + ret = false; + } + virNodeDeviceFree(device); + return ret; +} + diff --git a/tools/virsh.c b/tools/virsh.c index 1d878b9..e461410 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -746,100 +746,6 @@ cmdHelp(vshControl *ctl, const vshCmd *cmd) } } -/* - * "nodedev-create" command - */ -static const vshCmdInfo info_node_device_create[] = { - {"help", N_("create a device defined " - "by an XML file on the node")}, - {"desc", N_("Create a device on the node. Note that this " - "command creates devices on the physical host " - "that can then be assigned to a virtual machine.")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_device_create[] = { - {"file", VSH_OT_DATA, VSH_OFLAG_REQ, - N_("file containing an XML description of the device")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceCreate(vshControl *ctl, const vshCmd *cmd) -{ - virNodeDevicePtr dev = NULL; - const char *from = NULL; - bool ret = true; - char *buffer; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "file", &from) <= 0) - return false; - - if (virFileReadAll(from, VIRSH_MAX_XML_FILE, &buffer) < 0) - return false; - - dev = virNodeDeviceCreateXML(ctl->conn, buffer, 0); - VIR_FREE(buffer); - - if (dev != NULL) { - vshPrint(ctl, _("Node device %s created from %s\n"), - virNodeDeviceGetName(dev), from); - virNodeDeviceFree(dev); - } else { - vshError(ctl, _("Failed to create node device from %s"), from); - ret = false; - } - - return ret; -} - - -/* - * "nodedev-destroy" command - */ -static const vshCmdInfo info_node_device_destroy[] = { - {"help", N_("destroy (stop) a device on the node")}, - {"desc", N_("Destroy a device on the node. Note that this " - "command destroys devices on the physical host")}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_device_destroy[] = { - {"name", VSH_OT_DATA, VSH_OFLAG_REQ, - N_("name of the device to be destroyed")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceDestroy(vshControl *ctl, const vshCmd *cmd) -{ - virNodeDevicePtr dev = NULL; - bool ret = true; - const char *name = NULL; - - if (!vshConnectionUsability(ctl, ctl->conn)) { - return false; - } - - if (vshCommandOptString(cmd, "name", &name) <= 0) - return false; - - dev = virNodeDeviceLookupByName(ctl->conn, name); - - if (virNodeDeviceDestroy(dev) == 0) { - vshPrint(ctl, _("Destroyed node device '%s'\n"), name); - } else { - vshError(ctl, _("Failed to destroy node device '%s'"), name); - ret = false; - } - - virNodeDeviceFree(dev); - return ret; -} - /* Tree listing helpers. */ /* Given an index, return either the name of that device (non-NULL) or @@ -928,270 +834,6 @@ vshTreePrint(vshControl *ctl, vshTreeLookup lookup, void *opaque, return ret; } -struct vshNodeList { - char **names; - char **parents; -}; - -static const char * -vshNodeListLookup(int devid, bool parent, void *opaque) -{ - struct vshNodeList *arrays = opaque; - if (parent) - return arrays->parents[devid]; - return arrays->names[devid]; -} - -/* - * "nodedev-list" command - */ -static const vshCmdInfo info_node_list_devices[] = { - {"help", N_("enumerate devices on this host")}, - {"desc", ""}, - {NULL, NULL} -}; - -static const vshCmdOptDef opts_node_list_devices[] = { - {"tree", VSH_OT_BOOL, 0, N_("list devices in a tree")}, - {"cap", VSH_OT_STRING, VSH_OFLAG_NONE, N_("capability name")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeListDevices(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) -{ - const char *cap = NULL; - char **devices; - int num_devices, i; - bool tree = vshCommandOptBool(cmd, "tree"); - bool ret = true; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - - if (vshCommandOptString(cmd, "cap", &cap) <= 0) - cap = NULL; - - num_devices = virNodeNumOfDevices(ctl->conn, cap, 0); - if (num_devices < 0) { - vshError(ctl, "%s", _("Failed to count node devices")); - return false; - } else if (num_devices == 0) { - return true; - } - - devices = vshMalloc(ctl, sizeof(char *) * num_devices); - num_devices = - virNodeListDevices(ctl->conn, cap, devices, num_devices, 0); - if (num_devices < 0) { - vshError(ctl, "%s", _("Failed to list node devices")); - VIR_FREE(devices); - return false; - } - qsort(&devices[0], num_devices, sizeof(char*), vshNameSorter); - if (tree) { - char **parents = vshMalloc(ctl, sizeof(char *) * num_devices); - struct vshNodeList arrays = { devices, parents }; - - for (i = 0; i < num_devices; i++) { - virNodeDevicePtr dev = virNodeDeviceLookupByName(ctl->conn, devices[i]); - if (dev && STRNEQ(devices[i], "computer")) { - const char *parent = virNodeDeviceGetParent(dev); - parents[i] = parent ? vshStrdup(ctl, parent) : NULL; - } else { - parents[i] = NULL; - } - virNodeDeviceFree(dev); - } - for (i = 0 ; i < num_devices ; i++) { - if (parents[i] == NULL && - vshTreePrint(ctl, vshNodeListLookup, &arrays, num_devices, - i) < 0) - ret = false; - } - for (i = 0 ; i < num_devices ; i++) { - VIR_FREE(devices[i]); - VIR_FREE(parents[i]); - } - VIR_FREE(parents); - } else { - for (i = 0; i < num_devices; i++) { - vshPrint(ctl, "%s\n", devices[i]); - VIR_FREE(devices[i]); - } - } - VIR_FREE(devices); - return ret; -} - -/* - * "nodedev-dumpxml" command - */ -static const vshCmdInfo info_node_device_dumpxml[] = { - {"help", N_("node device details in XML")}, - {"desc", N_("Output the node device details as an XML dump to stdout.")}, - {NULL, NULL} -}; - - -static const vshCmdOptDef opts_node_device_dumpxml[] = { - {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceDumpXML(vshControl *ctl, const vshCmd *cmd) -{ - const char *name = NULL; - virNodeDevicePtr device; - char *xml; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (vshCommandOptString(cmd, "device", &name) <= 0) - return false; - if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { - vshError(ctl, "%s '%s'", _("Could not find matching device"), name); - return false; - } - - xml = virNodeDeviceGetXMLDesc(device, 0); - if (!xml) { - virNodeDeviceFree(device); - return false; - } - - vshPrint(ctl, "%s\n", xml); - VIR_FREE(xml); - virNodeDeviceFree(device); - return true; -} - -/* - * "nodedev-detach" command - */ -static const vshCmdInfo info_node_device_detach[] = { - {"help", N_("detach node device from its device driver")}, - {"desc", N_("Detach node device from its device driver before assigning to a domain.")}, - {NULL, NULL} -}; - - -static const vshCmdOptDef opts_node_device_detach[] = { - {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceDetach(vshControl *ctl, const vshCmd *cmd) -{ - const char *name = NULL; - virNodeDevicePtr device; - bool ret = true; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (vshCommandOptString(cmd, "device", &name) <= 0) - return false; - if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { - vshError(ctl, "%s '%s'", _("Could not find matching device"), name); - return false; - } - - /* Yes, our public API is misspelled. At least virsh can accept - * either spelling. */ - if (virNodeDeviceDettach(device) == 0) { - vshPrint(ctl, _("Device %s detached\n"), name); - } else { - vshError(ctl, _("Failed to detach device %s"), name); - ret = false; - } - virNodeDeviceFree(device); - return ret; -} - -/* - * "nodedev-reattach" command - */ -static const vshCmdInfo info_node_device_reattach[] = { - {"help", N_("reattach node device to its device driver")}, - {"desc", N_("Reattach node device to its device driver once released by the domain.")}, - {NULL, NULL} -}; - - -static const vshCmdOptDef opts_node_device_reattach[] = { - {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceReAttach(vshControl *ctl, const vshCmd *cmd) -{ - const char *name = NULL; - virNodeDevicePtr device; - bool ret = true; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (vshCommandOptString(cmd, "device", &name) <= 0) - return false; - if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { - vshError(ctl, "%s '%s'", _("Could not find matching device"), name); - return false; - } - - if (virNodeDeviceReAttach(device) == 0) { - vshPrint(ctl, _("Device %s re-attached\n"), name); - } else { - vshError(ctl, _("Failed to re-attach device %s"), name); - ret = false; - } - virNodeDeviceFree(device); - return ret; -} - -/* - * "nodedev-reset" command - */ -static const vshCmdInfo info_node_device_reset[] = { - {"help", N_("reset node device")}, - {"desc", N_("Reset node device before or after assigning to a domain.")}, - {NULL, NULL} -}; - - -static const vshCmdOptDef opts_node_device_reset[] = { - {"device", VSH_OT_DATA, VSH_OFLAG_REQ, N_("device key")}, - {NULL, 0, 0, NULL} -}; - -static bool -cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd) -{ - const char *name = NULL; - virNodeDevicePtr device; - bool ret = true; - - if (!vshConnectionUsability(ctl, ctl->conn)) - return false; - if (vshCommandOptString(cmd, "device", &name) <= 0) - return false; - if (!(device = virNodeDeviceLookupByName(ctl->conn, name))) { - vshError(ctl, "%s '%s'", _("Could not find matching device"), name); - return false; - } - - if (virNodeDeviceReset(device) == 0) { - vshPrint(ctl, _("Device %s reset\n"), name); - } else { - vshError(ctl, _("Failed to reset device %s"), name); - ret = false; - } - virNodeDeviceFree(device); - return ret; -} - /* Common code for the edit / net-edit / pool-edit functions which follow. */ static char * editWriteToTempFile(vshControl *ctl, const char *doc) @@ -3709,6 +3351,8 @@ static const vshCmdDef networkCmds[] = { {NULL, NULL, NULL, NULL, 0} }; +#include "virsh-nodedev.c" + static const vshCmdDef nodedevCmds[] = { {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create, info_node_device_create, 0}, -- 1.7.7.3

--- tools/virsh-domain-monitor.c | 16 ++ tools/virsh-domain.c | 95 +++++++++++++ tools/virsh-host.c | 19 +++ tools/virsh-interface.c | 32 ++++ tools/virsh-network.c | 22 +++ tools/virsh-nodedev.c | 19 +++ tools/virsh-nwfilter.c | 14 ++ tools/virsh-pool.c | 27 ++++ tools/virsh-secret.c | 15 ++ tools/virsh-snapshot.c | 24 +++ tools/virsh-volume.c | 22 +++ tools/virsh.c | 320 +----------------------------------------- 12 files changed, 307 insertions(+), 318 deletions(-) diff --git a/tools/virsh-domain-monitor.c b/tools/virsh-domain-monitor.c index 1a61f62..249ff13 100644 --- a/tools/virsh-domain-monitor.c +++ b/tools/virsh-domain-monitor.c @@ -1683,3 +1683,19 @@ cleanup: return ret; } #undef FILTER + +static const vshCmdDef domMonitoringCmds[] = { + {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0}, + {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0}, + {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0}, + {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0}, + {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0}, + {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0}, + {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0}, + {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0}, + {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0}, + {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0}, + {"domstate", cmdDomstate, opts_domstate, info_domstate, 0}, + {"list", cmdList, opts_list, info_list, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-domain.c b/tools/virsh-domain.c index 22d002c..6da4f46 100644 --- a/tools/virsh-domain.c +++ b/tools/virsh-domain.c @@ -8042,3 +8042,98 @@ cleanup: virDomainFree(dom); return ret; } + +static const vshCmdDef domManagementCmds[] = { + {"attach-device", cmdAttachDevice, opts_attach_device, + info_attach_device, 0}, + {"attach-disk", cmdAttachDisk, opts_attach_disk, + info_attach_disk, 0}, + {"attach-interface", cmdAttachInterface, opts_attach_interface, + info_attach_interface, 0}, + {"autostart", cmdAutostart, opts_autostart, info_autostart, 0}, + {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0}, + {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0}, + {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0}, + {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0}, + {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0}, + {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0}, + {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0}, +#ifndef WIN32 + {"console", cmdConsole, opts_console, info_console, 0}, +#endif + {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0}, + {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0}, + {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0}, + {"create", cmdCreate, opts_create, info_create, 0}, + {"define", cmdDefine, opts_define, info_define, 0}, + {"desc", cmdDesc, opts_desc, info_desc, 0}, + {"destroy", cmdDestroy, opts_destroy, info_destroy, 0}, + {"detach-device", cmdDetachDevice, opts_detach_device, + info_detach_device, 0}, + {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0}, + {"detach-interface", cmdDetachInterface, opts_detach_interface, + info_detach_interface, 0}, + {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0}, + {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0}, + {"domid", cmdDomid, opts_domid, info_domid, 0}, + {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0}, + {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0}, + {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0}, + {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0}, + {"domname", cmdDomname, opts_domname, info_domname, 0}, + {"dompmsuspend", cmdDomPMSuspend, + opts_dom_pm_suspend, info_dom_pm_suspend, 0}, + {"dompmwakeup", cmdDomPMWakeup, + opts_dom_pm_wakeup, info_dom_pm_wakeup, 0}, + {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0}, + {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative, + info_domxmlfromnative, 0}, + {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative, + info_domxmltonative, 0}, + {"dump", cmdDump, opts_dump, info_dump, 0}, + {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0}, + {"edit", cmdEdit, opts_edit, info_edit, 0}, + {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0}, + {"send-key", cmdSendKey, opts_send_key, info_send_key, 0}, + {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0}, + {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove, + info_managedsaveremove, 0}, + {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0}, + {"memtune", cmdMemtune, opts_memtune, info_memtune, 0}, + {"migrate", cmdMigrate, opts_migrate, info_migrate, 0}, + {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime, + opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0}, + {"migrate-setspeed", cmdMigrateSetMaxSpeed, + opts_migrate_setspeed, info_migrate_setspeed, 0}, + {"migrate-getspeed", cmdMigrateGetMaxSpeed, + opts_migrate_getspeed, info_migrate_getspeed, 0}, + {"numatune", cmdNumatune, opts_numatune, info_numatune, 0}, + {"reboot", cmdReboot, opts_reboot, info_reboot, 0}, + {"reset", cmdReset, opts_reset, info_reset, 0}, + {"restore", cmdRestore, opts_restore, info_restore, 0}, + {"resume", cmdResume, opts_resume, info_resume, 0}, + {"save", cmdSave, opts_save, info_save, 0}, + {"save-image-define", cmdSaveImageDefine, opts_save_image_define, + info_save_image_define, 0}, + {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml, + info_save_image_dumpxml, 0}, + {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit, + info_save_image_edit, 0}, + {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0}, + {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0}, + {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0}, + {"setmem", cmdSetmem, opts_setmem, info_setmem, 0}, + {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0}, + {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0}, + {"start", cmdStart, opts_start, info_start, 0}, + {"suspend", cmdSuspend, opts_suspend, info_suspend, 0}, + {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0}, + {"undefine", cmdUndefine, opts_undefine, info_undefine, 0}, + {"update-device", cmdUpdateDevice, opts_update_device, + info_update_device, 0}, + {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0}, + {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0}, + {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0}, + {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-host.c b/tools/virsh-host.c index c6296d3..298fb2a 100644 --- a/tools/virsh-host.c +++ b/tools/virsh-host.c @@ -818,3 +818,22 @@ cmdVersion(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) return true; } + +static const vshCmdDef hostAndHypervisorCmds[] = { + {"capabilities", cmdCapabilities, NULL, info_capabilities, 0}, + {"connect", cmdConnect, opts_connect, info_connect, + VSH_CMD_FLAG_NOCONNECT}, + {"freecell", cmdFreecell, opts_freecell, info_freecell, 0}, + {"hostname", cmdHostname, NULL, info_hostname, 0}, + {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0}, + {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0}, + {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0}, + {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0}, + {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0}, + {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command, + info_qemu_monitor_command, 0}, + {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0}, + {"uri", cmdURI, NULL, info_uri, 0}, + {"version", cmdVersion, opts_version, info_version, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-interface.c b/tools/virsh-interface.c index 6a43bb1..8c116c8 100644 --- a/tools/virsh-interface.c +++ b/tools/virsh-interface.c @@ -998,3 +998,35 @@ cmdInterfaceUnbridge(vshControl *ctl, const vshCmd *cmd) xmlFreeDoc(xml_doc); return ret; } + +static const vshCmdDef ifaceCmds[] = { + {"iface-begin", cmdInterfaceBegin, opts_interface_begin, + info_interface_begin, 0}, + {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge, + info_interface_bridge, 0}, + {"iface-commit", cmdInterfaceCommit, opts_interface_commit, + info_interface_commit, 0}, + {"iface-define", cmdInterfaceDefine, opts_interface_define, + info_interface_define, 0}, + {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy, + info_interface_destroy, 0}, + {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml, + info_interface_dumpxml, 0}, + {"iface-edit", cmdInterfaceEdit, opts_interface_edit, + info_interface_edit, 0}, + {"iface-list", cmdInterfaceList, opts_interface_list, + info_interface_list, 0}, + {"iface-mac", cmdInterfaceMAC, opts_interface_mac, + info_interface_mac, 0}, + {"iface-name", cmdInterfaceName, opts_interface_name, + info_interface_name, 0}, + {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback, + info_interface_rollback, 0}, + {"iface-start", cmdInterfaceStart, opts_interface_start, + info_interface_start, 0}, + {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge, + info_interface_unbridge, 0}, + {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine, + info_interface_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-network.c b/tools/virsh-network.c index 459ccfe..f5df891 100644 --- a/tools/virsh-network.c +++ b/tools/virsh-network.c @@ -686,3 +686,25 @@ cmdNetworkEdit(vshControl *ctl, const vshCmd *cmd) return ret; } + +static const vshCmdDef networkCmds[] = { + {"net-autostart", cmdNetworkAutostart, opts_network_autostart, + info_network_autostart, 0}, + {"net-create", cmdNetworkCreate, opts_network_create, + info_network_create, 0}, + {"net-define", cmdNetworkDefine, opts_network_define, + info_network_define, 0}, + {"net-destroy", cmdNetworkDestroy, opts_network_destroy, + info_network_destroy, 0}, + {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, + info_network_dumpxml, 0}, + {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0}, + {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0}, + {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0}, + {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0}, + {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0}, + {"net-undefine", cmdNetworkUndefine, opts_network_undefine, + info_network_undefine, 0}, + {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-nodedev.c b/tools/virsh-nodedev.c index ee9a6fd..ecff0d7 100644 --- a/tools/virsh-nodedev.c +++ b/tools/virsh-nodedev.c @@ -381,3 +381,22 @@ cmdNodeDeviceReset(vshControl *ctl, const vshCmd *cmd) return ret; } +static const vshCmdDef nodedevCmds[] = { + {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create, + info_node_device_create, 0}, + {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy, + info_node_device_destroy, 0}, + {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach, + info_node_device_detach, 0}, + {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach, + info_node_device_detach, VSH_CMD_FLAG_ALIAS}, + {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml, + info_node_device_dumpxml, 0}, + {"nodedev-list", cmdNodeListDevices, opts_node_list_devices, + info_node_list_devices, 0}, + {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach, + info_node_device_reattach, 0}, + {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset, + info_node_device_reset, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-nwfilter.c b/tools/virsh-nwfilter.c index 4b4996a..1fbe253 100644 --- a/tools/virsh-nwfilter.c +++ b/tools/virsh-nwfilter.c @@ -308,3 +308,17 @@ cleanup: return ret; } + +static const vshCmdDef nwfilterCmds[] = { + {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define, + info_nwfilter_define, 0}, + {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml, + info_nwfilter_dumpxml, 0}, + {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit, + info_nwfilter_edit, 0}, + {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list, + info_nwfilter_list, 0}, + {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine, + info_nwfilter_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-pool.c b/tools/virsh-pool.c index 6a1208f..6c8e0a3 100644 --- a/tools/virsh-pool.c +++ b/tools/virsh-pool.c @@ -1413,3 +1413,30 @@ cmdPoolEdit(vshControl *ctl, const vshCmd *cmd) return ret; } + +static const vshCmdDef storagePoolCmds[] = { + {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs, + opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0}, + {"find-storage-pool-sources", cmdPoolDiscoverSources, + opts_find_storage_pool_sources, info_find_storage_pool_sources, 0}, + {"pool-autostart", cmdPoolAutostart, opts_pool_autostart, + info_pool_autostart, 0}, + {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0}, + {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0}, + {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0}, + {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0}, + {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0}, + {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0}, + {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0}, + {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0}, + {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0}, + {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0}, + {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0}, + {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0}, + {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0}, + {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0}, + {"pool-undefine", cmdPoolUndefine, opts_pool_undefine, + info_pool_undefine, 0}, + {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-secret.c b/tools/virsh-secret.c index 9ec3186..6cbc635 100644 --- a/tools/virsh-secret.c +++ b/tools/virsh-secret.c @@ -356,3 +356,18 @@ cmdSecretList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED) VIR_FREE(uuids); return true; } + +static const vshCmdDef secretCmds[] = { + {"secret-define", cmdSecretDefine, opts_secret_define, + info_secret_define, 0}, + {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml, + info_secret_dumpxml, 0}, + {"secret-get-value", cmdSecretGetValue, opts_secret_get_value, + info_secret_get_value, 0}, + {"secret-list", cmdSecretList, NULL, info_secret_list, 0}, + {"secret-set-value", cmdSecretSetValue, opts_secret_set_value, + info_secret_set_value, 0}, + {"secret-undefine", cmdSecretUndefine, opts_secret_undefine, + info_secret_undefine, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-snapshot.c b/tools/virsh-snapshot.c index c0a2d9d..819e7b3 100644 --- a/tools/virsh-snapshot.c +++ b/tools/virsh-snapshot.c @@ -1602,3 +1602,27 @@ cleanup: return ret; } + +static const vshCmdDef snapshotCmds[] = { + {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create, + info_snapshot_create, 0}, + {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as, + info_snapshot_create_as, 0}, + {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current, + info_snapshot_current, 0}, + {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete, + info_snapshot_delete, 0}, + {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml, + info_snapshot_dumpxml, 0}, + {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit, + info_snapshot_edit, 0}, + {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info, + info_snapshot_info, 0}, + {"snapshot-list", cmdSnapshotList, opts_snapshot_list, + info_snapshot_list, 0}, + {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent, + info_snapshot_parent, 0}, + {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert, + info_snapshot_revert, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh-volume.c b/tools/virsh-volume.c index 6fb721e..39ba59a 100644 --- a/tools/virsh-volume.c +++ b/tools/virsh-volume.c @@ -1438,3 +1438,25 @@ cmdVolPath(vshControl *ctl, const vshCmd *cmd) virStorageVolFree(vol); return true; } + +static const vshCmdDef storageVolCmds[] = { + {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0}, + {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, + info_vol_create_as, 0}, + {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0}, + {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from, + info_vol_create_from, 0}, + {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0}, + {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0}, + {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0}, + {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0}, + {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0}, + {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0}, + {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0}, + {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0}, + {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0}, + {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0}, + {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0}, + {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0}, + {NULL, NULL, NULL, NULL, 0} +}; diff --git a/tools/virsh.c b/tools/virsh.c index e461410..8840460 100644 --- a/tools/virsh.c +++ b/tools/virsh.c @@ -3160,285 +3160,16 @@ vshParseArgv(vshControl *ctl, int argc, char **argv) } #include "virsh-domain.c" - -static const vshCmdDef domManagementCmds[] = { - {"attach-device", cmdAttachDevice, opts_attach_device, - info_attach_device, 0}, - {"attach-disk", cmdAttachDisk, opts_attach_disk, - info_attach_disk, 0}, - {"attach-interface", cmdAttachInterface, opts_attach_interface, - info_attach_interface, 0}, - {"autostart", cmdAutostart, opts_autostart, info_autostart, 0}, - {"blkdeviotune", cmdBlkdeviotune, opts_blkdeviotune, info_blkdeviotune, 0}, - {"blkiotune", cmdBlkiotune, opts_blkiotune, info_blkiotune, 0}, - {"blockcopy", cmdBlockCopy, opts_block_copy, info_block_copy, 0}, - {"blockjob", cmdBlockJob, opts_block_job, info_block_job, 0}, - {"blockpull", cmdBlockPull, opts_block_pull, info_block_pull, 0}, - {"blockresize", cmdBlockResize, opts_block_resize, info_block_resize, 0}, - {"change-media", cmdChangeMedia, opts_change_media, info_change_media, 0}, -#ifndef WIN32 - {"console", cmdConsole, opts_console, info_console, 0}, -#endif - {"cpu-baseline", cmdCPUBaseline, opts_cpu_baseline, info_cpu_baseline, 0}, - {"cpu-compare", cmdCPUCompare, opts_cpu_compare, info_cpu_compare, 0}, - {"cpu-stats", cmdCPUStats, opts_cpu_stats, info_cpu_stats, 0}, - {"create", cmdCreate, opts_create, info_create, 0}, - {"define", cmdDefine, opts_define, info_define, 0}, - {"desc", cmdDesc, opts_desc, info_desc, 0}, - {"destroy", cmdDestroy, opts_destroy, info_destroy, 0}, - {"detach-device", cmdDetachDevice, opts_detach_device, - info_detach_device, 0}, - {"detach-disk", cmdDetachDisk, opts_detach_disk, info_detach_disk, 0}, - {"detach-interface", cmdDetachInterface, opts_detach_interface, - info_detach_interface, 0}, - {"domdisplay", cmdDomDisplay, opts_domdisplay, info_domdisplay, 0}, - {"domhostname", cmdDomHostname, opts_domhostname, info_domhostname, 0}, - {"domid", cmdDomid, opts_domid, info_domid, 0}, - {"domif-setlink", cmdDomIfSetLink, opts_domif_setlink, info_domif_setlink, 0}, - {"domiftune", cmdDomIftune, opts_domiftune, info_domiftune, 0}, - {"domjobabort", cmdDomjobabort, opts_domjobabort, info_domjobabort, 0}, - {"domjobinfo", cmdDomjobinfo, opts_domjobinfo, info_domjobinfo, 0}, - {"domname", cmdDomname, opts_domname, info_domname, 0}, - {"dompmsuspend", cmdDomPMSuspend, - opts_dom_pm_suspend, info_dom_pm_suspend, 0}, - {"dompmwakeup", cmdDomPMWakeup, - opts_dom_pm_wakeup, info_dom_pm_wakeup, 0}, - {"domuuid", cmdDomuuid, opts_domuuid, info_domuuid, 0}, - {"domxml-from-native", cmdDomXMLFromNative, opts_domxmlfromnative, - info_domxmlfromnative, 0}, - {"domxml-to-native", cmdDomXMLToNative, opts_domxmltonative, - info_domxmltonative, 0}, - {"dump", cmdDump, opts_dump, info_dump, 0}, - {"dumpxml", cmdDumpXML, opts_dumpxml, info_dumpxml, 0}, - {"edit", cmdEdit, opts_edit, info_edit, 0}, - {"inject-nmi", cmdInjectNMI, opts_inject_nmi, info_inject_nmi, 0}, - {"send-key", cmdSendKey, opts_send_key, info_send_key, 0}, - {"managedsave", cmdManagedSave, opts_managedsave, info_managedsave, 0}, - {"managedsave-remove", cmdManagedSaveRemove, opts_managedsaveremove, - info_managedsaveremove, 0}, - {"maxvcpus", cmdMaxvcpus, opts_maxvcpus, info_maxvcpus, 0}, - {"memtune", cmdMemtune, opts_memtune, info_memtune, 0}, - {"migrate", cmdMigrate, opts_migrate, info_migrate, 0}, - {"migrate-setmaxdowntime", cmdMigrateSetMaxDowntime, - opts_migrate_setmaxdowntime, info_migrate_setmaxdowntime, 0}, - {"migrate-setspeed", cmdMigrateSetMaxSpeed, - opts_migrate_setspeed, info_migrate_setspeed, 0}, - {"migrate-getspeed", cmdMigrateGetMaxSpeed, - opts_migrate_getspeed, info_migrate_getspeed, 0}, - {"numatune", cmdNumatune, opts_numatune, info_numatune, 0}, - {"reboot", cmdReboot, opts_reboot, info_reboot, 0}, - {"reset", cmdReset, opts_reset, info_reset, 0}, - {"restore", cmdRestore, opts_restore, info_restore, 0}, - {"resume", cmdResume, opts_resume, info_resume, 0}, - {"save", cmdSave, opts_save, info_save, 0}, - {"save-image-define", cmdSaveImageDefine, opts_save_image_define, - info_save_image_define, 0}, - {"save-image-dumpxml", cmdSaveImageDumpxml, opts_save_image_dumpxml, - info_save_image_dumpxml, 0}, - {"save-image-edit", cmdSaveImageEdit, opts_save_image_edit, - info_save_image_edit, 0}, - {"schedinfo", cmdSchedinfo, opts_schedinfo, info_schedinfo, 0}, - {"screenshot", cmdScreenshot, opts_screenshot, info_screenshot, 0}, - {"setmaxmem", cmdSetmaxmem, opts_setmaxmem, info_setmaxmem, 0}, - {"setmem", cmdSetmem, opts_setmem, info_setmem, 0}, - {"setvcpus", cmdSetvcpus, opts_setvcpus, info_setvcpus, 0}, - {"shutdown", cmdShutdown, opts_shutdown, info_shutdown, 0}, - {"start", cmdStart, opts_start, info_start, 0}, - {"suspend", cmdSuspend, opts_suspend, info_suspend, 0}, - {"ttyconsole", cmdTTYConsole, opts_ttyconsole, info_ttyconsole, 0}, - {"undefine", cmdUndefine, opts_undefine, info_undefine, 0}, - {"update-device", cmdUpdateDevice, opts_update_device, - info_update_device, 0}, - {"vcpucount", cmdVcpucount, opts_vcpucount, info_vcpucount, 0}, - {"vcpuinfo", cmdVcpuinfo, opts_vcpuinfo, info_vcpuinfo, 0}, - {"vcpupin", cmdVcpuPin, opts_vcpupin, info_vcpupin, 0}, - {"vncdisplay", cmdVNCDisplay, opts_vncdisplay, info_vncdisplay, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-domain-monitor.c" - -static const vshCmdDef domMonitoringCmds[] = { - {"domblkerror", cmdDomBlkError, opts_domblkerror, info_domblkerror, 0}, - {"domblkinfo", cmdDomblkinfo, opts_domblkinfo, info_domblkinfo, 0}, - {"domblklist", cmdDomblklist, opts_domblklist, info_domblklist, 0}, - {"domblkstat", cmdDomblkstat, opts_domblkstat, info_domblkstat, 0}, - {"domcontrol", cmdDomControl, opts_domcontrol, info_domcontrol, 0}, - {"domif-getlink", cmdDomIfGetLink, opts_domif_getlink, info_domif_getlink, 0}, - {"domiflist", cmdDomiflist, opts_domiflist, info_domiflist, 0}, - {"domifstat", cmdDomIfstat, opts_domifstat, info_domifstat, 0}, - {"dominfo", cmdDominfo, opts_dominfo, info_dominfo, 0}, - {"dommemstat", cmdDomMemStat, opts_dommemstat, info_dommemstat, 0}, - {"domstate", cmdDomstate, opts_domstate, info_domstate, 0}, - {"list", cmdList, opts_list, info_list, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-pool.c" - -static const vshCmdDef storagePoolCmds[] = { - {"find-storage-pool-sources-as", cmdPoolDiscoverSourcesAs, - opts_find_storage_pool_sources_as, info_find_storage_pool_sources_as, 0}, - {"find-storage-pool-sources", cmdPoolDiscoverSources, - opts_find_storage_pool_sources, info_find_storage_pool_sources, 0}, - {"pool-autostart", cmdPoolAutostart, opts_pool_autostart, - info_pool_autostart, 0}, - {"pool-build", cmdPoolBuild, opts_pool_build, info_pool_build, 0}, - {"pool-create-as", cmdPoolCreateAs, opts_pool_X_as, info_pool_create_as, 0}, - {"pool-create", cmdPoolCreate, opts_pool_create, info_pool_create, 0}, - {"pool-define-as", cmdPoolDefineAs, opts_pool_X_as, info_pool_define_as, 0}, - {"pool-define", cmdPoolDefine, opts_pool_define, info_pool_define, 0}, - {"pool-delete", cmdPoolDelete, opts_pool_delete, info_pool_delete, 0}, - {"pool-destroy", cmdPoolDestroy, opts_pool_destroy, info_pool_destroy, 0}, - {"pool-dumpxml", cmdPoolDumpXML, opts_pool_dumpxml, info_pool_dumpxml, 0}, - {"pool-edit", cmdPoolEdit, opts_pool_edit, info_pool_edit, 0}, - {"pool-info", cmdPoolInfo, opts_pool_info, info_pool_info, 0}, - {"pool-list", cmdPoolList, opts_pool_list, info_pool_list, 0}, - {"pool-name", cmdPoolName, opts_pool_name, info_pool_name, 0}, - {"pool-refresh", cmdPoolRefresh, opts_pool_refresh, info_pool_refresh, 0}, - {"pool-start", cmdPoolStart, opts_pool_start, info_pool_start, 0}, - {"pool-undefine", cmdPoolUndefine, opts_pool_undefine, - info_pool_undefine, 0}, - {"pool-uuid", cmdPoolUuid, opts_pool_uuid, info_pool_uuid, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-volume.c" - -static const vshCmdDef storageVolCmds[] = { - {"vol-clone", cmdVolClone, opts_vol_clone, info_vol_clone, 0}, - {"vol-create-as", cmdVolCreateAs, opts_vol_create_as, - info_vol_create_as, 0}, - {"vol-create", cmdVolCreate, opts_vol_create, info_vol_create, 0}, - {"vol-create-from", cmdVolCreateFrom, opts_vol_create_from, - info_vol_create_from, 0}, - {"vol-delete", cmdVolDelete, opts_vol_delete, info_vol_delete, 0}, - {"vol-download", cmdVolDownload, opts_vol_download, info_vol_download, 0}, - {"vol-dumpxml", cmdVolDumpXML, opts_vol_dumpxml, info_vol_dumpxml, 0}, - {"vol-info", cmdVolInfo, opts_vol_info, info_vol_info, 0}, - {"vol-key", cmdVolKey, opts_vol_key, info_vol_key, 0}, - {"vol-list", cmdVolList, opts_vol_list, info_vol_list, 0}, - {"vol-name", cmdVolName, opts_vol_name, info_vol_name, 0}, - {"vol-path", cmdVolPath, opts_vol_path, info_vol_path, 0}, - {"vol-pool", cmdVolPool, opts_vol_pool, info_vol_pool, 0}, - {"vol-resize", cmdVolResize, opts_vol_resize, info_vol_resize, 0}, - {"vol-upload", cmdVolUpload, opts_vol_upload, info_vol_upload, 0}, - {"vol-wipe", cmdVolWipe, opts_vol_wipe, info_vol_wipe, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-network.c" - -static const vshCmdDef networkCmds[] = { - {"net-autostart", cmdNetworkAutostart, opts_network_autostart, - info_network_autostart, 0}, - {"net-create", cmdNetworkCreate, opts_network_create, - info_network_create, 0}, - {"net-define", cmdNetworkDefine, opts_network_define, - info_network_define, 0}, - {"net-destroy", cmdNetworkDestroy, opts_network_destroy, - info_network_destroy, 0}, - {"net-dumpxml", cmdNetworkDumpXML, opts_network_dumpxml, - info_network_dumpxml, 0}, - {"net-edit", cmdNetworkEdit, opts_network_edit, info_network_edit, 0}, - {"net-info", cmdNetworkInfo, opts_network_info, info_network_info, 0}, - {"net-list", cmdNetworkList, opts_network_list, info_network_list, 0}, - {"net-name", cmdNetworkName, opts_network_name, info_network_name, 0}, - {"net-start", cmdNetworkStart, opts_network_start, info_network_start, 0}, - {"net-undefine", cmdNetworkUndefine, opts_network_undefine, - info_network_undefine, 0}, - {"net-uuid", cmdNetworkUuid, opts_network_uuid, info_network_uuid, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-nodedev.c" - -static const vshCmdDef nodedevCmds[] = { - {"nodedev-create", cmdNodeDeviceCreate, opts_node_device_create, - info_node_device_create, 0}, - {"nodedev-destroy", cmdNodeDeviceDestroy, opts_node_device_destroy, - info_node_device_destroy, 0}, - {"nodedev-detach", cmdNodeDeviceDetach, opts_node_device_detach, - info_node_device_detach, 0}, - {"nodedev-dettach", cmdNodeDeviceDetach, opts_node_device_detach, - info_node_device_detach, VSH_CMD_FLAG_ALIAS}, - {"nodedev-dumpxml", cmdNodeDeviceDumpXML, opts_node_device_dumpxml, - info_node_device_dumpxml, 0}, - {"nodedev-list", cmdNodeListDevices, opts_node_list_devices, - info_node_list_devices, 0}, - {"nodedev-reattach", cmdNodeDeviceReAttach, opts_node_device_reattach, - info_node_device_reattach, 0}, - {"nodedev-reset", cmdNodeDeviceReset, opts_node_device_reset, - info_node_device_reset, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-interface.c" - -static const vshCmdDef ifaceCmds[] = { - {"iface-begin", cmdInterfaceBegin, opts_interface_begin, - info_interface_begin, 0}, - {"iface-bridge", cmdInterfaceBridge, opts_interface_bridge, - info_interface_bridge, 0}, - {"iface-commit", cmdInterfaceCommit, opts_interface_commit, - info_interface_commit, 0}, - {"iface-define", cmdInterfaceDefine, opts_interface_define, - info_interface_define, 0}, - {"iface-destroy", cmdInterfaceDestroy, opts_interface_destroy, - info_interface_destroy, 0}, - {"iface-dumpxml", cmdInterfaceDumpXML, opts_interface_dumpxml, - info_interface_dumpxml, 0}, - {"iface-edit", cmdInterfaceEdit, opts_interface_edit, - info_interface_edit, 0}, - {"iface-list", cmdInterfaceList, opts_interface_list, - info_interface_list, 0}, - {"iface-mac", cmdInterfaceMAC, opts_interface_mac, - info_interface_mac, 0}, - {"iface-name", cmdInterfaceName, opts_interface_name, - info_interface_name, 0}, - {"iface-rollback", cmdInterfaceRollback, opts_interface_rollback, - info_interface_rollback, 0}, - {"iface-start", cmdInterfaceStart, opts_interface_start, - info_interface_start, 0}, - {"iface-unbridge", cmdInterfaceUnbridge, opts_interface_unbridge, - info_interface_unbridge, 0}, - {"iface-undefine", cmdInterfaceUndefine, opts_interface_undefine, - info_interface_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-nwfilter.c" - -static const vshCmdDef nwfilterCmds[] = { - {"nwfilter-define", cmdNWFilterDefine, opts_nwfilter_define, - info_nwfilter_define, 0}, - {"nwfilter-dumpxml", cmdNWFilterDumpXML, opts_nwfilter_dumpxml, - info_nwfilter_dumpxml, 0}, - {"nwfilter-edit", cmdNWFilterEdit, opts_nwfilter_edit, - info_nwfilter_edit, 0}, - {"nwfilter-list", cmdNWFilterList, opts_nwfilter_list, - info_nwfilter_list, 0}, - {"nwfilter-undefine", cmdNWFilterUndefine, opts_nwfilter_undefine, - info_nwfilter_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - #include "virsh-secret.c" - -static const vshCmdDef secretCmds[] = { - {"secret-define", cmdSecretDefine, opts_secret_define, - info_secret_define, 0}, - {"secret-dumpxml", cmdSecretDumpXML, opts_secret_dumpxml, - info_secret_dumpxml, 0}, - {"secret-get-value", cmdSecretGetValue, opts_secret_get_value, - info_secret_get_value, 0}, - {"secret-list", cmdSecretList, NULL, info_secret_list, 0}, - {"secret-set-value", cmdSecretSetValue, opts_secret_set_value, - info_secret_set_value, 0}, - {"secret-undefine", cmdSecretUndefine, opts_secret_undefine, - info_secret_undefine, 0}, - {NULL, NULL, NULL, NULL, 0} -}; +#include "virsh-snapshot.c" +#include "virsh-host.c" static const vshCmdDef virshCmds[] = { {"cd", cmdCd, opts_cd, info_cd, VSH_CMD_FLAG_NOCONNECT}, @@ -3450,53 +3181,6 @@ static const vshCmdDef virshCmds[] = { {NULL, NULL, NULL, NULL, 0} }; -#include "virsh-snapshot.c" - -static const vshCmdDef snapshotCmds[] = { - {"snapshot-create", cmdSnapshotCreate, opts_snapshot_create, - info_snapshot_create, 0}, - {"snapshot-create-as", cmdSnapshotCreateAs, opts_snapshot_create_as, - info_snapshot_create_as, 0}, - {"snapshot-current", cmdSnapshotCurrent, opts_snapshot_current, - info_snapshot_current, 0}, - {"snapshot-delete", cmdSnapshotDelete, opts_snapshot_delete, - info_snapshot_delete, 0}, - {"snapshot-dumpxml", cmdSnapshotDumpXML, opts_snapshot_dumpxml, - info_snapshot_dumpxml, 0}, - {"snapshot-edit", cmdSnapshotEdit, opts_snapshot_edit, - info_snapshot_edit, 0}, - {"snapshot-info", cmdSnapshotInfo, opts_snapshot_info, - info_snapshot_info, 0}, - {"snapshot-list", cmdSnapshotList, opts_snapshot_list, - info_snapshot_list, 0}, - {"snapshot-parent", cmdSnapshotParent, opts_snapshot_parent, - info_snapshot_parent, 0}, - {"snapshot-revert", cmdDomainSnapshotRevert, opts_snapshot_revert, - info_snapshot_revert, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - -#include "virsh-host.c" - -static const vshCmdDef hostAndHypervisorCmds[] = { - {"capabilities", cmdCapabilities, NULL, info_capabilities, 0}, - {"connect", cmdConnect, opts_connect, info_connect, - VSH_CMD_FLAG_NOCONNECT}, - {"freecell", cmdFreecell, opts_freecell, info_freecell, 0}, - {"hostname", cmdHostname, NULL, info_hostname, 0}, - {"nodecpustats", cmdNodeCpuStats, opts_node_cpustats, info_nodecpustats, 0}, - {"nodeinfo", cmdNodeinfo, NULL, info_nodeinfo, 0}, - {"nodememstats", cmdNodeMemStats, opts_node_memstats, info_nodememstats, 0}, - {"nodesuspend", cmdNodeSuspend, opts_node_suspend, info_nodesuspend, 0}, - {"qemu-attach", cmdQemuAttach, opts_qemu_attach, info_qemu_attach, 0}, - {"qemu-monitor-command", cmdQemuMonitorCommand, opts_qemu_monitor_command, - info_qemu_monitor_command, 0}, - {"sysinfo", cmdSysinfo, NULL, info_sysinfo, 0}, - {"uri", cmdURI, NULL, info_uri, 0}, - {"version", cmdVersion, opts_version, info_version, 0}, - {NULL, NULL, NULL, NULL, 0} -}; - static const vshCmdGrp cmdGroups[] = { {VSH_CMD_GRP_DOM_MANAGEMENT, "domain", domManagementCmds}, {VSH_CMD_GRP_DOM_MONITORING, "monitor", domMonitoringCmds}, -- 1.7.7.3

On 07/23/2012 01:29 AM, Osier Yang wrote:
This splits virsh.c by the command groups, except 'virsh itself' group, each group will have a separate .c, filled with the its commands, a few helpers, and command group definition moved from virsh.c. and virsh.c simply include those new .c files.
It still could be optimized, but this set could set up the skelton, and further optimization could be later patches.
Osier Yang (11): virsh: Move definition of cmds and cmd groups right at the top of main virsh: Split cmds for domain and domain monitoring from virsh.c virsh: Split cmds for storage pool and storage volume from virsh.c virsh: Split cmds to manage network from virsh.c virsh: Split cmds to manage host interface from virsh.c virsh: Split cmds to manage network filter from virsh.c virsh: Split cmds to manage secret from virsh.c virsh: Split cmds to manage domain snapshot from virsh.c virsh: Split cmds in host group from virsh.c virsh: Split cmds in node device group from virsh.c virsh: Move command group definition into its own file
Patches 2 and 3 didn't come through yet (too big for the mail list, when uncompressed), but I'm in favor of the overall idea. I'll review what I can of the incomplete series; this has the potential to introduce conflicts in other pending patches, but is worth doing. -- Eric Blake eblake@redhat.com +1-919-301-3266 Libvirt virtualization library http://libvirt.org
participants (2)
-
Eric Blake
-
Osier Yang