Commit Graph

700 Commits

Author SHA1 Message Date
Eric Blake
3211deba3e snapshot: make virDomainSnapshotObjList opaque
We were failing to react to allocation failure when initializing
a snapshot object list.  Changing things to store a pointer
instead of a complete object adds one more possible point of
allocation failure, but at the same time, will make it easier to
react to failure now, as well as making it easier for a future
patch to split all virDomainSnapshotPtr handling into a separate
file, as I continue to add even more snapshot code.

Luckily, there was only one client outside of domain_conf.c that
was actually peeking inside the object, and a new wrapper function
was easy.

* src/conf/domain_conf.h (_virDomainObj): Use a pointer.
(virDomainSnapshotObjListInit): Rename.
(virDomainSnapshotObjListFree, virDomainSnapshotForEach): New
declarations.
(_virDomainSnapshotObjList): Move definitions...
* src/conf/domain_conf.c: ...here.
(virDomainSnapshotObjListInit, virDomainSnapshotObjListDeinit):
Rename...
(virDomainSnapshotObjListNew, virDomainSnapshotObjListFree): ...to
these.
(virDomainSnapshotForEach): New function.
(virDomainObjDispose, virDomainListPopulate): Adjust callers.
* src/qemu/qemu_domain.c (qemuDomainSnapshotDiscard)
(qemuDomainSnapshotDiscardAllMetadata): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsAllowed): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotLoad)
(qemuDomainUndefineFlags, qemuDomainSnapshotCreateXML)
(qemuDomainSnapshotListNames, qemuDomainSnapshotNum)
(qemuDomainListAllSnapshots)
(qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren)
(qemuDomainSnapshotListAllChildren)
(qemuDomainSnapshotLookupByName, qemuDomainSnapshotGetParent)
(qemuDomainSnapshotGetXMLDesc, qemuDomainSnapshotIsCurrent)
(qemuDomainSnapshotHasMetadata, qemuDomainRevertToSnapshot)
(qemuDomainSnapshotDelete): Likewise.
* src/libvirt_private.syms (domain_conf.h): Export new function.
2012-08-24 09:51:08 -06:00
Tang Chen
15a71e6059 Introduce virNetlinkEventServiceStopAll() to stop all netlink services.
This patch introduce virNetlinkEventServiceStopAll() to stop
all the monitors to receive netlink messages for libvirtd.

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
2012-08-22 18:23:58 +08:00
Tang Chen
151eee5a06 Introduce virDomainEmulatorPinAdd and virDomainEmulatorPinDel functions
Introduce 2 APIs to support emulator threads pin.
    1) virDomainEmulatorPinAdd: setup emulator threads pin with a given cpumap string.
    2) virDomainEmulatorPinDel: remove all emulator threads pin.

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 16:29:57 +08:00
Hu Tao
fe1d32596c Enable cpuset cgroup and synchronous vcpupin info to cgroup.
vcpu threads pin are implemented using sched_setaffinity(), but
not controlled by cgroup. This patch does the following things:

    1) enable cpuset cgroup
    2) reflect all the vcpu threads pin info to cgroup

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 15:12:22 +08:00
Hu Tao
a5dd8b808c updates of some vcpupin related functions
1. add a new function virDomainVcpuPinDefCopy
2. make virDomainVcpuPinDefFree non-static
2012-08-22 15:11:38 +08:00
Hu Tao
910282960f Introduce the function virCgroupMoveTask
Introduce a new API to move tasks of one controller from a cgroup to another cgroup

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 14:33:28 +08:00
Wen Congyang
92741ef3ee Introduce the function virCgroupForEmulator
Introduce the function virCgroupForEmulator() to create sub directory
for simulator thread(include I/O thread, vhost-net thread)

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 14:25:06 +08:00
J.B. Joret
5d4f8d9746 Support for Disk Geometry Override
A hypervisor may allow to override the disk geometry of drives.
Qemu, as an example with cyls=,heads=,secs=[,trans=].
This patch extends the domain config to allow the specification of
disk geometry with libvirt.

Signed-off-by: J.B. Joret <jb@linux.vnet.ibm.com>
Signed-off-by: Viktor Mihajlovski <mihajlov@linux.vnet.ibm.com>
2012-08-21 15:30:07 -06:00
Jiri Denemark
15f5e16f4e daemon: Autodetect lock driver directory
When running libvirtd from a build directory, libvirtd would load lock
drivers from system directory unless explicitly overridden by setting
LIBVIRT_LOCK_MANAGER_PLUGIN_DIR environment variable. Since we already
autodetect driver directory if libvirt is build with driver modules, we
can use the same trick to automagically set lock driver directory.
2012-08-21 18:05:19 +02:00
Peter Krempa
25f2c8b4b0 libssh2_transport: Add libssh2 session support to net client code
This patch adds a glue layer to enable using libssh2 code with the
network client code.

As in the original client implementation, shell code is sent to the
server to detect correct options for netcat and connect to libvirt's
unix socket.
2012-08-21 14:47:09 +02:00
Peter Krempa
637ea54274 libssh2_transport: add ssh context support to virNetSocket
This patch enables virNetSocket to be used as an ssh client when
properly configured.

This patch adds function virNetSocketNewConnectLibSSH2() that takes all
needed parameters and creates a libssh2 session and performs steps
needed to open the connection and then create a virNetSocket that
seamlesly encapsulates the communication.
2012-08-21 14:47:09 +02:00
Marcelo Cerri
a994ef2d1a Update security layer to handle many security labels
These changes make the security drivers able to find and handle the
correct security label information when more than one label is
available. They also update the DAC driver to be used as an usual
security driver.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:14:30 +02:00
Marcelo Cerri
e9377dda36 Multiple security drivers in XML data
This patch updates the domain and capability XML parser and formatter to
support more than one "seclabel" element for each domain and device. The
RNG schema and the tests related to this are also updated by this patch.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:13:33 +02:00
Daniel P. Berrange
5435f17ed6 Add support for creating sockets & RPC servers from a pre-opened fd
In order to support systemd socket based activation, it needs to
be possible to create virNetSocketPtr and virNetServerServicePtr
instance from a pre-opened file descriptor
2012-08-20 13:34:34 +01:00
Shradha Shah
3ebf5484bc conf: add function virDevicePCIAddressEqual
This function is needed by the network driver in a later commit.
It is useful in functions like networkNotifyActualDevice and
networkReleaseActualDevice
2012-08-17 15:43:26 -04:00
Shradha Shah
f9150c8158 conf: move DevicePCIAddress functions to separate file
Move the functions the parse/format, and validate PCI addresses to
their own file so they can be conveniently used in other places
besides device_conf.c

Refactoring existing code without causing any functional changes to
prepare for new code.

This patch makes the code reusable.

Signed-off-by: Shradha Shah <sshah@solarflare.com>
2012-08-17 15:43:25 -04:00
Daniel P. Berrange
eed537c5df Move some SASL symbols into libvirt_sasl.syms
Previous commit:

  commit 9093ab7734
  Author: Daniel P. Berrange <berrange@redhat.com>
  Date:   Wed Jul 18 17:03:17 2012 +0100

    Add lots of internal symbols to libvirt_private.syms

mistakenly put some conditional SASL symbols in libvirt_private.syms
instead of libvirt_sasl.syms
2012-08-15 21:41:42 +01:00
Laine Stump
3f9274a524 conf: add <vlan> element to network and domain interface elements
The following config elements now support a <vlan> subelements:

within a domain: <interface>, and the <actual> subelement of <interface>
within a network: the toplevel, as well as any <portgroup>

Each vlan element must have one or more <tag id='n'/> subelements.  If
there is more than one tag, it is assumed that vlan trunking is being
requested. If trunking is required with only a single tag, the
attribute "trunk='yes'" should be added to the toplevel <vlan>
element.

Some examples:

  <interface type='hostdev'/>
    <vlan>
      <tag id='42'/>
    </vlan>
    <mac address='52:54:00:12:34:56'/>
    ...
  </interface>

  <network>
    <name>vlan-net</name>
    <vlan trunk='yes'>
      <tag id='30'/>
    </vlan>
    <virtualport type='openvswitch'/>
  </network>

  <interface type='network'/>
    <source network='vlan-net'/>
    ...
  </interface>

  <network>
    <name>trunk-vlan</name>
    <vlan>
      <tag id='42'/>
      <tag id='43'/>
    </vlan>
    ...
  </network>

  <network>
    <name>multi</name>
    ...
    <portgroup name='production'/>
      <vlan>
        <tag id='42'/>
      </vlan>
    </portgroup>
    <portgroup name='test'/>
      <vlan>
        <tag id='666'/>
      </vlan>
    </portgroup>
  </network>

  <interface type='network'/>
    <source network='multi' portgroup='test'/>
    ...
  </interface>

IMPORTANT NOTE: As of this patch there is no backend support for the
vlan element for *any* network device type. When support is added in
later patches, it will only be for those select network types that
support setting up a vlan on the host side, without the guest's
involvement. (For example, it will be possible to configure a vlan for
a guest connected to an openvswitch bridge, but it won't be possible
to do that for one that is connected to a standard Linux host bridge.)
2012-08-15 13:10:57 -04:00
Laine Stump
cfbdd005e9 util: add virNetDevVlanType
To allow for the possibility of vlan "trunks", which have more than
one vlan tag associated with them, we need a vlan struct. Since it
will be used by multiple files in src/util, src/conf, src/network, and
src/qemu, it must be defined in src/util. Unfortunately there isn't
currently a common file for simple netdev data definitions, so I
created a new file.
2012-08-15 13:10:57 -04:00
Daniel P. Berrange
39b5e4d4d8 Refactor RPC client private data setup
Currently there is a hook function that is invoked when a
new client connection comes in, which allows an app to
setup private data. This setup will make it difficult to
serialize client state during process re-exec(). Change to
a model where the app registers a callback when creating
the virNetServerPtr instance, which is used to allocate
the client private data immediately during virNetClientPtr
construction.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-15 10:59:10 +01:00
Daniel P. Berrange
86f5457d49 Allow sync IO and keepalives to be skipped in RPC client setup
Currently the virNetClientPtr constructor will always register
the async IO event handler and the keepalive objects. In the
case of the lock manager, there will be no event loop available
nor keepalive support required. Split this setup out of the
constructor and into separate methods.

The remote driver will enable async IO and keepalives, while
the LXC driver will only enable async IO

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-15 10:58:30 +01:00
Daniel P. Berrange
95e49be5e2 Change interaction when accepting new RPC client connections
Currently the virNetServerServicePtr is responsible for
creating the virNetServerClientPtr instance when accepting
a new connection. Change this so that the virNetServerServicePtr
merely gives virNetServerPtr a virNetSocketPtr instance. The
virNetServerPtr can then create the virNetServerClientPtr
as it desires

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-15 10:55:51 +01:00
Daniel P. Berrange
2241582c6a Add APIs for virThreadPoolPtr to query some config params
It is desirable to be able to query the config params of
the thread pool, in order to save the server state. Add
virThreadPoolGetMinWorkers, virThreadPoolGetMaxWorkers
and virThreadPoolGetPriorityWorkers APIs.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-15 10:55:51 +01:00
Laine Stump
1c02ed1421 util: utility functions for virNetDevVPortProfile
This patch adds three utility functions that operate on
virNetDevVPortProfile objects.

* virNetDevVPortProfileCheckComplete() - verifies that all attributes
    required for the type of the given virtport are specified.

* virNetDevVPortProfileCheckNoExtras() - verifies that there are no
    attributes specified which are inappropriate for the type of the
    given virtport.

* virNetDevVPortProfileMerge3() - merges 3 virtports into a single,
    newly allocated virtport. If any attributes are specified in
    more than one of the three sources, and do not exactly match,
    an error is logged and the function fails.

These new functions depend on new fields in the virNetDevVPortProfile
object that keep track of whether or not each attribute was
specified. Since the higher level parse function doesn't yet set those
fields, these functions are not actually usable yet (but that's okay,
because they also aren't yet used - all of that functionality comes in
a later patch.)

Note that these three functions return 0 on success and -1 on
failure. This may seem odd for the first two Check functions, since
they could also easily return true/false, but since they actually log
an error when the requested condition isn't met (and should result in
a failure of the calling function), I thought 0/-1 was more
appropriate.
2012-08-14 15:47:20 -04:00
Daniel P. Berrange
aa5bd8b9b9 Add virRandom() API to generate numbers with non-power-of-2 limit
The current virRandomBits() API is only usable if the caller wants
a random number in the range [0, n-1) where n is a power of two.
This adds a virRandom() API which generates a double in the
range [0.0,1.0) with 48 bits of entropy. It then also adds a
virRandomInt(uint32_t max) API which generates an unsigned
in the range [0,@max)

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-14 15:31:25 +01:00
Martin Kletzander
43bfa23e6f json: fix interface locale dependency
libvirt creates invalid commands if wrong locale is selected. For
example with locale that uses comma as a decimal point, JSON commands
created with decimal numbers are invalid because comma separates the
entries in JSON. Fortunately even when decimal point is affected,
thousands grouping is not, because for grouping to be enabled with
*printf, there has to be an apostrophe flag specified (and supported).

This patch adds specific internal function for converting doubles to
strings with C locale.
2012-08-14 07:30:14 +02:00
Laine Stump
b8a56f12f5 nwfilter: fix crash during filter define when lxc driver failed startup
The meat of this patch is just moving the calls to
virNWFilterRegisterCallbackDriver from each hypervisor's "register"
function into its "initialize" function. The rest is just code
movement to allow that, and a new virNWFilterUnRegisterCallbackDriver
function to undo what the register function does.

The long explanation:

There is an array in nwfilter called callbackDrvArray that has
pointers to a table of functions for each hypervisor driver that are
called by nwfilter. One of those function pointers is to a function
that will lock the hypervisor driver. Entries are added to the table
by calling each driver's "register" function, which happens quite
early in libvirtd's startup.

Sometime later, each driver's "initialize" function is called. This
function allocates a driver object and stores a pointer to it in a
static variable that was previously initialized to NULL. (and here's
the important part...) If the "initialize" function fails, the driver
object is freed, and that pointer set back to NULL (but the entry in
nwfilter's callbackDrvArray is still there).

When the "lock the driver" function mentioned above is called, it
assumes that the driver was successfully loaded, so it blindly tries
to call virMutexLock on "driver->lock".

BUT, if the initialize never happened, or if it failed, "driver" is
NULL. And it just happens that "lock" is always the first field in
driver so it is also NULL.

Boom.

To fix this, the call to virNWFilterRegisterCallbackDriver for each
driver shouldn't be called until the end of its (*already guaranteed
successful*) "initialize" function, not during its "register" function
(which is currently the case). This implies that there should also be
a virNWFilterUnregisterCallbackDriver() function that is called in a
driver's "shutdown" function (although in practice, that function is
currently never called).
2012-08-09 23:28:00 -04:00
Daniel P. Berrange
05e4e7b46e Turn virNetClient* into virObject instances
Make all the virNetClient* objects use virObject APIs for
reference counting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:55 +01:00
Daniel P. Berrange
958499b0c1 Turn virNetServer* into virObject instances
Make all the virNetServer* objects use the virObject APIs
for reference counting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:55 +01:00
Daniel P. Berrange
410a5dac42 Turn virSocket into a virObject
Make virSocket use the virObject APIs for reference counting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Daniel P. Berrange
0b4d3fe556 Turn virNetSASLContext and virNetSASLSession into virObject instances
Make virNetSASLContext and virNetSASLSession use virObject APIs
for reference counting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Daniel P. Berrange
e10e1969d5 Turn virNetTLSContext and virNetTLSSession into virObject instances
Make virNetTLSContext and virNetTLSSession use the virObject
APIs for reference counting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Daniel P. Berrange
31cb030ab6 Turn virDomainObjPtr into a virObjectPtr
Switch virDomainObjPtr to use the virObject APIs for reference
counting. The main change is that virObjectUnref does not return
the reference count, merely a bool indicating whether the object
still has any refs left. Checking the return value is also not
mandatory.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Daniel P. Berrange
46ec5f85c8 Convert public datatypes to inherit from virObject
This converts the following public API datatypes to use the
virObject infrastructure:

  virConnectPtr
  virDomainPtr
  virDomainSnapshotPtr
  virInterfacePtr
  virNetworkPtr
  virNodeDevicePtr
  virNWFilterPtr
  virSecretPtr
  virStreamPtr
  virStorageVolPtr
  virStoragePoolPtr

The code is significantly simplified, since the mutex in the
virConnectPtr object now only needs to be held when accessing
the per-connection virError object instance. All other operations
are completely lock free.

* src/datatypes.c, src/datatypes.h, src/libvirt.c: Convert
  public datatypes to use virObject
* src/conf/domain_event.c, src/phyp/phyp_driver.c,
  src/qemu/qemu_command.c, src/qemu/qemu_migration.c,
  src/qemu/qemu_process.c, src/storage/storage_driver.c,
  src/vbox/vbox_tmpl.c, src/xen/xend_internal.c,
  tests/qemuxml2argvtest.c, tests/qemuxmlnstest.c,
  tests/sexpr2xmltest.c, tests/xmconfigtest.c: Convert
  to use virObjectUnref/virObjectRef

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Daniel P. Berrange
784a99f794 Add a generic reference counted virObject type
This introduces a fairly basic reference counted virObject type
and an associated virClass type, that use atomic operations for
ref counting.

In a global initializer (recommended to be invoked using the
virOnceInit API), a virClass type must be allocated for each
object type. This requires a class name, a "dispose" callback
which will be invoked to free memory associated with the object's
fields, and the size in bytes of the object struct.

eg,

   virClassPtr  connclass = virClassNew("virConnect",
                                        sizeof(virConnect),
                                        virConnectDispose);

The struct for the object, must include 'virObject' as its
first member

eg

  struct _virConnect {
    virObject object;

    virURIPtr uri;
  };

The 'dispose' callback is only responsible for freeing
fields in the object, not the object itself. eg a suitable
impl for the above struct would be

  void virConnectDispose(void *obj) {
     virConnectPtr conn = obj;
     virURIFree(conn->uri);
  }

There is no need to reset fields to 'NULL' or '0' in the
dispose callback, since the entire object will be memset
to 0, and the klass pointer & magic integer fields will
be poisoned with 0xDEADBEEF before being free()d

When creating an instance of an object, one needs simply
pass the virClassPtr eg

   virConnectPtr conn = virObjectNew(connclass);
   if (!conn)
      return NULL;
   conn->uri = virURIParse("foo:///bar")

Object references can be manipulated with

   virObjectRef(conn)
   virObjectUnref(conn)

The latter returns a true value, if the object has been
freed (ie its ref count hit zero)

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Eric Blake
87de27b7f9 virrandom: make virRandomInitialize an automatic one-shot
All callers used the same initialization seed (well, the new
viratomictest forgot to look at getpid()); so we might as well
make this value automatic.  And while it may feel like we are
giving up functionality, I documented how to get it back in the
unlikely case that you actually need to debug with a fixed
pseudo-random sequence.  I left that crippled by default, so
that a stray environment variable doesn't cause a lack of
randomness to become a security issue.

* src/util/virrandom.c (virRandomInitialize): Rename...
(virRandomOnceInit): ...and make static, with one-shot call.
Document how to do fixed-seed debugging.
* src/util/virrandom.h (virRandomInitialize): Drop prototype.
* src/libvirt_private.syms (virrandom.h): Don't export it.
* src/libvirt.c (virInitialize): Adjust caller.
* src/lxc/lxc_controller.c (main): Likewise.
* src/security/virt-aa-helper.c (main): Likewise.
* src/util/iohelper.c (main): Likewise.
* tests/seclabeltest.c (main): Likewise.
* tests/testutils.c (virtTestMain): Likewise.
* tests/viratomictest.c (mymain): Likewise.
2012-08-06 08:15:13 -06:00
Daniel P. Berrange
554612c104 Export virUUIDIsValid to libvirt internal code 2012-08-03 15:35:02 +01:00
Osier Yang
ed1e711b99 qemu: Allow to attach/detach controller device persistently
* src/conf/domain_conf.c:
  - Add virDomainControllerFind to find controller device by type
    and index.
  - Add virDomainControllerRemove to remove the controller device
    from maintained controler list.

* src/conf/domain_conf.h:
  - Declare the two new helpers.

* src/libvirt_private.syms:
  - Expose private symbols for the two new helpers.

* src/qemu/qemu_driver.c:
  - Support attach/detach controller device persistently

* src/qemu/qemu_hotplug.c:
  - Use the two helpers to simplify the codes.
2012-08-03 12:19:16 +08:00
Jiri Denemark
2f2ca02195 build: Link security manager into libvirt.so
Security manager is not a dynamically loadable driver, it's a common
infrastructure similar to util, conf, cpu, etc. used by individual
drivers. Such code is allowed to be linked into libvirt.so.

This reverts commit ec5b7bd2ec and most of
aae5cfb699.

This patch is supposed to fix virdrivermoduletest failures for qemu and
lxc drivers as well as libvirtd's ability to load qemu and lxc drivers.
2012-08-02 16:17:00 +02:00
Daniel P. Berrange
b49890de82 Remove manual one-shot global initializers
Remove the use of a manually run virLogStartup and
virNodeSuspendInitialize methods. Instead make sure they
are automatically run using VIR_ONCE_GLOBAL_INIT

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-02 11:50:46 +01:00
Peter Krempa
317badb213 domain_conf: Add helpers to verify if device configuration is valid
This patch adds helpers that validate domain's device configuration.
This will be needed later on to verify devices being hot-plugged to
guests. If the guest has no USB bus, then it's not valid to plug a USB
device to that guest.
2012-08-02 11:54:50 +02:00
Daniel P. Berrange
aae5cfb699 Don't link nwfilter or secrets driver to libvirt.so
The nwfilter and secrets drivers are both stateful and are already
linked directly to libvirtd. Linking them to libvirt.so is thus
wrong, likewise exporting their symbols in libvirt.so is wrong
2012-07-31 17:49:41 +01:00
Daniel P. Berrange
0f7f4b160b Add callback to virNetClient to be invoked on connection close
Allow detection of socket close in virNetClient via a callback
function, triggered on any condition that causes the socket to
be closed.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-30 10:08:41 +01:00
Daniel P. Berrange
25b0988974 Remove accidentally commited virNetClientSetEOFNotify symbol
The virNetClientSetEOFNotify symbol was accidentally added to
the libvirt_private.syms file due to an out-of-order cherry-pick
2012-07-27 10:53:50 +01:00
Daniel P. Berrange
9093ab7734 Add lots of internal symbols to libvirt_private.syms
Make sure that libvirt_private.syms has all the internal symbols
from APIs in src/rpc/*.h and src/util/cgroup.h, since the LXC
controller/driver will shortly need them

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-19 10:18:26 +01:00
Stefan Berger
387117ad92 Convert 'raw MAC address' usages to use virMacAddr
Introduce new members in the virMacAddr 'class'
- virMacAddrSet: set virMacAddr from a virMacAddr
- virMacAddrSetRaw: setting virMacAddr from raw 6 byte MAC address buffer
- virMacAddrGetRaw: writing virMacAddr into raw 6 byte MAC address buffer
- virMacAddrCmp: comparing two virMacAddr
- virMacAddrCmpRaw: comparing a virMacAddr with a raw 6 byte MAC address buffer

then replace raw MAC addresses by replacing

- 'unsigned char *' with virMacAddrPtr
- 'unsigned char ... [VIR_MAC_BUFLEN]' with virMacAddr

and introduce usage of above functions where necessary.
2012-07-17 08:07:59 -04:00
Daniel P. Berrange
7ed6d7dda7 Define public API for receiving guest memory balloon events
When the guest changes its memory balloon applications may want
to know what the new value is, without having to periodically
poll on XML / domain info. Introduce a "balloon change" event
to let apps see this

* include/libvirt/libvirt.h.in: Define the
  virConnectDomainEventBalloonChangeCallback callback
  and VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE constant
* python/libvirt-override-virConnect.py,
  python/libvirt-override.c: Wire up helpers for new event
* daemon/remote.c: Helper for serializing balloon event
* examples/domain-events/events-c/event-test.c,
  examples/domain-events/events-python/event-test.py: Add
  example of balloon event usage
* src/conf/domain_event.c, src/conf/domain_event.h: Handling
  of balloon events
* src/remote/remote_driver.c: Add handler of balloon events
* src/remote/remote_protocol.x: Define wire protocol for
  balloon events
* src/remote_protocol-structs: Likewise.
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-14 16:02:26 +08:00
Osier Yang
ea9509b9e8 virsh: Ensure the parents of the readline history path exists
Instead of changing the existed virFileMakePath to accept mode
argument and modifying a pile of its uses, this patch introduces
virFileMakePathWithMode, and use it instead of mkdir() to create
the readline history dir.
2012-07-10 21:37:13 +08:00
Daniel P. Berrange
9612e4b2e7 Move loop device setup code into virfile.{c,h}
While it is not currently used elsewhere in libvirt, the code
for finding a free loop device & associating a file with it
is not LXC specific. Move it into the viffile.{c,h} file where
potentially shared code is more commonly kept.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-05 10:46:10 +01:00
Eric Blake
8548a9c501 list: new helper function to collect snapshots
Wraps the conversion from 'char *name' to virDomainSnapshotPtr in
a reusable manner.

* src/conf/virdomainlist.h (virDomainListSnapshots): New declaration.
* src/conf/virdomainlist.c (virDomainListSnapshots): Implement it.
* src/libvirt_private.syms (virdomainlist.h): Export it.
2012-06-19 14:51:54 -06:00
Eric Blake
7e111c6fe6 snapshot: merge domain and snapshot computation
Now that domain listing is a thin wrapper around child listing,
it's easier to have a common entry point.  This restores the
hashForEach optimization lost in the previous patch when there
are no snapshots being filtered out of the entire list.

* src/conf/domain_conf.h (virDomainSnapshotObjListGetNames)
(virDomainSnapshotObjListNum): Add parameter.
(virDomainSnapshotObjListGetNamesFrom)
(virDomainSnapshotObjListNumFrom): Delete.
* src/libvirt_private.syms (domain_conf.h): Drop deleted functions.
* src/conf/domain_conf.c (virDomainSnapshotObjListGetNames):
Merge, and (re)add an optimization.
* src/qemu/qemu_driver.c (qemuDomainUndefineFlags)
(qemuDomainSnapshotListNames, qemuDomainSnapshotNum)
(qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren): Update callers.
* src/qemu/qemu_migration.c (qemuMigrationIsAllowed): Likewise.
* src/conf/virdomainlist.c (virDomainListPopulate): Likewise.
2012-06-18 15:11:28 -06:00
Peter Krempa
2c68080444 conf: Add helper for listing domains on drivers supporting virDomainObj
This patch adds common code to list domains in fashion used by
virListAllDomains with all currently supported flags. The header file
also contains macros that group filters together that are used to
shorten filter conditions.
2012-06-18 21:24:13 +02:00
Guido Günther
0dde544c95 Introduce virDomainFSIndexByName
for containers matching virDomainDiskIndexByName.
2012-06-12 17:59:28 +02:00
Eric Blake
9202f2c220 buf: support peeking at string contents
Right now, the only way to get at the contents of a virBuffer is
to destroy it.  But there are cases in my upcoming patches where
peeking at the contents makes life easier.  I suppose this does
open up the potential for bad code to dereference a stale pointer,
by disregarding the docs that the return value is invalid on the
next virBuf operation, but such is life.

* src/util/buf.h (virBufferCurrentContent): New declaration.
* src/util/buf.c (virBufferCurrentContent): Implement it.
* src/libvirt_private.syms (buf.h): Export it.
* tests/virbuftest.c (testBufAutoIndent): Test it.
2012-06-11 09:21:27 -06:00
Stefan Berger
797b47580a nwfilter: move code for IP address map into separate file
The goal of this patch is to prepare for support for multiple IP
addresses per interface in the DHCP snooping code.

Move the code for the IP address map that maps interface names to
IP addresses into their own file. Rename the functions on the way
but otherwise leave the code as-is. Initialize this new layer
separately before dependent layers (iplearning, dhcpsnooping)
and shut it down after them.
2012-06-01 19:32:06 -04:00
Daniel P. Berrange
076f200689 Add impl of APIs to get user directories on Win32
Add an impl of +virGetUserRuntimeDirectory, virGetUserCacheDirectory
virGetUserConfigDirectory and virGetUserDirectory for Win32 platform.
Also create stubs for non-Win32 platforms which lack getpwuid_r()

In adding these two helpers were added virFileIsAbsPath and
virFileSkipRoot, along with some macros VIR_FILE_DIR_SEPARATOR,
VIR_FILE_DIR_SEPARATOR_S, VIR_FILE_IS_DIR_SEPARATOR,
VIR_FILE_PATH_SEPARATOR, VIR_FILE_PATH_SEPARATOR_S

All this code was adapted from GLib2 under terms of LGPLv2+ license.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-05-28 10:55:09 +01:00
Daniel P. Berrange
6cd4b1fe16 Remove libvirt_test.la library
The libvirt_test.la library was introduced to allow test suites
to reference internal-only symbols. These days, nearly every
symbol we care about is in src/libvirt_private.syms, so there
is no need for libvirt_test.la to continue to exist

* src/Makefile.am: Delete libvirt_test.la & add new .syms files
* src/libvirt_private.syms: Export symbols needed by test suite
* tests/Makefile.am: Link to libvirt_test.la. Ensure LXC tests link
  to network_driver.la
* src/libvirt_esx.syms, src/libvirt_openvz.syms: Add exports needed
  by test suite
2012-05-24 13:18:00 +01:00
Laine Stump
3404729e58 util: export virBufferTrim
This was forgotten in commit cdb87b1c4b.
2012-05-22 11:36:04 -04:00
Daniel P. Berrange
2cb0899eec Fix potential events deadlock when unref'ing virConnectPtr
When the last reference to a virConnectPtr is released by
libvirtd, it was possible for a deadlock to occur in the
virDomainEventState functions. The virDomainEventStatePtr
holds a reference on virConnectPtr for each registered
callback. When removing a callback, the virUnrefConnect
function is run. If this causes the last reference on the
virConnectPtr to be released, then virReleaseConnect can
be run, which in turns calls qemudClose. This function has
a call to virDomainEventStateDeregisterConn which is intended
to remove all callbacks associated with the virConnectPtr
instance. This will try to grab a lock on virDomainEventState
but this lock is already held. Deadlock ensues

Thread 1 (Thread 0x7fcbb526a840 (LWP 23185)):

Since each callback associated with a virConnectPtr holds a
reference on virConnectPtr, it is impossible for the qemudClose
method to be invoked while any callbacks are still registered.
Thus the call to virDomainEventStateDeregisterConn must in fact
be a no-op. Thus it is possible to just remove all trace of
virDomainEventStateDeregisterConn and avoid the deadlock.

* src/conf/domain_event.c, src/conf/domain_event.h,
  src/libvirt_private.syms: Delete virDomainEventStateDeregisterConn
* src/libxl/libxl_driver.c, src/lxc/lxc_driver.c,
  src/qemu/qemu_driver.c, src/uml/uml_driver.c: Remove
  calls to virDomainEventStateDeregisterConn
2012-05-21 18:50:47 +01:00
Daniel Walsh
abf2ebbd27 Add security driver APIs for getting mount options
Some security drivers require special options to be passed to
the mount system call. Add a security driver API for handling
this data.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-05-16 10:05:47 +01:00
William Jon McCann
32a9aac2e0 Use XDG Base Directories instead of storing in home directory
As defined in:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

This offers a number of advantages:
 * Allows sharing a home directory between different machines, or
sessions (eg. using NFS)
 * Cleanly separates cache, runtime (eg. sockets), or app data from
user settings
 * Supports performing smart or selective migration of settings
between different OS versions
 * Supports reseting settings without breaking things
 * Makes it possible to clear cache data to make room when the disk
is filling up
 * Allows us to write a robust and efficient backup solution
 * Allows an admin flexibility to change where data and settings are stored
 * Dramatically reduces the complexity and incoherence of the
system for administrators
2012-05-14 15:15:58 +01:00
Osier Yang
97010eb1f1 numad: Set memory policy from numad advisory nodeset
Though numad will manage the memory allocation of task dynamically,
it wants management application (libvirt) to pre-set the memory
policy according to the advisory nodeset returned from querying numad,
(just like pre-bind CPU nodeset for domain process), and thus the
performance could benefit much more from it.

This patch introduces new XML tag 'placement', value 'auto' indicates
whether to set the memory policy with the advisory nodeset from numad,
and its value defaults to the value of <vcpu> placement, or 'static'
if 'nodeset' is specified. Example of the new XML tag's usage:

  <numatune>
    <memory placement='auto' mode='interleave'/>
  </numatune>

Just like what current "numatune" does, the 'auto' numa memory policy
setting uses libnuma's API too.

If <vcpu> "placement" is "auto", and <numatune> is not specified
explicitly, a default <numatume> will be added with "placement"
set as "auto", and "mode" set as "strict".

The following XML can now fully drive numad:

1) <vcpu> placement is 'auto', no <numatune> is specified.

   <vcpu placement='auto'>10</vcpu>

2) <vcpu> placement is 'auto', no 'placement' is specified for
   <numatune>.

   <vcpu placement='auto'>10</vcpu>
   <numatune>
     <memory mode='interleave'/>
   </numatune>

And it's also able to control the CPU placement and memory policy
independently. e.g.

1) <vcpu> placement is 'auto', and <numatune> placement is 'static'

   <vcpu placement='auto'>10</vcpu>
   <numatune>
     <memory mode='strict' nodeset='0-10,^7'/>
   </numatune>

2) <vcpu> placement is 'static', and <numatune> placement is 'auto'

   <vcpu placement='static' cpuset='0-24,^12'>10</vcpu>
   <numatune>
     <memory mode='interleave' placement='auto'/>
   </numatume>

A follow up patch will change the XML formatting codes to always output
'placement' for <vcpu>, even it's 'static'.
2012-05-08 16:57:32 -06:00
Laine Stump
c99e93758d util: function to get local nl_pid used by netlink event socket
This value will be needed to set the src_pid when sending netlink
messages to lldpad. It is part of the solution to:

  https://bugzilla.redhat.com/show_bug.cgi?id=816465

Note that libnl's port generation algorithm guarantees that the
nl_socket_get_local_port() will always be > 0 (since it is "getpid() +
(n << 22>" where n is always < 1024), so it is okay to cast the
uint32_t to int (thus allowing us to use -1 as an error sentinel).
2012-05-07 14:25:55 -04:00
Laine Stump
642973135c util: fix libvirtd startup failure due to netlink error
This is part of the solution to the problem detailed in:

  https://bugzilla.redhat.com/show_bug.cgi?id=816465

and further detailed in

  https://www.redhat.com/archives/libvir-list/2012-May/msg00202.htm

A short explanation is included in the comments of the patch itself.

Note that this patch by itself breaks communication between lldpad and
libvirtd, so the other 3 patches in the series must be applied at the
same time as this patch.
2012-05-07 14:25:43 -04:00
Guannan Ren
9914477efc usb: create functions to search usb device accurately
usbFindDevice():get usb device according to
                idVendor, idProduct, bus, device
                it is the exact match of the four parameters

usbFindDeviceByBus():get usb device according to bus, device
                  it returns only one usb device same as usbFindDevice

usbFindDeviceByVendor():get usb device according to idVendor,idProduct
                     it probably returns multiple usb devices.

usbDeviceSearch(): a helper function to do the actual search
2012-05-07 23:36:22 +08:00
Dmitry Guryanov
287737f413 util: add functions for interating over json object
Add function virJSONValueObjectKeysNumber, virJSONValueObjectGetKey
and virJSONValueObjectGetValue, which allow you to iterate over all
fields of json object: you can get number of fields and then get
name and value, stored in field with that name by index.

Signed-off-by: Dmitry Guryanov <dguryanov@parallels.com>
2012-05-03 09:07:25 -06:00
Jiri Denemark
9d2ac5453e qemu: Make sure qemu can access its directory in hugetlbfs
When libvirtd is started, we create "libvirt/qemu" directories under
hugetlbfs mount point. Only the "qemu" subdirectory is chowned to qemu
user and "libvirt" remains owned by root. If umask was too restrictive
when libvirtd started, qemu user may lose access to "qemu"
subdirectory. Let's explicitly grant search permissions to "libvirt"
directory for all users.
2012-04-30 08:17:40 +02:00
Stefan Berger
1614970ec5 Add new functions to virSocketAddr
Add 2 new functions to the virSocketAddr 'class':

- virSocketAddrEqual: tests whether two IP addresses and their ports are equal
- virSocketaddSetIPv4Addr: set a virSocketAddr given a 32 bit int
2012-04-25 09:53:29 -04:00
Daniel P. Berrange
2223ea984c The policy kit and HAL node device drivers both require a
DBus connection. The HAL device code further requires that
the DBus connection is integrated with the event loop and
provides such glue logic itself.

The forthcoming FirewallD integration also requires a
dbus connection with event loop integration. Thus we need
to pull the current event loop glue out of the HAL driver.

Thus we create src/util/virdbus.{c,h} files. This contains
just one method virDBusGetSystemBus() which obtains a handle
to the single shared system bus instance, with event glue
automagically setup.
2012-04-19 17:03:10 +01:00
Stefan Berger
6241eed3db Implement virHashRemoveAll function
Implement function to remove all entries of a hash table.
2012-04-19 10:21:43 -04:00
D. Herrendoerfer
997366ca7d qemu,util: fix netlink callback registration for migration
This patch adds a netlink callback when migrating a VEPA enabled
virtual machine.  It fixes a Bug where a VM would not request a port
association when it was cleared by lldpad.

This patch requires the latest git version of lldpad to work.

Signed-off-by: D. Herrendoerfer <d.herrendoerfer@herrendoerfer.name>
2012-04-12 14:32:10 -04:00
Philipp Hahn
b8bf79aad7 Support clock=variable relative to localtime
Since Xen 3.1 the clock=variable semantic is supported. In addition to
qemu/kvm Xen also knows about a variant where the offset is relative to
'localtime' instead of 'utc'.

Extends the libvirt structure with a flag 'basis' to specify, if the
offset is relative to 'localtime' or 'utc'.

Extends the libvirt structure with a flag 'reset' to force the reset
behaviour of 'localtime' and 'utc'; this is needed for backward
compatibility with previous versions of libvirt, since they report
incorrect XML.

Adapt the only user 'qemu' to the new name.
Extend the RelaxNG schema accordingly.
Document the new 'basis' attribute in the HTML documentation.
Adapt test for the new attribute.

Signed-off-by: Philipp Hahn <hahn@univention.de>
2012-04-02 09:08:31 -06:00
Zhou Peng
a1e50e820b private.syms: Add virNetDevMacVLanRestartWithVPortProfile
virNetDevMacVLanRestartWithVPortProfile is omitted in src/libvirt_private.syms,
which causes link err.
2012-03-29 17:03:37 +02:00
Osier Yang
487c063381 Add support for the suspend event
This patch introduces a new event type for the QMP event
SUSPEND:

    VIR_DOMAIN_EVENT_ID_PMSUSPEND

The event doesn't take any data, but considering there might
be reason for wakeup in future, the callback definition is:

typedef void
(*virConnectDomainEventSuspendCallback)(virConnectPtr conn,
                                        virDomainPtr dom,
                                        int reason,
                                        void *opaque);

"reason" is unused currently, always passes "0".
2012-03-23 23:12:18 +08:00
Osier Yang
57ddcc235a Add support for the wakeup event
This patch introduces a new event type for the QMP event
WAKEUP:

    VIR_DOMAIN_EVENT_ID_PMWAKEUP

The event doesn't take any data, but considering there might
be reason for wakeup in future, the callback definition is:

typedef void
(*virConnectDomainEventWakeupCallback)(virConnectPtr conn,
                                       virDomainPtr dom,
                                       int reason,
                                       void *opaque);

"reason" is unused currently, always passes "0".
2012-03-23 23:12:14 +08:00
Osier Yang
a26a1969c3 Add support for event tray moved of removable disks
This patch introduces a new event type for the QMP event
DEVICE_TRAY_MOVED, which occurs when the tray of a removable
disk is moved (i.e opened or closed):

    VIR_DOMAIN_EVENT_ID_TRAY_CHANGE

The event's data includes the device alias and the reason
for tray status' changing, which indicates why the tray
status was changed. Thus the callback definition for the event
is:

enum {
    VIR_DOMAIN_EVENT_TRAY_CHANGE_OPEN = 0,
    VIR_DOMAIN_EVENT_TRAY_CHANGE_CLOSE,

\#ifdef VIR_ENUM_SENTINELS
    VIR_DOMAIN_EVENT_TRAY_CHANGE_LAST
\#endif
} virDomainEventTrayChangeReason;

typedef void
(*virConnectDomainEventTrayChangeCallback)(virConnectPtr conn,
                                           virDomainPtr dom,
                                           const char *devAlias,
                                           int reason,
                                           void *opaque);
2012-03-23 23:10:26 +08:00
Daniel P. Berrange
a4fb88b5c9 Add helper API for finding auth file path
* src/util/virauth.c, src/util/virauth.h: Add virAuthGetConfigFilePath
* include/libvirt/virterror.h, src/util/virterror.c: Add
  VIR_FROM_AUTH error domain

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 13:24:07 +00:00
Daniel P. Berrange
4262e34eb5 Rename virRequest{Username,Password} to virAuthGet{Username,Password}
Ensure that the functions in virauth.h have names matching the file
prefix, by renaming  virRequest{Username,Password} to
virAuthGet{Username,Password}

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 13:24:06 +00:00
Daniel P. Berrange
f6632f6b7f Add a virKeyfilePtr object for parsing '.ini' files
The '.ini' file format is a useful alternative to the existing
config file style, when you need to have config files which
are hashes of hashes. The 'virKeyFilePtr' object provides a
way to parse these file types.

* src/Makefile.am, src/util/virkeyfile.c,
  src/util/virkeyfile.h: Add .ini file parser
* tests/Makefile.am, tests/virkeyfiletest.c: Test
  basic parsing capabilities

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 13:24:06 +00:00
Daniel P. Berrange
bc1ff1600e Convert drivers over to use virURIPtr for query params
Convert drivers currently using the qparams APIs, to instead
use the virURIPtr query parameters directly.

* src/esx/esx_util.c, src/hyperv/hyperv_util.c,
  src/remote/remote_driver.c, src/xenapi/xenapi_utils.c: Remove
  use of qparams
* src/util/qparams.h, src/util/qparams.c: Delete
* src/Makefile.am, src/libvirt_private.syms: Remove qparams

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 13:24:06 +00:00
Daniel P. Berrange
4ae4ae4ba4 Store parsed query parameters directly in the virURIPtr struct
Avoid the need for each driver to parse query parameters itself
by storing them directly in the virURIPtr struct. The parsing
code is a copy of that from src/util/qparams.c  The latter will
be removed in a later patch

* src/util/viruri.h: Add query params to virURIPtr
* src/util/viruri.c: Parse query parameters when creating virURIPtr
* tests/viruritest.c: Expand test to cover params

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 13:23:12 +00:00
Daniel P. Berrange
c33dae3175 Use virURIFree instead of xmlFreeURI
Since we defined a custom virURIPtr type, we should use a
virURIFree method instead of assuming it will always be
a typedef for xmlURIPtr

* src/util/viruri.c, src/util/viruri.h, src/libvirt_private.syms:
  Add a virURIFree method
* src/datatypes.c, src/esx/esx_driver.c, src/libvirt.c,
  src/qemu/qemu_migration.c, src/vmx/vmx.c, src/xen/xend_internal.c,
  tests/viruritest.c: s/xmlFreeURI/virURIFree/

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 12:59:20 +00:00
Laine Stump
0007237301 conf: forbid use of multicast mac addresses
A few times libvirt users manually setting mac addresses have
complained of a networking failure that ends up being due to a multicast
mac address being used for a guest interface. This patch prevents that
by logging an error and failing if a multicast mac address is
encountered in each of the three following cases:

1) domain xml <interface> mac address.
2) network xml bridge mac address.
3) network xml dhcp/host mac address.

There are several other places where a mac address can be input that
aren't controlled in this manner because failure to do so has no
consequences (e.g., if the address will be used to search through
existing interfaces for a match).

The RNG has been updated to add multiMacAddr and uniMacAddr along with
the existing macAddr, and macAddr was switched to uniMacAddr where
appropriate.
2012-03-19 20:33:30 -04:00
Osier Yang
d86120fc52 numad: Fix typo and warning
src/libvirt_private.syms:
  s/virDomainCpuPlacement/virDomainCpuPlacementMode/
src/qemu/qemu_process.c
  def->mem.cur_balloon expects "llu"
--
pushed under build-breaker rule
2012-03-15 19:43:42 +08:00
Osier Yang
0f8e7ae33a qemu: Support numad
numad is an user-level daemon that monitors NUMA topology and
processes resource consumption to facilitate good NUMA resource
alignment of applications/virtual machines to improve performance
and minimize cost of remote memory latencies. It provides a
pre-placement advisory interface, so significant processes can
be pre-bound to nodes with sufficient available resources.

More details: http://fedoraproject.org/wiki/Features/numad

"numad -w ncpus:memory_amount" is the advisory interface numad
provides currently.

This patch add the support by introducing a new XML attribute
for <vcpu>. e.g.

  <vcpu placement="auto">4</vcpu>
  <vcpu placement="static" cpuset="1-10^6">4</vcpu>

The returned advisory nodeset from numad will be printed
in domain's dumped XML. e.g.
  <vcpu placement="auto" cpuset="1-10^6">4</vcpu>

If placement is "auto", the number of vcpus and the current
memory amount specified in domain XML will be used for numad
command line (numad uses MB for memory amount):
  numad -w $num_of_vcpus:$current_memory_amount / 1024

The advisory nodeset returned from numad will be used to set
domain process CPU affinity then. (e.g. qemuProcessInitCpuAffinity).

If the user specifies both CPU affinity policy (e.g.
(<vcpu cpuset="1-10,^7,^8">4</vcpu>) and placement == "auto"
the specified CPU affinity will be overridden.

Only QEMU/KVM drivers support it now.

See docs update in patch for more details.
2012-03-15 12:24:56 +08:00
Eric Blake
0d0b409863 cpustats: collect VM user and sys times
As documented in linux.git/Documentation/cgroups/cpuacct.txt,
cpuacct.stat returns user and system time in ticks (the same
unit used in times(2)).  It would be a bit nicer if it were like
getrusage(2) and reported timeval contents, or like cpuacct.usage
and in nanoseconds, but we can't be picky.

* src/util/cgroup.h (virCgroupGetCpuacctStat): New function.
* src/util/cgroup.c (virCgroupGetCpuacctStat): Implement it.
(virCgroupGetValueStr): Allow for multi-line files.
* src/libvirt_private.syms (cgroup.h): Export it.
2012-03-12 08:46:56 -06:00
Peng Zhou
896e6ac4f8 qemu: spice agent-mouse support
spice agent-mouse support

Usage:
  <graphics type='spice'>
    <mouse mode='client'|'server'/>
  <graphics/>

Signed-off-by: Osier Yang <jyang@redhat.com>
2012-03-09 15:26:24 +08:00
Laine Stump
8845d29375 util: make virDomainLeaseDefFree global
It will be used in a different file in an upcoming patch.
2012-03-08 16:58:16 -05:00
Michal Privoznik
1e0534a770 qemu: Don't parse device twice in attach/detach
Some members are generated during XML parse (e.g. MAC address of
an interface); However, with current implementation, if we
are plugging a device both to persistent and live config,
we parse given XML twice: first time for live, second for config.
This is wrong then as the second time we are not guaranteed
to generate same values as we did for the first time.
To prevent that we need to create a copy of DeviceDefPtr;
This is done through format/parse process instead of writing
functions for deep copy as it is easier to maintain:
adding new field to any virDomain*DefPtr doesn't require change
of copying function.
2012-03-08 10:20:21 +01:00
Eric Blake
0d90823e87 util: new function for scaling numbers
Scaling an integer based on a suffix is something we plan on reusing
in several contexts: XML parsing, virsh CLI parsing, and possibly
elsewhere.  Make it easy to reuse, as well as adding in support for
powers of 1000.

* src/util/util.h (virScaleInteger): New function.
* src/util/util.c (virScaleInteger): Implement it.
* src/libvirt_private.syms (util.h): Export it.
2012-03-07 18:24:43 -07:00
KAMEZAWA Hiroyuki
44b0a53a7c qemu driver for virDomainGetCPUstats using cpuacct cgroup.
* For now, only "cpu_time" is supported.
* cpuacct cgroup is used for providing percpu cputime information.

* src/qemu/qemu.conf     - take care of cpuacct cgroup.
* src/qemu/qemu_conf.c   - take care of cpuacct cgroup.
* src/qemu/qemu_driver.c - added an interface
* src/util/cgroup.c/h    - added interface for getting percpu cputime

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2012-03-06 21:54:48 -07:00
KAMEZAWA Hiroyuki
ad18ff9dbf add nodeGetCPUmap() for getting available CPU IDs in a cpumap.
Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2012-03-06 21:54:48 -07:00
Roopa Prabhu
ce43483caf qemu: install port profile and mac address on netdev hostdevs
These changes are applied only if the hostdev has a parent net device
(i.e. if it was defined as "<interface type='hostdev'>" rather than
just "<hostdev>").  If the parent netdevice has virtual port
information, the original virtualport associate functions are called
(these set and restore both mac and port profile on an
interface). Otherwise, only mac address is set on the device.

Note that This is only supported for SR-IOV Virtual Functions (not for
standard PCI or USB netdevs), and virtualport association is only
supported for 802.1Qbh. For all other types of cards and types of
virtualport, a "Config Unsupported" error is returned and the
operation fails.

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
2012-03-06 06:04:04 -05:00
Roopa Prabhu
5095bf06f1 util: support functions for mac/portprofile associations on hostdev
This patch adds the following:

- functions to set and get vf configs
- Functions to replace and store vf configs (Only mac address is handled today.
  But the functions can be easily extended for vlans and other vf configs)
- function to dump link dev info (This is moved from virnetdevvportprofile.c)

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
2012-03-06 06:03:51 -05:00
Roopa Prabhu
b8b702734c util: two new pci util functions
pciDeviceGetVirtualFunctionInfo returns pf netdevice name and virtual
function index for a given vf. This is just a wrapper around existing functions
to return vf's pf and vf_index with one api call

pciConfigAddressToSysfsfile returns the sysfile pci device link
from a 'struct pci_config_address'

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
2012-03-06 06:03:46 -05:00
Laine Stump
ac9ca01cc4 conf: change virDomainNetRemove from static to global
This exact code is duplicated in qemuDomainDetachNetDevice().
2012-03-05 23:24:38 -05:00
Laine Stump
3b1c191fe7 conf: parse/format type='hostdev' network interfaces
This is the new interface type that sets up an SR-IOV PCI network
device to be assigned to the guest with PCI passthrough after
initializing some network device-specific things from the config
(e.g. MAC address, virtualport profile parameters). Here is an example
of the syntax:

  <interface type='hostdev' managed='yes'>
    <source>
      <address type='pci' domain='0' bus='0' slot='4' function='3'/>
    </source>
    <mac address='00:11:22:33:44:55'/>
    <address type='pci' domain='0' bus='0' slot='7' function='0'/>
  </interface>

This would assign the PCI card from bus 0 slot 4 function 3 on the
host, to bus 0 slot 7 function 0 on the guest, but would first set the
MAC address of the card to 00:11:22:33:44:55.

NB: The parser and formatter don't care if the PCI card being
specified is a standard single function network adapter, or a virtual
function (VF) of an SR-IOV capable network adapter, but the upcoming
code that implements the back end of this config will work *only* with
SR-IOV VFs. This is because modifying the mac address of a standard
network adapter prior to assigning it to a guest is pointless - part
of the device reset that occurs during that process will reset the MAC
address to the value programmed into the card's firmware.

Although it's not supported by any of libvirt's hypervisor drivers,
usb network hostdevs are also supported in the parser and formatter
for completeness and consistency. <source> syntax is identical to that
for plain <hostdev> devices, except that the <address> element should
have "type='usb'" added if bus/device are specified:

  <interface type='hostdev'>
    <source>
      <address type='usb' bus='0' device='4'/>
    </source>
    <mac address='00:11:22:33:44:55'/>
  </interface>

If the vendor/product form of usb specification is used, type='usb'
is implied:

  <interface type='hostdev'>
    <source>
      <vendor id='0x0012'/>
      <product id='0x24dd'/>
    </source>
    <mac address='00:11:22:33:44:55'/>
  </interface>

Again, the upcoming patch to fill in the backend of this functionality
will log an error and fail with "Unsupported Config" if you actually
try to assign a USB network adapter to a guest using <interface
type='hostdev'> - just use a standard <hostdev> entry in that case
(and also for single-port PCI adapters).
2012-03-05 23:24:28 -05:00
Laine Stump
cc5b1fe59a conf: hostdev utility functions
Three new functions useful in other files:

virDomainHostdevInsert:

Add a new hostdev at the end of the array. This would more sensibly be
called virDomainHostdevAppend, but the existing functions for other
types of devices are called Insert.

virDomainHostdevRemove:

Eliminates one entry from the hostdevs array, but doesn't free it;
patterned after the code at the end of the two
qemuDomainDetachHostXXXDevice functions (and also other pre-existing
virDomainXXXRemove functions for other device types).

virDomainHostdevFind:

This function is patterned from the search loops at the top of
qemuDomainDetachHostPciDevice and qemuDomainDetachHostUsbDevice, and
will be used to re-factor those (and other detach-related) functions.
2012-03-05 23:24:09 -05:00
Laine Stump
29293930a9 conf: make hostdev info a separate object
In order to allow for a virDomainHostdevDef that uses the
virDomainDeviceInfo of a "higher level" device (such as a
virDomainNetDef), this patch changes the virDomainDeviceInfo in the
HostdevDef into a virDomainDeviceInfoPtr. Rather than adding checks
all over the code to check for a null info, we just guarantee that it
is always valid. The new function virDomainHostdevDefAlloc() allocates
a virDomainDeviceInfo and plugs it in, and virDomainHostdevDefFree()
makes sure it is freed.

There were 4 places allocating virDomainHostdevDefs, all of them
parsers of one sort or another, and those have all had their
VIR_ALLOC(hostdev) changed to virDomainHostdevDefAlloc(). Other than
that, and the new functions, all the rest of the changes are just
mechanical removals of "&" or changing "." to "->".
2012-03-05 23:23:44 -05:00
Laine Stump
513fc05750 fix alphabetical order of virNetlink functions in symbol file 2012-02-29 15:26:13 -05:00
D. Herrendoerfer
e3ba402581 util: Add netlink event handling to virnetlink.c
This code adds a netlink event interface to libvirt.
It is based upon the event_poll code and makes use of
it. An event is generated for each netlink message sent
to the libvirt pid.

Signed-off-by: D. Herrendoerfer <d.herrendoerfer@herrendoerfer.name>
2012-02-29 10:37:24 -05:00
Osier Yang
7eadfddad5 conf: Add helper function to look up disk controller model 2012-02-28 14:27:08 +08:00
Peter Krempa
3f4238d771 util: Add helpers for safe domain console operations
This patch adds a set of functions used in creating console streams for
domains using PTYs and ensures mutually exclusive access to the PTYs.

If mutually exclusive access is not used, two clients may open the same
console, which results in corruption on both clients as both of them
race to read data from the PTY.

Two approaches are used to ensure this:
1) Internal data structure holding open PTYs.
        This is used internally and enables the user to forcibly
        terminate another console connection eg. when somebody leaves
        the console open on another host.

2) UUCP style lock files:
        This uses UUCP lock files according to the  FHS
        ( http://www.pathname.com/fhs/pub/fhs-2.3.html#VARLOCKLOCKFILES )
        to check if other programs (like minicom) are not using the pty
        device of the console.

        This feature is disabled by default and may be enabled using
        configure parameter
        --with-console-lock-files=/path/to/lock/file/directory
        or --with-console-lock-files=auto (which tries to infer the
        location from OS used (currently only linux).

        On usual linux systems, normal users may not write to the
        /var/lock directory containing the locks. This poses problems
        while in session mode. If the current user has no access to the
        lockfile directory, check for presence of the file is still
        done, but no lock file is created. This does NOT result in an
        error.
2012-02-27 15:05:17 +01:00
Martin Kletzander
9f748277bb Fixed URI parsing
Function xmlParseURI does not remove square brackets around IPv6
address when parsing. One of the solutions is making wrappers around
functions working with xmlURI*. This assures that uri->server will be
always properly assigned and it doesn't have to be changed when used
on some new place in the code.
For this purpose, functions virParseURI and virSaveURI were
added. These function are wrappers around xmlParseURI and xmlSaveUri
respectively.
Also there is one new syntax check function to prohibit these functions
anywhere else.

File changes:
 - src/util/viruri.h        -- declaration
 - src/util/viruri.c        -- definition
 - src/libvirt_private.syms -- symbol export
 - src/Makefile.am          -- added source and header files
 - cfg.mk                   -- added sc_prohibit_xmlURI
 - all others               -- ID name and include fixes
2012-02-24 16:49:21 -07:00
Jiri Denemark
5fadb1549d Introduce virStorageFileIsClusterFS 2012-02-23 14:23:45 +01:00
Ansis Atteka
df81004632 network: support Open vSwitch
This patch allows libvirt to add interfaces to already
existing Open vSwitch bridges. The following syntax in
domain XML file can be used:

    <interface type='bridge'>
      <mac address='52:54:00:d0:3f:f2'/>
      <source bridge='ovsbr'/>
      <virtualport type='openvswitch'>
        <parameters interfaceid='921a80cd-e6de-5a2e-db9c-ab27f15a6e1d'/>
      </virtualport>
      <address type='pci' domain='0x0000' bus='0x00'
                          slot='0x03' function='0x0'/>
    </interface>

or if libvirt should auto-generate the interfaceid use
following syntax:

    <interface type='bridge'>
      <mac address='52:54:00:d0:3f:f2'/>
      <source bridge='ovsbr'/>
      <virtualport type='openvswitch'>
      </virtualport>
      <address type='pci' domain='0x0000' bus='0x00'
                          slot='0x03' function='0x0'/>
    </interface>

It is also possible to pass an optional profileid. To do that
use following syntax:

   <interface type='bridge'>
     <source bridge='ovsbr'/>
     <mac address='00:55:1a:65:a2:8d'/>
     <virtualport type='openvswitch'>
       <parameters interfaceid='921a80cd-e6de-5a2e-db9c-ab27f15a6e1d'
                   profileid='test-profile'/>
     </virtualport>
   </interface>

To create Open vSwitch bridge install Open vSwitch and
run the following command:

    ovs-vsctl add-br ovsbr
2012-02-15 16:04:54 -05:00
Laine Stump
9368465f75 conf: rename virDomainNetGetActualDirectVirtPortProfile
An upcoming patch will add a <virtualport> element to interfaces of
type='bridge', so it makes sense to give this function a more generic
name.
2012-02-15 16:04:53 -05:00
Osier Yang
7c90026db9 npiv: Auto-generate WWN if it's not specified
The auto-generated WWN comply with the new addressing schema of WWN:

<quote>
the first nibble is either hex 5 or 6 followed by a 3-byte vendor
identifier and 36 bits for a vendor-specified serial number.
</quote>

We choose hex 5 for the first nibble. And for the 3-bytes vendor ID,
we uses the OUI according to underlying hypervisor type, (invoking
virConnectGetType to get the virt type). e.g. If virConnectGetType
returns "QEMU", we use Qumranet's OUI (00:1A:4A), if returns
ESX|VMWARE, we use VMWARE's OUI (00:05:69). Currently it only
supports qemu|xen|libxl|xenapi|hyperv|esx|vmware drivers. The last
36 bits are auto-generated.
2012-02-10 12:53:25 +08:00
Daniel P. Berrange
21fe874832 Update symbols file for virFileDirectFd/virFileWrapperFd rename 2012-02-08 19:50:15 +00:00
D. Herrendoerfer
d04394288f util: rename netlink.[ch] to virnetlink.[ch]
Rename the src/util/netlink files to src/util/virnetlink to
better fit the naming scheme. Also rename nlComm to virNetlinkCommand.

Signed-off-by: D. Herrendoerfer <d.herrendoerfer@herrendoerfer.name>
2012-02-03 15:27:40 -05:00
Laine Stump
26e9fdc0bc build: add missing virStorageFileResize to libvirt_private.syms
This was forgotten when the function was originally written (not
noticed because it wasn't used at the time). It's required for
proper compilation with modules enabled after applying the recent
virStorageVolResize patches.
2012-02-01 16:14:46 -05:00
Laine Stump
f594cddaf2 build: add missing virCommandAddCap to libvirt_private.syms
This was forgotten when the function was initially written (not
noticed because it wasn't used at the time). It's required for proper
compilation with modules enabled after applying the recent rawio
patches.
2012-02-01 16:14:46 -05:00
Daniel P. Berrange
9b516aa31b Move virEmitXMLWarning into xml.h
The virEmitXMLWarning function should always have been in
the xml.[hc] files, and should use virXML as its name
prefix

* src/util/util.c, src/util/util.h: Remove virEmitXMLWarning
* src/util/xml.c, src/util/xml.h: Add virXMLEmitWarning
2012-01-27 18:03:30 +00:00
Daniel P. Berrange
510fa47c2a Move virMacAddrXXX functions to src/util/virmacaddr.[ch]
Move the virMacAddrXXX functions out of util.[ch] and into a
new dedicate file virmacaddr.[ch]
2012-01-27 17:56:10 +00:00
Daniel P. Berrange
4ce98dadcc Rename virXXXXMacAddr to virMacAddrXXX
Rename virFormatMacAddr, virGenerateMacAddr and virParseMacAddr
to virMacAddrFormat, virMacAddrGenerate and virMacAddrParse
respectively
2012-01-27 17:53:44 +00:00
Stefan Berger
8fa78dd49c nwfilter: Force instantiation of filters upon driver reload
Introduce a function that rebuilds all running VMs' filters. Call
this function when reloading the nwfilter driver.

This addresses a problem introduced by the 2nd patch that typically
causes no filters to be reinstantiate anymore upon driver reload
since their XML has not changed. Yet the current behavior is that
upon a SIGHUP all filters get reinstantiated.
2012-01-27 08:19:58 -05:00
Daniel P. Berrange
e95ef67b35 Introduce new API for generating random numbers
The old virRandom() API was not generating good random numbers.
Replace it with a new API virRandomBits which instead of being
told the upper limit, gets told the number of bits of randomness
required.

* src/util/virrandom.c, src/util/virrandom.h: Add virRandomBits,
  and move virRandomInitialize
* src/util/util.h, src/util/util.c: Delete virRandom and
  virRandomInitialize
* src/libvirt.c, src/security/security_selinux.c,
  src/test/test_driver.c, src/util/iohelper.c: Update for
  changes from virRandom to virRandomBits
* src/storage/storage_backend_iscsi.c: Remove bogus call
  to virRandomInitialize & convert to virRandomBits
2012-01-26 14:03:14 +00:00
Daniel P. Berrange
ef7efbc6ef Add virFileTouch for creating empty files
Add a virFileTouch API which ensures that a file will always
exist, even if zero length

* src/util/virfile.c, src/util/virfile.h,
  src/libvirt_private.syms: Introduce virFileTouch
2012-01-25 14:11:03 +00:00
Eric Blake
c2551bea56 error: drop old-style error reporting
While we still don't want to enable gcc's new -Wformat-literal
warning, I found a rather easy case where the warning could be
reduced, by getting rid of obsolete error-reporting practices.
This is the last place where we were passing the (unused) net
and conn arguments for constructing an error.

* src/util/virterror_internal.h (virErrorMsg): Delete prototype.
(virReportError): Delete macro.
* src/util/virterror.c (virErrorMsg): Make static.
* src/libvirt_private.syms (virterror_internal.h): Drop export.
* src/util/conf.c (virConfError): Convert to macro.
(virConfErrorHelper): New function, and adjust error calls.
* src/xen/xen_hypervisor.c (virXenErrorFunc): Delete.
(xenHypervisorGetSchedulerType)
(xenHypervisorGetSchedulerParameters)
(xenHypervisorSetSchedulerParameters)
(xenHypervisorDomainBlockStats)
(xenHypervisorDomainInterfaceStats)
(xenHypervisorDomainGetOSType)
(xenHypervisorNodeGetCellsFreeMemory, xenHypervisorGetVcpus):
Update callers.
2012-01-19 13:26:04 -07:00
Eric Blake
61ca98b054 util: add new file for virTypedParameter utils
Preparation for another patch that refactors common patterns
into the new file for fewer lines of code overall.

* src/util/util.h (virTypedParameterArrayClear): Move...
* src/util/virtypedparam.h: ...to new file.
(virTypedParameterArrayValidate, virTypedParameterAssign): New
prototypes.
* src/util/util.c (virTypedParameterArrayClear): Likewise.
* src/util/virtypedparam.c: New file.
* po/POTFILES.in: Mark file for translation.
* src/Makefile.am (UTIL_SOURCES): Build it.
* src/libvirt_private.syms (util.h): Split...
(virtypedparam.h): to new section.
(virkeycode.h): Sort.
* daemon/remote.c: Adjust callers.
* tools/virsh.c: Likewise.
2012-01-19 13:14:10 -07:00
Daniel P. Berrange
2f9dc36d49 Rename APIs for fetching UNIX socket credentials
To avoid a namespace clash with forthcoming identity APIs,
rename the virNet*GetLocalIdentity() APIs to have the form
virNet*GetUNIXIdentity()

* daemon/remote.c, src/libvirt_private.syms: Update
  for renamed APIs
* src/rpc/virnetserverclient.c, src/rpc/virnetserverclient.h,
  src/rpc/virnetsocket.c, src/rpc/virnetsocket.h: s/LocalIdentity/UNIXIdentity/
2012-01-19 15:39:52 +00:00
Daniel P. Berrange
1fff03ef9b Add virGetGroupName to convert from GID to group name 2012-01-19 13:30:04 +00:00
Daniel P. Berrange
c53ba61b21 Fix startup of LXC containers with filesystems containing symlinks
Given an LXC guest with a root filesystem path of

  /export/lxc/roots/helloworld/root

During startup, we will pivot the root filesystem to end up
at

  /.oldroot/export/lxc/roots/helloworld/root

We then try to open

  /.oldroot/export/lxc/roots/helloworld/root/dev/pts

Now consider if '/export/lxc' is an absolute symlink pointing
to '/media/lxc'. The kernel will try to open

  /media/lxc/roots/helloworld/root/dev/pts

whereas it should be trying to open

  /.oldroot//media/lxc/roots/helloworld/root/dev/pts

To deal with the fact that the root filesystem can be moved,
we need to resolve symlinks in *any* part of the filesystem
source path.

* src/libvirt_private.syms, src/util/util.c,
  src/util/util.h: Add virFileResolveAllLinks to resolve
  all symlinks in a path
* src/lxc/lxc_container.c: Resolve all symlinks in filesystem
  paths during startup
2012-01-18 13:34:42 +00:00
Deepak C Shetty
d9e0d8204b Add new attribute wrpolicy to <driver> element
This introduces new attribute wrpolicy with only supported
value as immediate. This will be an optional
attribute with no defaults. This helps specify whether
to skip the host page cache.

When wrpolicy is specified, meaning when wrpolicy=immediate
a writeback is explicitly initiated for the dirty pages in
the host page cache as part of the guest file write operation.

Usage:
<filesystem type='mount' accessmode='passthrough'>
  <driver type='path' wrpolicy='immediate'/>
  <source dir='/export/to/guest'/>
  <target dir='mount_tag'/>
</filesystem>

Currently this only works with type='mount' for the QEMU/KVM driver.

Signed-off-by: Deepak C Shetty <deepakcs@linux.vnet.ibm.com>
2012-01-17 15:37:42 -07:00
Jiri Denemark
e7201afdf7 qemu: Add support for host CPU modes
This adds support for host-model and host-passthrough CPU modes to qemu
driver. The host-passthrough mode is mapped to -cpu host.
2012-01-17 12:22:19 +01:00
Jiri Denemark
277bc0dcb8 cpu: Update guest CPU in host-* mode
VIR_DOMAIN_XML_UPDATE_CPU flag for virDomainGetXMLDesc may be used to
get updated custom mode guest CPU definition in case it depends on host
CPU. This patch implements the same behavior for host-model and
host-passthrough CPU modes.
2012-01-17 11:42:56 +01:00
Paolo Bonzini
ed6bd4bc49 export virNetDevGetVirtualFunctions as a private symbol
This avoids a linking error.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2012-01-13 08:12:16 -07:00
Osier Yang
5edfcaae6f qemu: Support copy on read for disk
The new introduced optional attribute "copy_on_read</code> controls
whether to copy read backing file into the image file. The value can
be either "on" or "off". Copy-on-read avoids accessing the same backing
file sectors repeatedly and is useful when the backing file is over a
slow network. By default copy-on-read is off.
2012-01-13 10:08:15 +08:00
Stefan Berger
64484d550d Address side effects of accessing vars via index
Address side effect of accessing a variable via an index: Filters
accessing a variable where an element is accessed that is beyond the
size of the list (for example $TEST[10] and only 2 elements are available)
cannot instantiate that filter. Test for this and report proper error
to user.
2012-01-11 06:42:37 -05:00
Stefan Berger
80e9a5cd4c Introduce possibility to have an iterator per variable
This patch introduces the capability to use a different iterator per
variable.

The currently supported notation of variables in a filtering rule like

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A' srcportstart='$B'/>
  </rule>

processes the two lists 'A' and 'B' in parallel. This means that A and B
must have the same number of 'N' elements and that 'N' rules will be 
instantiated (assuming all tuples from A and B are unique).

In this patch we now introduce the assignment of variables to different
iterators. Therefore a rule like

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A[@1]' srcportstart='$B[@2]'/>
  </rule>

will now create every combination of elements in A with elements in B since
A has been assigned to an iterator with Id '1' and B has been assigned to an
iterator with Id '2', thus processing their value independently.

The first rule has an equivalent notation of

  <rule action='accept' direction='out'>
     <tcp  srcipaddr='$A[@0]' srcportstart='$B[@0]'/>
  </rule>
2012-01-11 06:42:37 -05:00
Eric Blake
269ce467fc domiftune: clean up previous patches
Most severe here is a latent (but currently untriggered) memory leak
if any hypervisor ever adds a string interface property; the
remainder are mainly cosmetic.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_BANDWIDTH_*): Move
macros closer to interface that uses them, and document type.
* src/libvirt.c (virDomainSetInterfaceParameters)
(virDomainGetInterfaceParameters): Formatting tweaks.
* daemon/remote.c (remoteDispatchDomainGetInterfaceParameters):
Avoid memory leak.
* src/libvirt_public.syms (LIBVIRT_0.9.9): Sort lines.
* src/libvirt_private.syms (domain_conf.h): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSetInterfaceParameters): Fix
comments, break long lines.
2012-01-02 14:35:12 -07:00
Hu Tao
ee3de186b3 domiftune: Add a util function virDomainNetFind
Add a util function virDomainNetFind to find a domain's net def.
2011-12-29 18:27:35 +08:00
Michal Privoznik
8a34f822e6 qemu: Keep list of USB devices attached to domains
In order to avoid situation where a USB device is
in use by two domains, we must keep a list of already
attached devices like we do for PCI.
2011-12-24 18:12:04 +01:00
Hu Tao
059425ae45 Add functions to set/get cgroup cpuset parameters 2011-12-20 09:13:36 -07:00
Daniel P. Berrange
34ad13536e Hide use of timers for domain event dispatch
Currently all drivers using domain events need to provide a callback
for handling a timer to dispatch events in a clean stack. There is
no technical reason for dispatch to go via driver specific code. It
could trivially be dispatched directly from the domain event code,
thus removing tedious boilerplate code from all drivers

Also fix the libxl & xen drivers to pass 'true' when creating the
virDomainEventState, since they run inside the daemon & thus always
expect events to be present.

* src/conf/domain_event.c, src/conf/domain_event.h: Internalize
  dispatch of events from timer callback
* src/libxl/libxl_driver.c, src/lxc/lxc_driver.c,
  src/qemu/qemu_domain.c, src/qemu/qemu_driver.c,
  src/remote/remote_driver.c, src/test/test_driver.c,
  src/uml/uml_driver.c, src/vbox/vbox_tmpl.c,
  src/xen/xen_driver.c: Remove all timer dispatch functions
2011-12-19 11:08:24 +00:00
Daniel P. Berrange
2c2d533768 Remove decl of all APIs related to domain event callbacks & queues
The virDomainEventCallbackList and virDomainEventQueue APIs are
now solely helpers used internally by virDomainEventState APIs.
Remove their decls from domain_event.h since no driver code should
need to use them any more.

* src/conf/domain_event.c: Make virDomainEventCallbackList and
  virDomainEventQueue APIs static & remove some unused APIs
* src/conf/domain_event.h, src/libvirt_private.syms: Remove
  virDomainEventCallbackList and virDomainEventQueue APIs
2011-12-19 11:08:11 +00:00
Daniel P. Berrange
4f5326c315 Add APIs to allow management of callbacks purely with virDomainEventState
While virDomainEventState has APIs for managing removal of callbacks,
while locked, adding callbacks in the first place requires direct
access to the virDomainEventCallbackList structure. This is not
threadsafe since it is bypassing the virDomainEventState locks

* src/conf/domain_event.c, src/conf/domain_event.h,
  src/libvirt_private.syms: Add APIs for managing callbacks
  via virDomainEventState.
2011-12-19 11:08:10 +00:00
Daniel P. Berrange
d09f6ba5fe Return count of callbacks when registering callbacks
When registering a callback for a particular event some callers
need to know how many callbacks already exist for that event.
While it is possible to ask for a count, this is not free from
race conditions when threaded. Thus the API for registering
callbacks should return the count of callbacks. Also rename
virDomainEventStateDeregisterAny to virDomainEventStateDeregisterID

* src/conf/domain_event.c, src/conf/domain_event.h,
  src/libvirt_private.syms: Return count of callbacks when
  registering callbacks
* src/libxl/libxl_driver.c, src/libxl/libxl_driver.c,
  src/qemu/qemu_driver.c, src/remote/remote_driver.c,
  src/remote/remote_driver.c, src/uml/uml_driver.c,
  src/vbox/vbox_tmpl.c, src/xen/xen_driver.c: Update
  for change in APIs
2011-12-19 11:08:10 +00:00
Lei Li
ae52342754 Provide a helper method virDomainLiveConfigHelperMethod
This chunk of code below repeated in several functions, factor it into
a helper method virDomainLiveConfigHelperMethod to eliminate duplicated code
based on Eric and Adam's suggestion. I have tested it for all the
relevant APIs changed.

Signed-off-by: Eric Blake <eblake@redhat.com>
Signed-off-by: Lei Li <lilei@linux.vnet.ibm.com>
2011-12-13 15:10:42 -07:00
Eric Blake
f59a941757 build: fix build with older libxml2
On RHEL 5, with libxml2-2.6.26, the build failed with:
virsh.c: In function 'vshNodeIsSuperset':
virsh.c:11951: warning: implicit declaration of function 'xmlChildElementCount'

(or if warnings aren't errors, a link failure later on).

* src/util/xml.h (virXMLChildElementCount): New prototype.
* src/util/xml.c (virXMLChildElementCount): New function.
* src/libvirt_private.syms (xml.h): Export it.
* tools/virsh.c (vshNodeIsSuperset): Use it.
2011-12-08 11:37:24 +08:00
Daniel P. Berrange
b265beda55 Fix incorrect symbols for virtime.h module breaking Mingw32
The Mingw32 linker highlighted that the symbols for virtime.h
declared in libvirt_private.syms were incorrect

* src/libvirt_private.syms: Fix virtime.h symbols
2011-12-05 14:05:22 +00:00
Daniel P. Berrange
a8bb75a3e6 Remove time APIs from src/util/util.h
The virTimestamp and virTimeMs functions in src/util/util.h
duplicate functionality from virtime.h, in a non-async signal
safe manner. Remove them, and convert all code over to the new
APIs.

* src/util/util.c, src/util/util.h: Delete virTimeMs and virTimestamp
* src/lxc/lxc_driver.c, src/qemu/qemu_domain.c,
  src/qemu/qemu_driver.c, src/qemu/qemu_migration.c,
  src/qemu/qemu_process.c, src/util/event_poll.c: Convert to use
  virtime APIs
2011-11-30 11:43:50 +00:00
Daniel P. Berrange
3ec1289896 Add internal APIs for dealing with time
The logging APIs need to be able to generate formatted timestamps
using only async signal safe functions. This rules out using
gmtime/localtime/malloc/gettimeday(!) and much more.

Introduce a new internal API which is async signal safe.

  virTimeMillisNowRaw replacement for gettimeofday. Uses clock_gettime
                      where available, otherwise falls back to the unsafe
                      gettimeofday

  virTimeFieldsNowRaw  replacements for gmtime(), convert a timestamp
  virTimeFieldsThenRaw into a broken out set of fields. No localtime()
                       replacement is provided, because converting to
                       local time is not practical with only async signal
                       safe APIs.

  virTimeStringNowRaw  replacements for strftime() which print a timestamp
  virTimeStringThenRaw into a string, using a pre-determined format, with
                       a fixed size buffer (VIR_TIME_STRING_BUFLEN)

For each of these there is also a version without the Raw postfix
which raises a full libvirt error. These versions are not async
signal safe

* src/Makefile.am, src/util/virtime.c, src/util/virtime.h: New files
* src/libvirt_private.syms: New APis
* configure.ac: Check for clock_gettime in -lrt
* tests/virtimetest.c, tests/Makefile.am: Test new APIs
2011-11-30 11:43:49 +00:00
Daniel P. Berrange
380110cf08 Remove obsolete virGetPMCapabilities sym from private symbols file
Fix the build on Mingw32 by removing the now obsolete
virGetPMCapabilities symbol from the private exports file

* src/libvirt_private.syms: Remove virGetPMCapabilities
2011-11-30 11:42:57 +00:00
Daniel P. Berrange
f5272027c3 Add export of node suspend capabilities APIs
* src/libvirt_private.syms: Export virNodeSuspendSupportsTarget
  and virNodeSuspendGetTargetMask
2011-11-30 10:12:29 +00:00
Hu Tao
93ab58595d blkiotune: add qemu support for blkiotune.device_weight
Implement setting/getting per-device blkio weights in qemu,
using the cgroups blkio.weight_device tunable.
2011-11-29 12:26:21 -07:00
Hu Tao
6ac81c8ec8 blkiotune: add interface for blkiotune.device_weight
This adds per-device weights to <blkiotune>.  Note that the
cgroups implementation only supports weights per block device,
and not per-file within the device; hence this option must be
global to the domain definition rather than tied to individual
<devices>/<disk> entries:

<domain ...>
  <blkiotune>
    <device>
      <path>/path/to/block</path>
      <weight>1000</weight>
    </device>
  </blkiotune>
..

This patch also adds a parameter --device-weights to virsh command
blkiotune for setting/getting blkiotune.weight_device for any
hypervisor that supports it.  All <device> entries under
<blkiotune> are concatenated into a single string attribute under
virDomain{Get,Set}BlkioParameters, named "device_weight".

Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-11-29 12:26:21 -07:00
Srivatsa S. Bhat
4ddb37c395 Implement the core API to suspend/resume the host
Add the core functions that implement the functionality of the API.
Suspend is done by using an asynchronous mechanism so that we can return
the status to the caller before the host gets suspended. This asynchronous
operation is achieved by suspending the host in a separate thread of
execution. However, returning the status to the caller is only best-effort,
but not guaranteed.

To resume the host, an RTC alarm is set up (based on how long we want to
suspend) before suspending the host. When this alarm fires, the host
gets woken up.

Suspend-to-RAM operation on a host running Linux can take upto more than 20
seconds, depending on the load of the system. (Freezing of tasks, an operation
preceding any suspend operation, is given up after a 20 second timeout).
And Suspend-to-Disk can take even more time, considering the time required
for compaction, creating the memory image and writing it to disk etc.
So, we do not allow the user to specify a suspend duration of less than 60
seconds, to be on the safer side, since we don't want to prematurely declare
failure when we only had to wait for some more time.
2011-11-29 17:29:17 +08:00
Jiri Denemark
f4324e3292 Implement keepalive protocol in libvirt daemon 2011-11-24 11:44:08 +01:00
Stefan Berger
ad6c67cf85 Enable detection of multiple IP addresses
In preparation of DHCP Snooping and the detection of multiple IP
addresses per interface:

The hash table that is used to collect the detected IP address of an
interface can so far only handle one IP address per interface. With
this patch we extend this to allow it to handle a list of IP addresses.

Above changes the returned variable type of virNWFilterGetIpAddrForIfname()
from char * to virNWFilterVarValuePtr; adapt all existing functions calling
this function.
2011-11-22 19:05:45 -05:00
Stefan Berger
ba3bf00acf Add support for STP filtering
This patch adds support for filtering of STP (spanning tree protocol) traffic
to the parser and makes us of the ebtables support for STP filtering. This code
now enables the filtering of traffic in chains with prefix 'stp'.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-22 15:12:03 -05:00
Srivatsa S. Bhat
e352b16400 Export KVM Host Power Management capabilities
This patch exports KVM Host Power Management capabilities as XML so that
higher-level systems management software can make use of these features
available in the host.

The script "pm-is-supported" (from pm-utils package) is run to discover if
Suspend-to-RAM (S3) or Suspend-to-Disk (S4) is supported by the host.
If either of them are supported, then a new tag "<power_management>" is
introduced in the XML under the <host> tag.

However in case the query to check for power management features succeeded,
but the host does not support any such feature, then the XML will contain
an empty <power_management/> tag. In the event that the PM query itself
failed, the XML will not contain any "power_management" tag.

To use this, new APIs could be implemented in libvirt to exploit power
management features such as S3/S4.
2011-11-22 11:31:22 +08:00
Michal Privoznik
2e37bf42d2 qemu: Copy console definition from serial
Now, when we support multiple consoles per domain,
the vm->def->console[0] can still remain an alias
for vm->def->serial[0]; However, we need to copy
it's source definition as well otherwise we'll regress
on virDomainOpenConsole.
2011-11-21 14:53:13 +01:00
Daniel P. Berrange
66d5d3f186 Fix build on Mingw32 wrt export of virNetServerGetDBusConn
Mingw32 complains if you request export of a symbol which does
not in fact exist.

* src/libvirt_bridge.syms, src/libvirt_macvtap.syms: Delete
  obsolete files
* src/libvirt_private.syms: Remove virNetServerGetDBusConn
* src/libvirt_dbus.syms: Add virNetServerGetDBusConn
2011-11-21 11:46:52 +00:00
Stefan Berger
c80296e21a Create rules for each member of a list
This patch extends the NWFilter driver for Linux (ebiptables) to create
rules for each member of a previously introduced list. If for example
an attribute value (internally) looks like this:

IP = [10.0.0.1, 10.0.0.2, 10.0.0.3]

then 3 rules will be generated for a rule accessing the variable 'IP',
one for each member of the list. The effect of this is that this now
allows for filtering for multiple values in one field. This can then be
used to support for filtering/allowing of multiple IP addresses per
interface.

An iterator is introduced that extracts each member of a list and
puts it into a hash table which then is passed to the function creating
a rule. For the above example the iterator would cause 3 loops.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
581d1cea34 Rework value part of name-value pairs
NWFilters can be provided name-value pairs using the following
XML notation:

      <filterref filter='xyz'>
        <parameter name='PORT' value='80'/>
        <parameter name='VAL' value='abc'/>
      </filterref>

The internal representation currently is so that a name is stored as a
string and the value as well. This patch now addresses the value part of it
and introduces a data structure for storing a value either as a simple
value or as an array for later support of lists.

This patch adjusts all code that was handling the values in hash tables
and makes it use the new data type.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:18 -05:00
Stefan Berger
e9640b99ef Add function to get hash table's key/value pairs
Add a function to the virHashTable for getting an array of the hash table's
key-value pairs and have the keys (optionally) sorted.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-11-18 11:58:17 -05:00
Daniel P. Berrange
0c1587e10b Fix up ordering of private symbols file
Fix ordering of symbols after re-arranging network device
management API source files

* src/libvirt_private.syms: Fix ordering
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
91904106a2 Move ifaceMacvtapLinkDump and ifaceGetNthParent functions
Move the ifaceMacvtapLinkDump and ifaceGetNthParent functions
into virnetdevvportprofile.c since they are specific to that
code. This avoids polluting the headers with the Linux specific
netlink data types

* src/util/interface.c, src/util/interface.h: Move
  ifaceMacvtapLinkDump and ifaceGetNthParent functions and delete
  remaining file
* src/util/virnetdevvportprofile.c: Add ifaceMacvtapLinkDump
  and ifaceGetNthParent functions
* src/network/bridge_driver.c, src/nwfilter/nwfilter_gentech_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c, src/util/virnetdevmacvlan.c:
  Remove include of interface.h
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
8f688c85af Rename APIs for dealing with virtual/physical functions
Rename ifaceIsVirtualFunction to virNetDevIsVirtualFunction,
ifaceGetVirtualFunctionIndex to virNetDevGetVirtualFunctionIndex
and ifaceGetPhysicalFunction to virNetDevGetPhysicalFunction

* src/util/interface.c, src/util/interface.h: Rename APIs
* src/util/virnetdevvportprofile.c: Update for API rename
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
6e0c4dce0b Rename ifaceCheck to virNetDevValidateConfig
Rename the ifaceCheck method to virNetDevValidateConfig and change
so that it always raises an error and returns -1 on error.

* src/util/interface.c, src/util/interface.h: Rename ifaceCheck
  to virNetDevValidateConfig
* src/nwfilter/nwfilter_gentech_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c: Update for API rename
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
50f190856d Rename ifaceGetIPAddress to virNetDevGetIPv4Address
To match up with the existing virNetDevSetIPv4Address, rename
ifaceGetIPAddress to virNetDevGetIPv4Address

* util/interface.h, util/interface.c: Rename API
* network/bridge_driver.c: Update for API rename
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
ebbb6bd11f Rename ifaceGetIndex and ifaceGetVLAN
Rename the ifaceGetIndex method to virNetDevGetIndex and
ifaceGetVlanID to virNetDevGetVLanID. Also change the error
reporting behaviour to always raise errors and return -1 on
failure

* util/interface.c, util/interface.h: Rename ifaceGetIndex
  and ifaceGetVLAN
* nwfilter/nwfilter_gentech_driver.c, nwfilter/nwfilter_learnipaddr.c,
  nwfilter/nwfilter_learnipaddr.c, util/virnetdevvportprofile.c: Update
  for API renames and error handling changes
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
10462d5c78 Rename interface MAC address replacement APIs
Rename ifaceReplaceMacAddress to virNetDevReplaceMacAddress
and ifaceRestoreMacAddress to virNetDevRestoreMacAddress.

* util/interface.c, util/interface.h, util/virnetdevmacvlan.c:
  Rename APIs
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
57f0de4c26 Rename low level macvlan creation APIs
Rename ifaceMacvtapLinkAdd to virNetDevMacVLanCreate and
ifaceLinkDel to virNetDevMacVLanDelete. Strictly speaking
the latter isn't restricted to macvlan devices, but that's
the only use libvirt has for it.

* util/interface.c, util/interface.h,
  util/virnetdevmacvlan.c: Rename APIs
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
43925db7ca Rename Macvtap management APIs
In preparation for code re-organization, rename the Macvtap
management APIs to have the following patterns

  virNetDevMacVLanXXXXX     - macvlan/macvtap interface management
  virNetDevVPortProfileXXXX - virtual port profile management

* src/util/macvtap.c, src/util/macvtap.h: Rename APIs
* src/conf/domain_conf.c, src/network/bridge_driver.c,
  src/qemu/qemu_command.c, src/qemu/qemu_command.h,
  src/qemu/qemu_driver.c, src/qemu/qemu_hotplug.c,
  src/qemu/qemu_migration.c, src/qemu/qemu_process.c,
  src/qemu/qemu_process.h: Update for renamed APIs
2011-11-18 16:10:01 +00:00
Jim Fehlig
d47ab3fe61 Fix build with polkit0
I missed adding virNetServerGetDBusConn() to libvirtd_private.syms
in commit b8adfcc6, which didn't cause a problem in 0.9.6 but
results in this build error in 0.9.7

libvirtd-remote.o: In function `remoteDispatchAuthPolkit':
remote.c:(.text+0x188dd): undefined reference to `virNetServerGetDBusConn'
2011-11-16 14:11:59 -07:00
Eli Qiao
d776170012 util: Add netdev helper functions to private symbols
Signed-off-by: Eli Qiao <taget@linux.vnet.ibm.com>
2011-11-16 11:01:05 +08:00
Daniel P. Berrange
5240ad6580 Remove ifaceSetMac and ifaceGetMac APIs
The ifaceSetMac and ifaceGetMac APIs duplicate the functionality
of the virNetDevSetMAC and virNetDevGetMAC APIs, but returning
errno's instead of raising errors.

* src/util/interface.c, src/util/interface.h: Remove
  ifaceSetMac and ifaceGetMac APIs, adjusting callers
  for new error behaviour
2011-11-15 10:28:03 +00:00
Daniel P. Berrange
268085c3bd Remove ifaceUp, ifaceDown, ifaceCtrl & ifaceIsUp APIs
The ifaceUp, ifaceDown, ifaceCtrl & ifaceIsUp APIs can be replaced
with calls to virNetDevSetOnline and virNetDevIsOnline

* src/util/interface.c, src/util/interface.h: Delete ifaceUp,
  ifaceDown, ifaceCtrl & ifaceIsUp
* src/nwfilter/nwfilter_gentech_driver.c, src/util/macvtap.c:
  Update to use virNetDevSetOnline and virNetDevIsOnline
2011-11-15 10:28:02 +00:00
Daniel P. Berrange
767e01ceb1 Rename virVirtualPortProfileParams & APIs
Rename the virVirtualPortProfileParams struct to be
virNetDevVPortProfile, and rename the APIs to match
this prefix.

* src/util/network.c, src/util/network.h: Rename port profile
  APIs
* src/conf/domain_conf.c, src/conf/domain_conf.h,
  src/conf/network_conf.c, src/conf/network_conf.h,
  src/network/bridge_driver.c, src/qemu/qemu_hotplug.c,
  src/util/macvtap.c, src/util/macvtap.h: Update for
  renamed APIs/structs
2011-11-15 10:10:05 +00:00
Eric Blake
a218c81da2 API: add VIR_TYPED_PARAM_STRING
This allows strings to be transported between client and server
in the context of name-type-value virTypedParameter functions.
For compatibility,

    o new clients will not send strings to old servers, based on
      a feature check
    o new servers will not send strings to old clients without the
      flag VIR_TYPED_PARAM_STRING_OKAY; this will be enforced at
      the RPC layer in the next patch, so that drivers need not
      worry about it in general.  The one exception is that
      virDomainGetSchedulerParameters lacks a flags argument, so
      it must not return a string; drivers that forward that
      function on to virDomainGetSchedulerParametersFlags will
      have to pay attention to the flag.
    o the flag VIR_TYPED_PARAM_STRING_OKAY is set automatically,
      based on a feature check (so far, no driver implements it),
      so clients do not have to worry about it

Future patches can then enable the feature on a per-driver basis.

This patch also ensures that drivers can blindly strdup() field
names (previously, a malicious client could stuff 80 non-NUL bytes
into field and cause a read overrun).

* src/libvirt_internal.h (VIR_DRV_FEATURE_TYPED_PARAM_STRING): New
driver feature.
* src/libvirt.c (virTypedParameterValidateSet)
(virTypedParameterSanitizeGet): New helper functions.
(virDomainSetMemoryParameters, virDomainSetBlkioParameters)
(virDomainSetSchedulerParameters)
(virDomainSetSchedulerParametersFlags)
(virDomainGetMemoryParameters, virDomainGetBlkioParameters)
(virDomainGetSchedulerParameters)
(virDomainGetSchedulerParametersFlags, virDomainBlockStatsFlags):
Use them.
* src/util/util.h (virTypedParameterArrayClear): New helper
function.
* src/util/util.c (virTypedParameterArrayClear): Implement it.
* src/libvirt_private.syms (util.h): Export it.
Based on an initial patch by Hu Tao, with feedback from
Daniel P. Berrange.

Signed-off-by: Eric Blake <eblake@redhat.com>
2011-11-11 17:21:36 -07:00
Eli Qiao
329b2b2819 util: fix compile error on debian
Add virnetdev.h,virnetdevbridge.h,virnetdevtap.h to private symbols,
since debian linker no longer allows transitive link resolution

Signed-off-by: Eli Qiao <taget@linux.vnet.ibm.com>
2011-11-11 17:04:33 -07:00
Daniel P. Berrange
0eee075dc7 Adjust naming of network device bandwidth management APIs
Rename virBandwidth to virNetDevBandwidth, and virRate to
virNetDevBandwidthRate.

* src/util/network.c, src/util/network.h: Rename bandwidth
  structs and APIs
* src/conf/domain_conf.c, src/conf/domain_conf.h,
  src/conf/network_conf.c, src/conf/network_conf.h,
  src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/qemu/qemu_command.c, src/util/macvtap.c,
  src/util/macvtap.h, tools/virsh.c: Update for API changes.
2011-11-09 17:10:28 +00:00
Daniel P. Berrange
4c544e6c61 Santize naming of socket address APIs
The socket address APIs in src/util/network.h either take the
form  virSocketAddrXXX, virSocketXXX or virSocketXXXAddr.

Sanitize this so everything is virSocketAddrXXXX, and ensure
that the virSocketAddr parameter is always the first one.

* src/util/network.c, src/util/network.h: Santize socket
  address API naming
* src/conf/domain_conf.c, src/conf/network_conf.c,
  src/conf/nwfilter_conf.c, src/network/bridge_driver.c,
  src/nwfilter/nwfilter_ebiptables_driver.c,
  src/nwfilter/nwfilter_learnipaddr.c,
  src/qemu/qemu_command.c, src/rpc/virnetsocket.c,
  src/util/dnsmasq.c, src/util/iptables.c,
  src/util/virnetdev.c, src/vbox/vbox_tmpl.c: Update for
  API renaming
2011-11-09 17:10:23 +00:00
Osier Yang
d84b36263c qemu: Restore the original states of PCI device when restarting daemon
To support "managed" mode of host PCI device, we record the original
states (unbind_from_stub, remove_slot, and reprobe) so that could
reattach the device to host with original driver. But there is no XML
for theses attrs, and thus after daemon is restarted, we lose the
original states. It's easy to reproduce:

    1) virsh start domain
    2) virsh attach-device dom hostpci.xml (in 'managed' mode)
    3) service libvirtd restart
    4) virsh destroy domain

    You will see the device won't be bound to the original driver
if there was one.

This patch is to solve the problem by introducing internal XML
(won't be dumped to user, only dumped to status XML). The XML is:
    <origstates>
      <unbind/>
      <remove_slot/>
      <reprobe/>
    </origstates>

Which will be child node of <hostdev><source>...</souce></hostdev>.
(only for PCI device).

A new struct "virDomainHostdevOrigStates" is introduced for the XML,
and the according members are updated when preparing the PCI device.
And function "qemuUpdateActivePciHostdevs" is modified to honor
the original states. Use of qemuGetPciHostDeviceList is removed
in function "qemuUpdateActivePciHostdevs", and the "managed" value of
the device config is honored by the change. This fixes another problem
alongside:

    qemuGetPciHostDeviceList set the device as "managed" force
    regardless of whether the device is configured as "managed='yes'"
    or not in XML, which is not right.
2011-10-30 13:00:06 +08:00
Josh Durgin
5bd6271f59 storage: add auth to virDomainDiskDef
Add additional fields to let you specify the how to authenticate with a disk.
The secret to use may be referenced by a usage string or a UUID, i.e.:

<auth username='myuser'>
 <secret type='ceph' usage='secretname'/>
</auth>

or

<auth username='myuser'>
 <secret type='ceph' uuid='0a81f5b2-8403-7b23-c8d6-21ccc2f80d6f'/>
</auth>

Signed-off-by: Josh Durgin <josh.durgin@dreamhost.com>
2011-10-28 12:51:22 -06:00
Daniel P. Berrange
3ae0ab67e6 Extend RPC server to allow FD passing
The RPC server classes are extended to allow FDs to be received
from clients with calls. There is not currently any way for a
procedure to pass FDs back to the client with replies

* daemon/remote.c, src/rpc/gendispatch.pl: Change virNetMessageHeaderPtr
  param to virNetMessagePtr in dispatcher impls
* src/rpc/virnetserver.c, src/rpc/virnetserverclient.c,
  src/rpc/virnetserverprogram.c, src/rpc/virnetserverprogram.h:
  Extend to support FD passing
2011-10-28 10:43:00 +01:00
Daniel P. Berrange
36a9c83de4 Add client side support for FD passing
Extend the RPC client code to allow file descriptors to be sent
to the server with calls, and received back with replies.

* src/remote/remote_driver.c: Stub extra args
* src/libvirt_private.syms, src/rpc/virnetclient.c,
  src/rpc/virnetclient.h, src/rpc/virnetclientprogram.c,
  src/rpc/virnetclientprogram.h: Extend APIs to allow
  FD passing
2011-10-28 10:42:54 +01:00
Daniel P. Berrange
b0f996a6b1 Extend RPC protocol to allow FD passing
Define two new RPC message types VIR_NET_CALL_WITH_FDS and
VIR_NET_REPLY_WITH_FDS. These message types are equivalent
to VIR_NET_CALL and VIR_NET_REPLY, except that between the
message header, and payload there is a 32-bit integer field
specifying how many file descriptors have been passed.

The actual file descriptors are sent/recv'd out of band.

* src/rpc/virnetmessage.c, src/rpc/virnetmessage.h,
  src/libvirt_private.syms: Add support for handling
  passed file descriptors
* src/rpc/virnetprotocol.x: Extend protocol for FD
  passing
2011-10-28 10:27:15 +01:00
Daniel P. Berrange
018044c89f Add APIs for virNetSocket for sending/receiving file descriptors
Add APIs to the virNetSocket object, to allow file descriptors
to be sent/received over UNIX domain socket connections

* src/rpc/virnetsocket.c, src/rpc/virnetsocket.h,
  src/libvirt_private.syms: Add APIs for FD send/recv
2011-10-28 10:23:53 +01:00
Jiri Denemark
fef8127c5f Introduce virXMLSaveFile as a wrapper for virFileRewrite
Every time we write XML into a file we call virEmitXMLWarning to write a
warning that the file is automatically generated. virXMLSaveFile
simplifies this into a single step and makes rewriting existing XML file
safe by using virFileRewrite internally.
2011-10-27 20:13:06 +02:00
Jiri Denemark
559644ddd2 Introduce virFileRewrite for safe file rewrite
When saving config files we just overwrite old content of the file. In
case something fails during that process (e.g. disk gets full) we lose
both old and new content. This patch makes the process more robust by
writing the new content into a separate file and only if that succeeds
the original file is atomically replaced with the new one.
2011-10-27 20:11:24 +02:00
Michal Privoznik
a877575a88 util: Add virFileAccessibleAs to private symbols
Commit 458b7099b2 introduced this
function. However it was not added into libvirt_private.syms so
the compilation may not succeed on some hosts.
2011-10-25 11:38:13 +02:00
Michal Privoznik
baf2ff7e90 startupPolicy: Emit event on disk source dropping
If a disk source gets dropped because it is not accessible,
mgmt application might want to be informed about this. Therefore
we need to emit an event. The event presented in this patch
is however a bit superset of what written above. The reason is simple:
an intention to be easily expanded, e.g. on 'user ejected disk
in guest' events. Therefore, callback gets source string and disk alias
(which should be unique among a domain) and reason (an integer);
2011-10-25 09:27:10 +02:00
Michal Privoznik
e5a84d74a2 conf: Introduce optional startupPolicy attribute for cdrom and floppy
This attribute says what to do with cdrom (or floppy) if
the source is missing. It accepts:
- mandatory - fail if missing for any reason (the default)
- requisite - fail if missing on boot up, drop if missing on
              migrate/restore/revert
- optional  - drop if missing at any start attempt.

However, this patch introduces only XML part of this new
functionality.
2011-10-25 09:22:42 +02:00
Eric Blake
b1836a254e storage: make previous leak less likely to regress
Splitting into two functions allows the user to call the right
function, rather than having to remember that a *Free function is
an exception to the rule.

* src/conf/storage_conf.h (virStoragePoolSourceClear): New function.
* src/libvirt_private.syms (storage_conf.h): Export it.
* src/conf/storage_conf.c (virStoragePoolSourceFree): Split...
(virStoragePoolSourceClear): ...into new function.
(virStoragePoolDefFree, virStoragePoolDefParseSourceString):
Update callers.
* src/test/test_driver.c (testStorageFindPoolSources): Likewise.
* src/storage/storage_backend_fs.c
(virStorageBackendFileSystemNetFindPoolSourcesFunc)
(virStorageBackendFileSystemNetFindPoolSources): Likewise.
* src/storage/storage_backend_iscsi.c
(virStorageBackendISCSIFindPoolSources): Likewise.
* src/storage/storage_backend_logical.c
(virStorageBackendLogicalFindPoolSources): Likewise.
2011-10-24 19:42:49 -06:00
Eric Blake
9cba392768 snapshot: indent domain xml when nesting
<domainsnapshot> is the first public instance of <domain> being
used as a sub-element, although we have two other private uses
(runtime state, and migration cookie).  Although indentation has
no effect on XML parsing, using it makes the output more consistent.

This uses virBuffer auto-indentation to obtain the effect, for all
but the portions of <domain> that are not generated a line at a
time into the same virBuffer.  Further patches will clean up the
remaining problems.

* src/conf/domain_conf.h (virDomainDefFormatInternal): New prototype.
* src/conf/domain_conf.c (virDomainDefFormatInternal): Export.
(virDomainObjFormat, virDomainSnapshotDefFormat): Update callers.
* src/libvirt_private.syms (domain_conf.h): Add new export.
* src/qemu/qemu_migration.c (qemuMigrationCookieXMLFormat): Use
new function.
(qemuMigrationCookieXMLFormatStr): Update caller.
2011-10-20 16:02:16 -06:00
Eric Blake
fd9c052e6d virbuf: add auto-indentation support
Rather than having to adjust all callers in a chain to deal with
indentation, it is nicer to have virBuffer do auto-indentation.

* src/util/buf.h (_virBuffer): Increase size.
(virBufferAdjustIndent, virBufferGetIndent): New prototypes.
* src/libvirt_private.syms (buf.h): Export new functions.
* src/util/buf.c (virBufferAdjustIndent, virBufferGetIndent): New
functions.
(virBufferSetError, virBufferAdd, virBufferAddChar)
(virBufferVasprintf, virBufferStrcat, virBufferURIEncodeString):
Implement auto-indentation.
* tests/virbuftest.c (testBufAutoIndent): Test it.
(testBufInfiniteLoop): Don't rely on internals.
Idea by Daniel P. Berrange.
2011-10-20 16:02:16 -06:00
Xu He Jie
de12bee7eb compile: Add a missing function 'pciDeviceListFind' to libvirt_private.syms
compile error:
./src/.libs/libvirt_driver_qemu.a(libvirt_driver_qemu_la-qemu_hostdev.o): In function `qemuPrepareHostdevPCIDevices':
/home/soulxu/data/work-code/libvirt/src/qemu/qemu_hostdev.c:183: undefined reference to `pciDeviceListFind'
/home/soulxu/data/work-code/libvirt/src/qemu/qemu_hostdev.c:230: undefined reference to `pciDeviceListFind'
./src/.libs/libvirt_driver_qemu.a(libvirt_driver_qemu_la-qemu_hostdev.o): In function `qemuGetActivePciHostDeviceList':
/home/soulxu/data/work-code/libvirt/src/qemu/qemu_hostdev.c:102: undefined reference to `pciDeviceListFind'
./src/.libs/libvirt_driver_qemu.a(libvirt_driver_qemu_la-qemu_hostdev.o): In function `qemuDomainReAttachHostdevDevices':
/home/soulxu/data/work-code/libvirt/src/qemu/qemu_hostdev.c:370: undefined reference to `pciDeviceListFind'

Signed-off-by: Xu He Jie <xuhj@linux.vnet.ibm.com>
2011-10-18 22:04:06 +08:00
Osier Yang
24b8be890d qemu: Do not reattach PCI device used by other domain when shutdown
When failing on starting a domain, it tries to reattach all the PCI
devices defined in the domain conf, regardless of whether the devices
are still used by other domain. This will cause the devices to be deleted
from the list qemu_driver->activePciHostdevs, thus the devices will be
thought as usable even if it's not true. And following commands
nodedev-{reattach,reset} will be successful.

How to reproduce:
  1) Define two domains with same PCI device defined in the confs.
  2) # virsh start domain1
  3) # virsh start domain2
  4) # virsh nodedev-reattach $pci_device

You will see the device will be reattached to host successfully.
As pciDeviceReattach just check if the device is still used by
other domain via checking if the device is in list driver->activePciHostdevs,
however, the device is deleted from the list by step 2).

This patch is to prohibit the bug by:
  1) Prohibit a domain starting or device attachment right at
     preparation period (qemuPrepareHostdevPCIDevices) if the
     device is in list driver->activePciHostdevs, which means
     it's used by other domain.

  2) Introduces a new field for struct _pciDevice, (const char *used_by),
     it will be set as the domain name at preparation period,
     (qemuPrepareHostdevPCIDevices). Thus we can prohibit deleting
     the device from driver->activePciHostdevs if it's still used by
     other domain when stopping the domain process.

* src/pci.h (define two internal functions, pciDeviceSetUsedBy and
    pciDevceGetUsedBy)
* src/pci.c (new field "const char *used_by" for struct _pciDevice,
    implementations for the two new functions)
* src/libvirt_private.syms (Add the two new internal functions)
* src/qemu_hostdev.h (Modify the definition of functions
    qemuPrepareHostdevPCIDevices, and qemuDomainReAttachHostdevDevices)
* src/qemu_hostdev.c (Prohibit preparation and don't delete the
    device from activePciHostdevs list if it's still used by other domain)
* src/qemu_hotplug.c (Update function usage, as the definitions are
    changed)

Signed-off-by: Eric Blake <eblake@redhat.com>
2011-10-14 12:53:32 -06:00
Guido Günther
920487b36d Add virBufferEscapeShell
Escape strings so they're safe to pass to the shell. It's based on
virsh's cmdEcho.
2011-10-13 23:41:31 +02:00
Sage Weil
7f197559f2 buf: implement generic virBufferEscape
Implement a generic helper to escape a given set of characters with a
leading '\'.  Generalizes virBufferEscapeSexpr().

Signed-off-by: Sage Weil <sage@newdream.net>
2011-10-12 11:05:41 -06:00
Eric Blake
7ec6f7bd33 snapshot: framework for more efficient relation traversal
No one was using virDomainSnapshotHasChildren, but that was an
O(n) function.  Exposing and tracking a bit more metadata for each
snapshot will allow the same query to be made with an O(1) query
of the member field.  For single snapshot operations (create,
delete), callers can be trusted to maintain the metadata themselves,
but for reloading, we can't compute parents as we go since there
is no guarantee that parents were parsed before children, so we also
provide a function to refresh the relationships, and which can
be used to detect if the user has ignored our warnings and been
directly modifying files in /var/lib/libvirt/qemu/snapshot.  This
patch only adds metadata; later patches will actually use it.

This layout intentionally hardcodes the size of each snapshot struct,
by tracking sibling pointers, rather than having to deal with the
headache of yet more memory management by directly sticking a
dynamically sized child[] on each parent.

* src/conf/domain_conf.h (_virDomainSnapshotObj)
(_virDomainSnapshotObjList): Add members.
(virDomainSnapshotUpdateRelations, virDomainSnapshotDropParent):
New prototypes.
(virDomainSnapshotHasChildren): Delete.
* src/conf/domain_conf.c (virDomainSnapshotSetRelations)
(virDomainSnapshotUpdateRelations, virDomainSnapshotDropParent):
New functions.
(virDomainSnapshotHasChildren): Drop unused function.
* src/libvirt_private.syms (domain_conf): Update exports.
2011-10-11 17:08:43 -06:00
Eric Blake
83ad88b7bd build: fix mingw build without sasl
Detected by autogen.sh on a cross-mingw build:

Creating library file: .libs/libvirt.dll.a
Cannot export virNetSASLContextCheckIdentity: symbol not defined
Cannot export virNetSASLContextNewServer: symbol not defined
...

* src/libvirt_private.syms (virnetsaslcontext.h): Move symbols...
* src/libvirt_sasl.syms: ...to new file.
* src/Makefile.am (USED_SYM_FILES) [HAVE_SASL]: Use new file.
(EXTRA_DIST): Ship it.
2011-10-11 16:30:25 -06:00
Daniel P. Berrange
22af84dc52 Make libvirt.so include the RPC server code
To avoid static linking libvirtd to the RPC server code, which
then prevents sane introduction of DTrace probes, put it all
in the libvirt.so, and export it

* daemon/Makefile.am: Don't link to RPC libraries
* src/Makefile.am: Link all RPC libraries to libvirt.so
* src/libvirt_private.syms: Export all RPC functions
2011-10-11 11:11:52 +01:00
Eric Blake
5907403716 snapshot: implement snapshot children listing in qemu
Not too hard to wire up.  The trickiest part is realizing that
listing children of a snapshot cannot use SNAPSHOT_LIST_ROOTS,
and that we overloaded that bit to also mean SNAPSHOT_LIST_DESCENDANTS;
we use that bit to decide which iteration to use, but don't want
the existing counting/listing functions to see that bit.

* src/conf/domain_conf.h (virDomainSnapshotObjListNumFrom)
(virDomainSnapshotObjListGetNamesFrom): New prototypes.
* src/conf/domain_conf.c (virDomainSnapshotObjListNumFrom)
(virDomainSnapshotObjListGetNamesFrom): New functions.
* src/libvirt_private.syms (domain_conf.h): Export them.
* src/qemu/qemu_driver.c (qemuDomainSnapshotNumChildren)
(qemuDomainSnapshotListChildrenNames): New functions.
2011-10-10 17:31:06 -06:00
Laine Stump
c329db7180 qemu: make PCI multifunction support more manual
When support for was added for PCI multifunction cards (in commit
9f8baf, first included in libvirt 0.9.3), it was done by always
turning on the multifunction bit for all PCI devices. Since that time
it has been realized that this is not an ideal solution, and that the
multifunction bit must be selectively turned on. For example, see

  https://bugzilla.redhat.com/show_bug.cgi?id=728174

and the discussion before and after

  https://www.redhat.com/archives/libvir-list/2011-September/msg01036.html

This patch modifies multifunction support so that the multifunction=on
option is only added to the qemu commandline for a device if its PCI
<address> definition has the attribute "multifunction='on'", e.g.:

  <address type='pci' domain='0x0000' bus='0x00'
           slot='0x04' function='0x0' multifunction='on'/>

In practice, the multifunction bit should only be turned on if
function='0' AND other functions will be used in the same slot - it
usually isn't needed for functions 1-7 (although there are apparently
some exceptions, e.g. the Intel X53 according to the QEMU source
code), and should never be set if only function 0 will be used in the
slot. The test cases have been changed accordingly to illustrate.

With this patch in place, if a user attempts to assign multiple
functions in a slot without setting the multifunction bit for function
0, libvirt will issue an error when the domain is defined, and the
define operation will fail. In the future, we may decide to detect
this situation and automatically add multifunction=on to avoid the
error; even then it will still be useful to have a manual method of
turning on multifunction since, as stated above, there are some
devices that excpect it to be turned on for all functions in a slot.

A side effect of this patch is that attempts to use the same PCI
address for two different devices will now log an error (previously
this would cause the domain define operation to fail, but there would
be no log message generated). Because the function doing this log was
almost completely rewritten, I didn't think it worthwhile to make a
separate patch for that fix (the entire patch would immediately be
obsoleted).
2011-10-01 11:48:28 -04:00
Laine Stump
dc79852af8 qemu: add ability to set PCI device "rombar" on or off
This patch was made in response to:

  https://bugzilla.redhat.com/show_bug.cgi?id=738095

In short, qemu's default for the rombar setting (which makes the
firmware ROM of a PCI device visible/not on the guest) was previously
0 (not visible), but they recently changed the default to 1
(visible). Unfortunately, there are some PCI devices that fail in the
guest when rombar is 1, so the setting must be exposed in libvirt to
prevent a regression in behavior (it will still require explicitly
setting <rom bar='off'/> in the guest XML).

rombar is forced on/off by adding:

  <rom bar='on|off'/>

inside a <hostdev> element that defines a PCI device. It is currently
ignored for all other types of devices.

At the moment there is no clean method to determine whether or not the
rombar option is supported by QEMU - this patch uses the advice of a
QEMU developer to assume support for qemu-0.12+. There is currently a
patch in the works to put this information in the output of "qemu-kvm
-device pci-assign,?", but of course if we switch to keying off that,
we would lose support for setting rombar on all the versions of qemu
between 0.12 and whatever version gets that patch.
2011-09-27 11:23:28 -04:00
Jiri Denemark
d2d6776342 qemu: Introduce shutdown reason for paused state
Qemu sends STOP event as part of the shutdown process. Detect such STOP
event and consider shutdown to be reason of emitting such event. That's
the best we can do until qemu provides us the reason directly in STOP
event. This allows us to report shutdown reason for paused state so that
apps can detect domains that failed to finish the shutdown process
(e.g., because qemu is buggy and doesn't exit on SIGTERM or it is
blocked in flushing disk buffers).
2011-09-16 17:25:55 +02:00