Commit Graph

1000 Commits

Author SHA1 Message Date
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
Eric Blake
19896423f7 hash: minor touchups
On RHEL5, I got:
util/virrandom.c:66: warning: nested extern declaration of '_gl_verify_function66' [-Wnested-externs]

The fix is to hoist the verify earlier.  Also some other hodge-podge
fixes I noticed while reviewing Dan's recent series.

* .gitignore: Ignore new test.
* src/util/cgroup.c: Bump copyright year.
* src/util/virhash.c: Fix typo in description.
* src/util/virrandom.c (virRandomBits): Mark doc comment, and
hoist assert to silence older gcc.
2012-01-26 15:27:10 -07:00
Michal Privoznik
8973190735 util: Include stdint.h because of uint32_t
Some files are using uint32_t or int64_t without including
stdint.h which defines them. Fix this.
2012-01-26 19:14:01 +01:00
Daniel P. Berrange
72b4139700 Replace hashing algorithm with murmurhash
Recent discussions have illustrated the potential for DOS attacks
with the hash table implementations used by most languages and
libraries.

   https://lwn.net/Articles/474912/

libvirt has an internal hash table impl, and uses hash tables for
a variety of purposes. The hash key generation code is pretty
simple and thus not strongly collision resistant.

This patch replaces the current libvirt hash key generator with
the (public domain) Murmurhash3 code. In addition every hash
table now gets a random seed value which is used to perturb the
hashing code. This should make it impossible to mount any
practical attack against libvirt hashing code.

* bootstrap.conf: Import bitrotate module
* src/Makefile.am: Add virhashcode.[ch]
* src/util/util.c: Make virRandom() return a fixed 32 bit
  integer value.
* src/util/hash.c, src/util/hash.h, src/util/cgroup.c: Replace
  hash code generation with a call to virHashCodeGen()
* src/util/virhashcode.h, src/util/virhashcode.c: Add a new
  virHashCodeGen() API using the Murmurhash3 algorithm.
2012-01-26 14:18:53 +00:00
Daniel P. Berrange
1d5c7a9fdf Rename hash.h and hash.c to virhash.h and virhash.c
In preparation for the patch to include Murmurhash3, which
introduces a virhashcode.h and virhashcode.c files, rename
the existing hash.h and hash.c to virhash.h and virhash.c
respectively.
2012-01-26 14:11:13 +00:00
Daniel P. Berrange
9f2bf8fd03 Convert various virHash functions to use size_t / uint32
In preparation for conversion over to use the Murmurhash3
algorithm, convert various virHash APIs to use size_t or
uint32 for their return values/parameters, instead of the
variable size 'unsigned long' or 'int' types
2012-01-26 14:09:21 +00: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
Marc-André Lureau
d553554b75 Cast pointer to int using intptr_t
Fix a few warnings with mingw64 x86_64.
2012-01-25 18:00:47 -07:00
Eric Blake
3d5c139c49 build: fix header order on mingw
In file included from ../gnulib/lib/unistd.h:51:0,
                 from ../src/util/util.h:30,
                 from rpc/virkeepalive.c:29:
/usr/x86_64-w64-mingw32/sys-root/mingw/include/winsock2.h:15:2: warning: #warning Please include winsock2.h before windows.h [-Wcpp]

Reported by Marc-André Lureau.

* src/util/threads-win32.h (includes): Pick up winsock2.h before
windows.h, as required by mingw64.
2012-01-25 15:05:45 -07:00
Marc-André Lureau
75d3612ef8 errcode is typedef by mingw, rename an argument name
Fixes the following warning:
util/virterror.c:1242:31: warning: declaration of 'errcode' shadows a global declaration [-Wshadow]
2012-01-25 14:49:24 -07:00
Marc-André Lureau
5f1767e845 Add missing virGetGroupName()
Add missing function if !HAVE_GETPWUID_R.
2012-01-25 12:27:11 -07: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
Laszlo Ersek
d19149dda8 virCommandProcessIO(): make poll() usage more robust
POLLIN and POLLHUP are not mutually exclusive. Currently the following
seems possible: the child writes 3K to its stdout or stderr pipe, and
immediately closes it. We get POLLIN|POLLHUP (I'm not sure that's possible
on Linux, but SUSv4 seems to allow it). We read 1K and throw away the
rest.

When poll() returns and we're about to check the /revents/ member in a
given array element, let's map all the revents bits to two (independent)
ideas: "let's attempt to read()", and "let's attempt to write()". This
should cover all errors, EOFs, and normal conditions; the read()/write()
call should report any pending error.

Under this approach, both POLLHUP and POLLERR are mapped to "needs read()"
if we're otherwise prepared for POLLIN. POLLERR also maps to "needs
write()" if we're otherwise prepared for POLLOUT. The rest of the mappings
(POLLPRI etc.) would be easy, but probably useless for pipes.

Additionally, SUSv4 doesn't appear to forbid POLLIN|POLLERR (or
POLLOUT|POLLERR) set simultaneously. One could argue that the read() or
write() call would return without blocking in these cases (with an error),
so POLLIN / POLLOUT would be justified beside POLLERR.

The code now penalizes POLLIN|POLLERR differently from plain POLLERR. The
former (ie. read() returning -1) is terminal and we jump to cleanup, while
plain POLLERR masks only the affected file descriptor for the future.
Let's unify those.

Signed-off-by: Laszlo Ersek <lersek@redhat.com>
2012-01-24 13:50:45 -07:00
Stefan Berger
da094fe201 Compare two hash tables for equality
Add function to compare two hash tables for equality.
2012-01-23 15:35:54 -05:00
Eric Blake
bb69630b6c maint: enforce use of _LAST marker
When converting a linear enum to a string, we have checks in
place in the VIR_ENUM_IMPL macro to ensure that there is one
string for every value, which lets us quickly flag if a user
added a value but forgot to add a counterpart string.  However,
this only works if we use the _LAST marker.

* cfg.mk (sc_require_enum_last_marker): New syntax check.
* src/conf/domain_conf.h (virDomainSnapshotState): Add new marker.
* src/conf/domain_conf.c (virDomainSnapshotState): Fix offender.
* src/qemu/qemu_monitor_json.c (qemuMonitorWatchdogAction)
(qemuMonitorIOErrorAction, qemuMonitorGraphicsAddressFamily):
Likewise.
* src/util/virtypedparam.c (virTypedParameter): Likewise.
2012-01-20 16:16:04 -07: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
Eric Blake
927cfaf467 threads: check for failure to set thread-local value
We had a memory leak on a very arcane OOM situation (unlikely to ever
hit in practice, but who knows if libvirt.so would ever be linked
into some other program that exhausts all thread-local storage keys?).
I found it by code inspection, while analyzing a valgrind report
generated by Alex Jia.

* src/util/threads.h (virThreadLocalSet): Alter signature.
* src/util/threads-pthread.c (virThreadHelper): Reduce allocation
lifetime.
(virThreadLocalSet): Detect failure.
* src/util/threads-win32.c (virThreadLocalSet): Likewise.
(virCondWait): Fix caller.
* src/util/virterror.c (virLastErrorObject): Likewise.
2012-01-19 13:14:10 -07: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
Osier Yang
6be610bfaa qemu: Introduce inactive PCI device list
pciTrySecondaryBusReset checks if there is active device on the
same bus, however, qemu driver doesn't maintain an effective
list for the inactive devices, and it passes meaningless argument
for parameter "inactiveDevs". e.g. (qemuPrepareHostdevPCIDevices)

if (!(pcidevs = qemuGetPciHostDeviceList(hostdevs, nhostdevs)))
    return -1;

..skipped...

if (pciResetDevice(dev, driver->activePciHostdevs, pcidevs) < 0)
    goto reattachdevs;

NB, the "pcidevs" used above are extracted from domain def, and
thus one won't be able to attach a device of which bus has other
device even detached from host (nodedev-detach). To see more
details of the problem:

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

This patch is to resolve the problem by introducing an inactive
PCI device list (just like qemu_driver->activePciHostdevs), and
the whole logic is:

  * Add the device to inactive list during nodedev-dettach
  * Remove the device from inactive list during nodedev-reattach
  * Remove the device from inactive list during attach-device
    (for non-managed device)
  * Add the device to inactive list after detach-device, only
    if the device is not managed

With the above, we have a sufficient inactive PCI device list, and thus
we can use it for pciResetDevice. e.g.(qemuPrepareHostdevPCIDevices)

if (pciResetDevice(dev, driver->activePciHostdevs,
                   driver->inactivePciHostdevs) < 0)
    goto reattachdevs;
2012-01-17 17:05:32 -07:00
Eric Blake
0327ff0798 uuid: fix off-by-one
Detected by Coverity.  Although unlikely, if we are ever started
with stdin closed, we could reach a situation where we open a
uuid file but then fail to close it, making that file the new
stdin for the rest of the process.

* src/util/uuid.c (getDMISystemUUID): Allow for stdin.
2012-01-12 15:18:23 -07:00
Daniel P. Berrange
08272dc8b4 Rsync keymaps.csv file with GTK-VNC 2012-01-12 20:44:55 +00:00
Shradha Shah
3a0c717b9e Added Function virNetDevGetVirtualFunctions
This functions enables us to get the Virtual Functions attached to
a Physical function given the name of a SR-IOV physical functio.

In order to accomplish the task, added a getter function pciGetDeviceAddrString
to get the BDF of the Virtual Function in a char array.
2012-01-11 13:01:16 -07:00
Shradha Shah
f19338c66c Added function pciSysfsFile to enable access to the PCI SYSFS files. 2012-01-11 13:01:16 -07:00
Eric Blake
03ea567327 build: fix mingw virCommand build
Commit db371a2 mistakenly added new functions inside a #ifndef WIN32
guard, even though they are needed on all platforms.

* src/util/command.c (virCommandFDSet): Move outside WIN32
conditional.
2012-01-06 17:34:05 -07:00
Michal Privoznik
db371a217d command: Discard FD_SETSIZE limit for opened files
Currently, virCommand implementation uses FD_ macros from
sys/select.h. However, those cannot handle more opened files
than FD_SETSIZE. Therefore switch to generalized implementation
based on array of integers.
2012-01-05 09:50:07 +01:00
Michal Privoznik
06b9c5b923 virCommand: Properly handle POLLHUP
It is a good practise to set revents to zero before doing any poll().
Moreover, we should check if event we waited for really occurred or
if any of fds we were polling on didn't encountered hangup.
2012-01-04 10:40:23 +01:00
Yuri Chornoivan
524ba58bb9 Fix typos in messages.
https://bugzilla.redhat.com/show_bug.cgi?id=770954
2012-01-03 20:30:33 -07: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
Peter Krempa
8fb2aeb662 migration: Add more specific error code/message on migration abort
A generic error code was returned, if the user aborted a migration job.
This made it hard to distinguish between a user requested abort and an
error that might have occured. This patch introduces a new error code,
which is returned in the specific case of a user abort, while leaving
all other failures with their existing code. This makes it easier to
distinguish between failure while mirgrating and an user requested
abort.

 * include/libvirt/virterror.h: - add new error code
 * src/util/virterror.c: - add message for the new error code
 * src/qemu/qemu_migration.h: - Emit operation aborted error instead of
                                operation failed, on migration abort
2011-12-16 16:38:26 +01:00
Michal Privoznik
a7adac3730 threadpool: Use while loop on virCondWait
instead of simple 'if' statement as virCondWait can return
even if associated condition was not signaled.
2011-12-09 19:33:11 +01:00
Michal Privoznik
6c811ed486 threads: Document spurious wakeups on virCondWait 2011-12-09 19:33:11 +01:00
Michal Privoznik
3b0bb65dd4 threadpool: Don't wait on condition if pool has no workers
Pool creates new workers dynamically. However, it is possible
for a pool to have no workers. If we want to free that pool,
we don't want to wait on quit condition as it will never be
signaled.
2011-12-09 15:25:46 +01:00
Jiri Denemark
2d5046d31f bridge: Fix forward delay APIs
Due to copy&paste error in c1df2c14b5,
virNetDevBridge[SG]etSTPDelay APIs were accessing wrong file.
2011-12-09 13:57:45 +01: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
Eric Blake
3a9ce767f1 maint: fix improper use of 'an'
https://bugzilla.redhat.com/show_bug.cgi?id=648855 mentioned a
misuse of 'an' where 'a' is proper; that has since been fixed,
but a search found other problems (some were a spelling error for
'and', while most were fixed by 'a').

* daemon/stream.c: Fix grammar.
* src/conf/domain_conf.c: Likewise.
* src/conf/domain_event.c: Likewise.
* src/esx/esx_driver.c: Likewise.
* src/esx/esx_vi.c: Likewise.
* src/rpc/virnetclient.c: Likewise.
* src/rpc/virnetserverprogram.c: Likewise.
* src/storage/storage_backend_fs.c: Likewise.
* src/util/conf.c: Likewise.
* src/util/dnsmasq.c: Likewise.
* src/util/iptables.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* src/xen/xend_internal.c: Likewise.
* src/xen/xs_internal.c: Likewise.
* tools/virsh.c: Likewise.
2011-12-03 17:11:56 -07:00
Eric Blake
2b045d39df command: handle empty buffer argument correctly
virBufferContentAndReset (intentionally) returns NULL for a buffer
with no content, but it is feasible to invoke a command with an
explicit empty string.

* src/util/command.c (virCommandAddEnvBuffer): Reject empty string.
(virCommandAddArgBuffer): Allow explicit empty argument.
* tests/commandtest.c (test9): Test it.
* tests/commanddata/test9.log: Adjust.
2011-12-03 15:55:46 -07:00
Eric Blake
c74a2a03f0 build: fix build on Cygwin
The RPC fixups needed on Linux are also needed on cygwin, and
worked without further tweaking to the list of fixups.  Also,
unlike BSD, Cygwin exports 'struct ifreq', but unlike Linux,
Cygwin lacks the ioctls that we were using 'struct ifreq' to
access.  This patch allows compilation under cygwin.

* src/rpc/genprotocol.pl: Also perform fixups on cygwin.
* src/util/virnetdev.c (HAVE_STRUCT_IFREQ): Also require AF_PACKET
definition.
* src/util/virnetdevbridge.c (virNetDevSetupControlFull): Only
compile if SIOCBRADDBR works.
2011-12-03 13:03:44 -07:00
Eric Blake
a699793449 maint: typo fixes
Many of these were mentioned by Yuri Chornoivan in:
https://bugzilla.redhat.com/show_bug.cgi?id=669506

* src/esx/esx_vi.c (esxVI_WaitForTaskCompletion): Fix spelling.
* src/conf/netdev_vport_profile_conf.c
(virNetDevVPortProfileParse): Likewise.
* src/xen/xend_internal.c (xenDaemonDomainSetVcpusFlags):
Likewise.
* src/xen/xm_internal.c (xenXMDomainSetVcpusFlags): Likewise.
* src/esx/esx_util.c (esxUtil_ResolveHostname): Likewise.
* src/storage/storage_backend_fs.c
(virStorageBackendFileSystemBuild): Likewise.
* daemon/libvirtd.conf: Likewise.
* src/util/logging.c (virLogMessage): Likewise.
* src/uml/uml_conf.c (umlBuildCommandLineNet): Likewise.
* src/vmx/vmx.c (virVMXFormatEthernet): Likewise.
2011-12-01 16:08:34 -07:00
Daniel P. Berrange
949e10911a Fix build for platforms lacking struct ifreq
This ought to fix the build if you have net/if.h but do
not have struct ifreq

* configure.ac: Check for struct ifreq in net/if.h
* src/util/virnetdev.c: Conditionalize to avoid use of
  struct ifreq if it does not exist
2011-12-01 11:01:49 -07:00
Daniel P. Berrange
b0ed12276e Don't use undocumented __isleap macro
The glibc time.h header has an undocumented __isleap macro
that we are using. Since it is undocumented & does not appear
on any other OS, stop using it and just define the macro in
libvirt code instead.

* src/util/virtime.c: Remove __isleap usage
2011-12-01 13:28:44 +00:00
Alex Jia
4c8327994c util: Plug memory leak on virNetDevMacVLanCreateWithVPortProfile() error path
Detected by Coverity. Leak introduced in commit 90074ec.

Signed-off-by: Alex Jia <ajia@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-11-30 16:57:08 -07:00
Alex Jia
5483e5736d util: Plug memory leak on virNetDevBridgeGet() sucessful path
Detected by Coverity. Leak introduced in commit c1df2c1.

Two bugs here:
1. memory leak on successful parse
2. failure to parse still returned success

Signed-off-by: Alex Jia <ajia@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-11-30 16:47:03 -07: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
32d3ec7466 Make logging async signal safe wrt time stamp generation
Use the new virTimeStringNowRaw() API for generating log timestamps
in an async signal safe manner

* src/util/logging.c: Use virTimeStringNowRaw
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
a82ed6a0c3 Don't mark suspend as active until we know it is running
If suspend failed for some reason (e.g. too short duration) then
subsequent attempts to trigger suspend were rejected because we
had already marked a suspend as being in progress

* src/util/virnodesuspend.c: Don't mark suspend as active
  until we've successfully triggered it
2011-11-30 10:12:30 +00:00
Daniel P. Berrange
8c60bc169f Remove pointless strdup in node suspend code
The command name for the suspend action does not need to be
strdup'd. The constant string can be used directly. This
also means the code can be trivially rearranged to make the
switch clearer

* src/util/virnodesuspend.c: Remove strdup of cmdString
2011-11-30 10:12:30 +00:00
Daniel P. Berrange
2fc056c1ba Do lazy init of host PM features
To avoid probing the host power management features on any
call to virInitialize, only initialize the mutex in
virNodeSuspendInit. Do lazy load of the supported PM target
mask when it is actually needed

* src/util/virnodesuspend.c: Lazy init of supported features
2011-11-30 10:12:30 +00:00
Daniel P. Berrange
f1f28611f1 Remove powerMgmt_valid field from capabilities struct
If we ensure that virNodeSuspendGetTargetMask always resets
*bitmask to zero upon failure, there is no need for the
powerMgmt_valid field.

* src/util/virnodesuspend.c: Ensure *bitmask is zero upon
  failure
* src/conf/capabilities.c, src/conf/capabilities.h: Remove
  powerMgmt_valid field
* src/qemu/qemu_capabilities.c: Remove powerMgmt_valid
2011-11-30 10:12:30 +00:00
Daniel P. Berrange
c92653f4dd Move suspend capabilities APIs out of util.h into virnodesuspend.c
The node suspend capabilities APIs should not have been put into
util.[ch]. Instead move them into virnodesuspend.[ch]

* src/util/util.c, src/util/util.h: Remove suspend capabilities APIs
* src/util/virnodesuspend.c, src/util/virnodesuspend.h: Add
  suspend capabilities APIs
* src/qemu/qemu_capabilities.c: Include virnodesuspend.h
2011-11-30 10:12:29 +00:00
Daniel P. Berrange
53c2aad88b Rename suspend capabilities APIs
Rename virGetPMCapabilities to virNodeSuspendGetTargetMask and
virDiscoverHostPMFeature to virNodeSuspendSupportsTarget.

* src/util/util.c, src/util/util.h: Rename APIs
* src/qemu/qemu_capabilities.c, src/util/virnodesuspend.c: Adjust
  for new names
2011-11-30 10:12:29 +00:00
Daniel P. Berrange
33386276a9 Sanitize virDiscoverHostPMFeature to return a boolean
Since virDiscoverHostPMFeature is just checking one feature,
there is no reason for it to return a bitmask. Change it to
return a boolean

* src/util/util.c, src/util/util.h: Make virDiscoverHostPMFeature
  return a boolean
2011-11-30 10:12:29 +00:00
Daniel P. Berrange
6ea25cd975 Move the virHostPMCapability enum helpers into capabilities.c
The virHostPMCapability enum helper was declared in util.h
but implemented in capabilities.c, which is in a completely
separate library at link time. Move the declaration into the
capabilities.c file and rename it to match normal conventions

* src/util/util.h: Remove virHostPMCapability enum decl
* src/conf/capabilities.c: Add virCapsHostPMTarget enum
2011-11-30 10:12:29 +00:00
Daniel P. Berrange
6fb5400fc6 Remove internal only virHostPMCapability enum
The internal virHostPMCapability enum just duplicates the
public virNodeSuspendTarget enum, but with different names.

* src/util/util.c: Use VIR_NODE_SUSPEND_TARGET constants
* src/util/util.h: Remove virHostPMCapability enum
* src/conf/capabilities.c: Use VIR_NODE_SUSPEND_TARGET_LAST
2011-11-30 10:12:29 +00:00
Daniel P. Berrange
866b0a7069 Fix values of PM target type constants
The VIR_NODE_SUSPEND_TARGET constants are not flags, so they
should just be assigned straightforward incrementing values.

* include/libvirt/libvirt.h.in: Change VIR_NODE_SUSPEND_TARGET
  values
* src/util/virnodesuspend.c: Fix suspend target checks
2011-11-30 10:12:29 +00:00
Alex Jia
a001a5e28b util: avoid null deref on qcowXGetBackingStore
Detected by Coverity. the only case is caller passes a NULL to 'format' variable,
then taking 'if (format)' false branch, the function qcow2GetBackingStoreFormat
will directly dereferences the NULL 'format' pointer variable.

Signed-off-by: Alex Jia <ajia@redhat.com>
2011-11-30 11:05:13 +01: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
Michal Privoznik
dee901c1ff bandwidth: Fix funky identation 2011-11-29 14:26:14 +01:00
Jiri Denemark
54bf875aa6 lxc: Fix suspend/resume with freezer cgroup 2011-11-29 14:16:42 +01: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
Srivatsa S. Bhat
302743f177 Add 'Hybrid-Suspend' power management discovery for the host
Some systems support a feature known as 'Hybrid-Suspend', apart from the
usual system-wide sleep states such as Suspend-to-RAM (S3) or Suspend-to-Disk
(S4). Add the functionality to discover this power management feature and
export it in the capabilities XML under the <power_management> tag.
2011-11-29 17:29:16 +08:00
Paolo Bonzini
a1b62f983b util: fix thinko in runIO
When aligning you need to clear the bits in the mask and leave the
others aside.  Likely this code has never run, and will never run.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2011-11-25 05:37:39 -07:00
Jiri Denemark
8d6e3edd0e Introduce virConnectSetKeepAlive
virConnectSetKeepAlive public API can be used by a client connecting to
remote server to start using keepalive protocol. The API is handled
directly by remote driver and not transmitted over the wire to the
server.
2011-11-24 11:44:08 +01:00
Daniel P. Berrange
aad764e107 Fix disabling of virtual port profile code on old hosts
The WITH_VIRTUALPORT macro is defined to 0 when disabled, not
left undefined. So #if must be used instead of #ifdef

* src/util/virnetdevvportprofile.c: s/#ifdef/#if/
2011-11-23 12:29:37 +00: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
Jim Fehlig
a495365d09 Don't copy sexpr node value that is an empty string
Xen4.1 initializes some unspecified sexpr config items to an empty
string, unlike previous Xen versions that would leave the item unset.
E.g. the kernel item for an HVM guest (non-direct kernel boot):

Xen4.0 and earlier
  ...
  (image
    (hvm
      (kernel )
  ...

Xen4.1
  ...
  (image
    (hvm
      (kernel '')
  ...

The empty string for kernel causes some grief in subsequent parsing
where existence of specified kernel is checked, e.g.

  if (!def->os.kernel)
  ...

This patch solves the problem in sexpr_node_copy() by not copying
a node containing an empty string.
2011-11-18 16:00:31 -07:00
Eric Blake
f14b4cb5a0 build: fix compile error with no macvtap
Since commit 6ec8288a, compilation has failed on RHEL 5:

util/virnetdevmacvlan.c:672: error: conflicting types for 'virNetDevMacVLanCreateWithVPortProfile'

* src/util/virnetdevmacvlan.c
(virNetDevMacVLanCreateWithVPortProfile): Add missing parameter.
2011-11-18 14:58:11 -07: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
6ec8288a96 Allow creation of plain macvlan devices
Update virNetDevMacVLanCreateWithVPortProfile to allow creation
of plain macvlan devices, as well as macvtap devices. The former
is useful for LXC containers

* src/qemu/qemu_command.c: Explicitly request a macvtap device
* src/util/virnetdevmacvlan.c, src/util/virnetdevmacvlan.h: Add
  new flag to allow switching between macvlan and macvtap
  creation
2011-11-18 16:10:37 +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
74b32b6297 Move functions for dealing with physical/virtual devices
Move virNetDevIsVirtualFunction, virNetDevGetVirtualFunctionIndex
and virNetDevGetPhysicalFunction to virnetdev.c

* src/util/interface.c, src/util/interface.h, src/util/virnetdev.c,
  src/util/virnetdev.h: Move APIs
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
5373cb74bd Move virNetDevValidateConfig to virnetdev.c
* src/util/interface.c, src/util/interface.h: Remove virNetDevValidateConfig
* src/util/virnetdev.c, src/util/virnetdev.h: Add virNetDevValidateConfig
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
8e6cd41418 Move virNetDevGetIPv4Address to virnetdev.c
Move the virNetDevGetIPv4Address function to virnetdev.c

* util/interface.c, util/interface.h: Remove virNetDevGetIPv4Address
* util/virnetdev.c, util/virnetdev.h: Add virNetDevGetIPv4Address
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
00bba08d24 Move virNetDevGetIndex & virNetDevGetVLanID to virnetdev.c
Move virNetDevGetIndex & virNetDevGetVLanID to virnetdev.c to
suit their functional purpose

* util/interface.c, util/interface.h: Remove virNetDevGetIndex &
  virNetDevGetVLanID
* util/virnetdev.c, util/virnetdev.h: Add virNetDevGetIndex &
  virNetDevGetVLanID
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
255917f516 Move MAC address replacement functions to virnetdev.c
Move virNetDevReplaceMacAddress and virNetDevRestoreMacAddress
to the virnetdev.c file where they naturally belong

* util/interface.c, util/interface.h: Remove
  virNetDevReplaceMacAddress and virNetDevRestoreMacAddress
* util/virnetdev.c, util/virnetdev.h: Add
  virNetDevReplaceMacAddress and virNetDevRestoreMacAddress
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
d2fed854c0 Move the low level macvlan creation APIs
Move the low level macvlan creation APIs into the
virnetdevmacvlan.c file where they more naturally
belong

* util/interface.c, util/interface.h: Remove virNetDevMacVLanCreate
  and virNetDevMacVLanDelete
* util/virnetdevmacvlan.c, util/virnetdevmacvlan.h: Add
  virNetDevMacVLanCreate and virNetDevMacVLanDelete
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
191090ae27 Rename high level macvlan creation APIs
Rename virNetDevMacVLanCreate to virNetDevMacVLanCreateWithVPortProfile
and virNetDevMacVLanDelete to virNetDevMacVLanDeleteWithVPortProfile

To make way for renaming the other macvlan creation APIs in
interface.c

* util/virnetdevmacvlan.c, util/virnetdevmacvlan.h,
  qemu/qemu_command.c, qemu/qemu_hotplug.c, qemu/qemu_process.c:
  Rename APIs
2011-11-18 16:10:02 +00:00
Daniel P. Berrange
896104c9f0 Rename and split the macvtap.c file
Rename the macvtap.c file to virnetdevmacvlan.c to reflect its
functionality. Move the port profile association code out into
virnetdevvportprofile.c. Make the APIs available unconditionally
to callers

* src/util/macvtap.h: rename to src/util/virnetdevmacvlan.h,
* src/util/macvtap.c: rename to src/util/virnetdevmacvlan.c
* src/util/virnetdevvportprofile.c, src/util/virnetdevvportprofile.h:
  Pull in vport association code
* src/Makefile.am, src/conf/domain_conf.h, src/qemu/qemu_conf.c,
  src/qemu/qemu_conf.h, src/qemu/qemu_driver.c: Update include
  paths & remove conditional compilation
2011-11-18 16:10:01 +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
Stefan Berger
39d91e9f88 Fix strchr call triggering gcc 4.3 & 4.4 bug
Replacing the strchr call with two variables through a strstr call.
Calling strchr with two variables triggers a gcc 4.3/4.4
bug when used in combination with -Wlogical-op and at least -O1.
2011-11-15 15:00:10 -05:00
Stefan Berger
c2cc02ea98 maint: fix build
include stdint.h to fix the build
2011-11-15 14:58:38 -05: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
428cffb1e7 Move LXC veth.c code into shared utility APIs
Move the virNetDevSetName and virNetDevSetNamespace APIs out
of LXC's veth.c and into virnetdev.c.

Move the remaining content of the file to src/util/virnetdevveth.c

* src/lxc/veth.c: Rename to src/util/virnetdevveth.c
* src/lxc/veth.h: Rename to src/util/virnetdevveth.h
* src/util/virnetdev.c, src/util/virnetdev.h: Add
  virNetDevSetName and virNetDevSetNamespace
* src/lxc/lxc_container.c, src/lxc/lxc_controller.c,
  src/lxc/lxc_driver.c: Update include paths
2011-11-15 10:28:02 +00:00
Daniel P. Berrange
d3406045fd Split src/util/network.{c,h} into 5 pieces
The src/util/network.c file is a dumping ground for many different
APIs. Split it up into 5 pieces, along functional lines

 - src/util/virnetdevbandwidth.c: virNetDevBandwidth type & helper APIs
 - src/util/virnetdevvportprofile.c: virNetDevVPortProfile type & helper APIs
 - src/util/virsocketaddr.c: virSocketAddr and APIs
 - src/conf/netdev_bandwidth_conf.c: XML parsing / formatting
   for virNetDevBandwidth
 - src/conf/netdev_vport_profile_conf.c: XML parsing / formatting
   for virNetDevVPortProfile

* src/util/network.c, src/util/network.h: Split into 5 pieces
* src/conf/netdev_bandwidth_conf.c, src/conf/netdev_bandwidth_conf.h,
  src/conf/netdev_vport_profile_conf.c, src/conf/netdev_vport_profile_conf.h,
  src/util/virnetdevbandwidth.c, src/util/virnetdevbandwidth.h,
  src/util/virnetdevvportprofile.c, src/util/virnetdevvportprofile.h,
  src/util/virsocketaddr.c, src/util/virsocketaddr.h: New pieces
* daemon/libvirtd.h, daemon/remote.c, src/conf/domain_conf.c,
  src/conf/domain_conf.h, src/conf/network_conf.c,
  src/conf/network_conf.h, src/conf/nwfilter_conf.h,
  src/esx/esx_util.h, src/network/bridge_driver.c,
  src/qemu/qemu_conf.c, src/rpc/virnetsocket.c,
  src/rpc/virnetsocket.h, src/util/dnsmasq.h, src/util/interface.h,
  src/util/iptables.h, src/util/macvtap.c, src/util/macvtap.h,
  src/util/virnetdev.h, src/util/virnetdevtap.c,
  tools/virsh.c: Update include files
2011-11-15 10:27:54 +00:00
Daniel P. Berrange
df64f4807e Fix error reporting in port profile parsing/formatting APIs
The virtual port profile parsing/formatting APIs do not
correctly handle unknown profile type strings/numbers.
They behave as a no-op, instead of raising an error

* src/util/network.c, src/util/network.h: Fix error
  handling of port profile APIs
* src/conf/domain_conf.c, src/conf/network_conf.c: Update
  for API changes
2011-11-15 10:19:43 +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
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
Daniel P. Berrange
e49c9bf25c Split bridge.h into three separate files
Following the renaming of the bridge management APIs, we can now
split the source file into 3 corresponding pieces

 * src/util/virnetdev.c: APIs for any type of network interface
 * src/util/virnetdevbridge.c: APIs for bridge interfaces
 * src/util/virnetdevtap.c: APIs for TAP interfaces

* src/util/virnetdev.c, src/util/virnetdev.h,
  src/util/virnetdevbridge.c, src/util/virnetdevbridge.h,
  src/util/virnetdevtap.c, src/util/virnetdevtap.h: Copied
  from bridge.{c,h}
* src/util/bridge.c, src/util/bridge.h: Split into 3 pieces
* src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/openvz/openvz_driver.c, src/qemu/qemu_command.c,
  src/qemu/qemu_conf.h, src/uml/uml_conf.c, src/uml/uml_conf.h,
  src/uml/uml_driver.c: Update #include directives
2011-11-09 16:34:25 +00:00
Daniel P. Berrange
c1df2c14b5 Remove usage of brctl command line tool
Convert the virNetDevBridgeSetSTP and virNetDevBridgeSetSTPDelay
to use ioctls instead of spawning brctl.

Implement the virNetDevBridgeGetSTP and virNetDevBridgeGetSTPDelay
methods which were declared in the header but never existed

* src/util/bridge.c: Convert to use bridge ioctls instead of brctl
2011-11-09 16:33:53 +00:00
Daniel P. Berrange
ccc243470d Add an API for retrieving the MAC address of an interface
* src/util/bridge.c, src/util/bridge.h: Add virNetDevGetMAC
2011-11-09 16:33:44 +00:00
Daniel P. Berrange
dfb454cebc Expose MTU management APIs
The MTU management APIs are useful to other code inside libvirt,
so should be exposed as non-static APIs.

* src/util/bridge.c, src/util/bridge.h: Expose virNetDevSetMTU,
  virNetDevSetMTUFromDevice & virNetDevGetMTU
2011-11-09 16:33:39 +00:00
Daniel P. Berrange
d8a62d9552 Turn two int parameters into bools in bridge APIs
* src/util/bridge.c, src/util/bridge.h: s/int/bool/ in
  virNetDevSetOnline and virNetDevBridgeSetSTP
2011-11-09 16:33:34 +00:00
Daniel P. Berrange
dced27c89e Rename all brXXXX APIs to follow new convention
The existing brXXX APIs in src/util/bridge.h are renamed to
follow one of three different conventions

 - virNetDevXXX       - operations for any type of interface
 - virNetDevBridgeXXX - operations for bridge interfaces
 - virNetDevTapXXX    - operations for tap interfaces

* src/util/bridge.h, src/util/bridge.c: Rename all APIs
* src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/qemu/qemu_command.c, src/uml/uml_conf.c,
  src/uml/uml_driver.c: Update for API renaming
2011-11-09 16:33:28 +00:00
Daniel P. Berrange
4f4fd8f7ad Make all brXXX APIs raise errors, instead of returning errnos
Currently every caller of the brXXX APIs has to store the returned
errno value and then raise an error message. This results in
inconsistent error messages across drivers, additional burden on
the callers and makes the error reporting inaccurate since it is
hard to distinguish different scenarios from 1 errno value.

* src/util/bridge.c: Raise errors instead of returning errnos
* src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/qemu/qemu_command.c, src/uml/uml_conf.c,
  src/uml/uml_driver.c: Remove error reporting code
2011-11-09 16:33:19 +00:00
Daniel P. Berrange
6cfeb9a766 Remove 'brControl' object
The bridge management APIs in src/util/bridge.c require a brControl
object to be passed around. This holds the file descriptor for the
control socket. This extra object complicates use of the API for
only a minor efficiency gain, which is in turn entirely offset by
the need to fork/exec the brctl command for STP configuration.

This patch removes the 'brControl' object entirely, instead opening
the control socket & closing it again within the scope of each method.

The parameter names for the APIs are also made to consistently use
'brname' for bridge device name, and 'ifname' for an interface
device name. Finally annotations are added for non-NULL parameters
and return check validation

* src/util/bridge.c, src/util/bridge.h: Remove brControl object
  and update API parameter names & annotations.
* src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/uml/uml_conf.h, src/uml/uml_conf.c, src/uml/uml_driver.c,
  src/qemu/qemu_command.c, src/qemu/qemu_conf.h,
  src/qemu/qemu_driver.c: Remove reference to 'brControl' object
2011-11-09 16:33:14 +00:00
Eric Blake
f7bd00c12c build: fix build on platforms without ptsname_r
MacOS lacks ptsname_r, and gnulib doesn't (yet) provide it.
But we can avoid it altogether, by using gnulib openpty()
instead.  Note that we do _not_ want the pt_chown module;
gnulib uses it only to implement a replacement openpty() if
the system lacks both openpty() and granpt(), but all
systems that we currently port to either have at least one of
openpty() and/or grantpt(), or lack ptys altogether.  That is,
we aren't porting to any system that requires us to deal with
the hassle of installing a setuid pt_chown helper just to use
gnulib's ability to provide openpty() on obscure platforms.

* .gnulib: Update to latest, for openpty fixes
* bootstrap.conf (gnulib_modules): Add openpty, ttyname_r.
(gnulib_tool_option_extras): Exclude pt_chown module.
* src/util/util.c (virFileOpenTty): Rewrite in terms of openpty
and ttyname_r.
* src/util/util.h (virFileOpenTtyAt): Delete dead prototype.
2011-11-07 09:34:02 -07:00
Eric Blake
4d970fd293 build: silence compiler warning on BSD
Building on 64-bit FreeBSD 8.2 complained about a cast between
a pointer and a smaller integer.  Going through an intermediate
cast shuts up the compiler.

* src/util/threads-pthread.c (virThreadSelfID): Silence a warning.
2011-11-04 16:43:37 -06:00
Daniel P. Berrange
26b7430773 Fix off-by-one printing month in logging code
The field 'mon' in 'struct tm' gives months 0-11, where as
humans tend to expect months 1-12. Thus the month number
needing adjusting by 1

* src/util/logging.c: Use human friendly month number
2011-11-02 14:55:35 +00:00
Wen Congyang
7ab1c25cc5 fix crash when starting network
commit 27908453 introduces a regression, and it will
cause libvirt crashed when starting network.

The reason is that tapfd may be NULL, but we dereference
it without checking whether it is NULL.
2011-11-02 22:21:59 +08: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
Roopa Prabhu
228a9ec312 macvtap: Fix error return value convention/inconsistencies
- changed some return 1's to return -1
- changed if (rc) error checks to if (rc < 0)
- fixed some other minor convention violations

I might have missed some. Can fix in another patch or can respin

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
Reported-by: Eric Blake <eblake@redhat.com>
Reported-by: Laine Stump <laine@laine.org>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-10-28 16:47:28 -06:00
Ryota Ozaki
884b98add5 util: Fix virUUIDGeneratePseudoRandomBytes
It forgets to move a pointer to a buffer for UUID and as a result
fills only the first byte of the buffer.
2011-10-28 08:54:34 -06:00
Tyler Coumbes
279084537f bridge: modify for use when sVirt is enabled with qemu
This refactors the TAP creation code out of brAddTap into a new
function brCreateTap to allow it to be used on its own. I have also
changed ifSetInterfaceMac to brSetInterfaceMac and exported it since
it is will be needed by code outside of util/bridge.c in the next
patch.

 AUTHORS                 |    1 +
 src/libvirt_bridge.syms |    2 +
 src/util/bridge.c       |  116 +++++++++++++++++++++++++++++++----------------
 src/util/bridge.h       |    9 ++++
 4 files changed, 89 insertions(+), 39 deletions(-)
2011-10-27 20:28:39 -06: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
Daniel P. Berrange
838d8c1b6b Fix typo in virFileAccessibleAs
* src/util/util.c: s/git_t/gid_t/ in parameter list of virFileAccessibleAs
2011-10-27 09:25:02 +01:00
Michal Privoznik
458b7099b2 util: Create virFileAccessibleAs function
This function checks if a given path is accessible under
given uid and gid.
2011-10-25 09:27:02 +02:00
Eric Blake
e36da1bd8a snapshot: simplify indentation of network xml
More simplifications possible due to auto-indent.  Also,
<bandwidth> within <actual> was only using 6 instead of 8 spaces.

* src/util/network.h (virVirtualPortProfileFormat)
(virBandwidthDefFormat): Alter signature.
* src/util/network.c (virVirtualPortProfileFormat)
(virBandwidthDefFormat): Alter indentation.
(virBandwidthChildDefFormat): Tweak to make use easier.
* src/conf/network_conf.c (virPortGroupDefFormat)
(virNetworkDefFormat): Adjust callers.
* src/conf/domain_conf.c (virDomainNetDefFormat): Likewise.
(virDomainActualNetDefFormat): Likewise, and fix bandwidth
indentation.
2011-10-20 17:04:47 -06:00
Eric Blake
9a220665e7 snapshot: simplify indentation of sysinfo
The improvements to virBuffer, along with a paradigm shift to pass
the original buffer through rather than creating a second buffer,
allow us to shave off quite a few lines of code.

* src/util/sysinfo.h (virSysinfoFormat): Alter signature.
* src/util/sysinfo.c (virSysinfoFormat, virSysinfoBIOSFormat)
(virSysinfoSystemFormat, virSysinfoProcessorFormat)
(virSysinfoMemoryFormat): Change indentation parameter.
* src/conf/domain_conf.c (virDomainSysinfoDefFormat): Adjust
caller.
* src/qemu/qemu_driver.c (qemuGetSysinfo): Likewise.
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
Eric Blake
818a966510 virbuf: more detailed error reporting
The next patch wants to add some sanity checking, which would
be a different error than ENOMEM.  Many existing callers blindly
report OOM failure if virBuf reports an error, and this will be
wrong in the (unlikely) case that they actually had a usage error
instead; but since the most common error really is ENOMEM, I'm
not going to fix all callers.  Meanwhile, new discriminating
callers can react differently depending on what failure happened.

* src/util/buf.c (virBufferSetError): Add parameter.
(virBufferGrow, virBufferVasprintf, virBufferEscapeString)
(virBufferEscapeSexpr, virBufferEscapeShell): Adjust callers.
2011-10-20 16:02:15 -06:00
Eric Blake
5c09b81be7 virbuf: fix const-correctness
Although the compiler wasn't complaining (since it was the pointer,
rather than what was being pointed to, that was actually const), it
looks quite suspicious to call a function with an argument labeled
const when the nature of the pointer (virBufferPtr) is hidden behind
a typedef.  Dropping const makes the function declarations easier
to read.

* src/util/buf.h: Drop const from all functions that modify buffer
argument.
* src/util/buf.c (virBufferSetError, virBufferAdd)
(virBufferContentAndReset, virBufferFreeAndReset)
(virBufferAsprintf, virBufferVasprintf, virBufferEscapeString)
(virBufferEscapeSexpr, virBufferEscape): Fix fallout.
2011-10-20 16:02:15 -06:00
Daniel P. Berrange
646b300773 Fix virFileOpenTty definition on Win32
Stub out a complete impl of virFileOpenTty to avoid unused
parameter warnings

* src/util/util.c: Fix virFileOpenTty on Win32
2011-10-20 10:03:29 +01:00
Serge E. Hallyn
80710c69fe lxc: use hand-rolled code in place of unlockpt and grantpt
The glibc ones (intentionally) cannot handle ptys opened in a
devpts not mounted at /dev/pts.

Drop the (un-exported, unused) virFileOpenTtyAt.

Signed-off-by: Serge Hallyn <serge.hallyn@canonical.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-10-19 14:47:16 -06:00
Daniel P. Berrange
c005e523b2 Replace virBufferAdd with virBufferAddLit for const string
The statement

        virBufferAdd(buf, "''", 2);

triggers a syntax-check warning

* src/util/buf.c: Replace virBufferAdd with virBufferAddLit
2011-10-19 09:45:09 +01:00
Daniel P. Berrange
777ffbd0e2 Allow for URI aliases when connecting to libvirt
This adds support for a libvirt client configuration file
either /etc/libvirt/libvirt.conf for privileged clients,
or $HOME/.libvirt/libvirt.conf for unprivileged clients.

It allows one parameter

 uri_aliases = [
   "hail=qemu+ssh://root@hail.cloud.example.com/system",
   "sleet=qemu+ssh://root@sleet.cloud.example.com/system",
 ]

Any call to virConnectOpen with a non-NULL URI will first
attempt to match against the uri_aliases list. An application
can disable this by using VIR_CONNECT_NO_ALIASES

* docs/uri.html.in: Document URI aliases
* include/libvirt/libvirt.h.in: Add VIR_CONNECT_NO_ALIASES
* libvirt.spec.in, mingw32-libvirt.spec.in: Add /etc/libvirt/libvirt.conf
* src/Makefile.am: Install default config file
* src/libvirt.c: Add support for URI aliases
* src/remote/remote_driver.c: Don't try to handle URIs
  with no scheme and which clearly are not paths
* src/util/conf.c: Don't raise error on virConfFree(NULL)
* src/xen/xen_driver.c: Don't raise error on URIs
  with no scheme
2011-10-19 09:14:34 +01:00
Guido Günther
04323fbcb4 virBufferEscapeShell: Emit quotes for the empty string
Make the empty string return '' to match cmdEcho's behavior.
2011-10-19 09:24:01 +02:00
Guido Günther
94f776e716 virBufferEscapeShell: Fix escaping of single quotes.
When checking if we need to escape a single quote we were looking at the
character after the quote instead of at the quote itself.
2011-10-18 17:03:36 +02:00
Roopa Prabhu
7c23c34d38 Add missing strdup return value check
Check strdup return value and fail if error

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
2011-10-14 17:18:37 -06:00
Roopa Prabhu
80b077ee5e macvtap: avoid invalid free
Commit 0472f39 plugged a leak, but introduced another bug:

Actually looks like physfndev is conditionally allocated in getPhysfnDev
Its better to modify getPhysfnDev to allocate physfndev every time.
2011-10-14 14:54:47 -06: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
Jiri Denemark
57d91fca64 util: Fix typo in virGetHostname description 2011-10-14 16:25:50 +02:00
Eric Blake
0472f39f8b macvtap: plug memory leak for 802.1Qbh
Detected by Coverity.  Leak present since commit ca3b22b.

* src/util/macvtap.c (doPortProfileOp8021Qbh): Release device name.
2011-10-13 16:45:58 -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
Jiri Denemark
f1409fa7c6 util: Make getaddrinfo failure nonfatal in virGetHostname
Setting a hostname that cannot be resolved is not the best configuration
but since virGetHostname only calls getaddrinfo to get host's canonical
name and we do not fail if the returned canonical name is NULL or
"localhost", there is no reason why we should fail if getaddrinfo itself
fails.
2011-10-13 22:05:35 +02:00
Eric Blake
430156cf32 build: add compiler attributes to virUUIDParse
Coverity complained that most, but not all, clients of virUUIDParse
were checking for errors.  Silence those coverity warnings by
explicitly marking the cases where we trust the input, and fixing
one instance that really should have been checking.  In particular,
this silences a rather large percentage of the warnings I saw on my
most recent Coverity analysis run.

* src/util/uuid.h (virUUIDParse): Enforce rules.
* src/util/uuid.c (virUUIDParse): Drop impossible check; at least
Coverity will detect if we break rules and pass NULL.
* src/xenapi/xenapi_driver.c (xenapiDomainCreateXML)
(xenapiDomainLookupByID, xenapiDomainLookupByName)
(xenapiDomainDefineXML): Ignore return when we trust data source.
* src/vbox/vbox_tmpl.c (nsIDtoChar, vboxIIDToUUID_v3_x)
(vboxCallbackOnMachineStateChange)
(vboxCallbackOnMachineRegistered, vboxStoragePoolLookupByName):
Likewise.
* src/node_device/node_device_hal.c (gather_system_cap): Likewise.
* src/xenxs/xen_sxpr.c (xenParseSxpr): Check for errors.
2011-10-13 12:23:37 -06:00
Eric Blake
219600c94e command: avoid fd leak on failure
virCommandTransferFD promises that the fd is no longer owned by
the caller.  Normally, we want the fd to remain open until the
child runs, but in error situations, we must close it earlier.

* src/util/command.c (virCommandTransferFD): Close fd now if we
can't track it to close later.
(virCommandKeepFD): Adjust helper to make this easier.
2011-10-13 11:48:42 -06: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
Daniel P. Berrange
ddf3bd32ce Rewrite all the DTrace/SystemTAP probing
The libvirtd daemon had a few crude system tap probes. Some of
these were broken during the RPC rewrite. The new modular RPC
code is structured in a way that allows much more effective
tracing. Instead of trying to hook up the original probes,
define a new set of probes for the RPC and event code.

The master probes file is now src/probes.d.  This contains
probes for virNetServerClientPtr, virNetClientPtr, virSocketPtr
virNetTLSContextPtr and virNetTLSSessionPtr modules. Also add
probes for the poll event loop.

The src/dtrace2systemtap.pl script can convert the probes.d
file into a libvirt_probes.stp file to make use from systemtap
much simpler.

The src/rpc/gensystemtap.pl script can generate a set of
systemtap functions for translating RPC enum values into
printable strings. This works for all RPC header enums (program,
type, status, procedure) and also the authentication enum

The PROBE macro will automatically generate a VIR_DEBUG
statement, so any place with a PROBE can remove any existing
manual DEBUG statements.

* daemon/libvirtd.stp, daemon/probes.d: Remove obsolete probing
* daemon/libvirtd.h: Remove probe macros
* daemon/Makefile.am: Remove all probe buildings/install
* daemon/remote.c: Update authentication probes
* src/dtrace2systemtap.pl, src/rpc/gensystemtap.pl: Scripts
  to generate STP files
* src/internal.h: Add probe macros
* src/probes.d: Master list of probes
* src/rpc/virnetclient.c, src/rpc/virnetserverclient.c,
  src/rpc/virnetsocket.c, src/rpc/virnettlscontext.c,
  src/util/event_poll.c: Insert probe points, removing any
  DEBUG statements that duplicate the info
2011-10-11 11:26:13 +01:00
Eric Blake
dbbe16c26e maint: typo fixes
I noticed a couple typos in recent commits, and fixed the remaining
instances of them.

* docs/internals/command.html.in: Fix spelling errors.
* include/libvirt/libvirt.h.in (virConnectDomainEventCallback):
Likewise.
* python/libvirt-override.py (virEventAddHandle): Likewise.
* src/lxc/lxc_container.c (lxcContainerChild): Likewise.
* src/util/hash.c (virHashCreateFull): Likewise.
* src/storage/storage_backend_logical.c
(virStorageBackendLogicalMakeVol): Likewise.
* src/esx/esx_driver.c (esxFormatVMXFileName): Likewise.
* src/vbox/vbox_tmpl.c (vboxIIDIsEqual_v3_x): Likewise.
2011-10-10 14:02:06 -06:00
Eric Blake
3c797404a5 snapshot: add REVERT_FORCE to API
Although reverting to a snapshot is a form of data loss, this is
normally expected.  However, there are two cases where additional
surprises (failure to run the reverted state, or a break in
connectivity to the domain) can come into play.  Requiring extra
acknowledgment in these cases will make it less likely that
someone can get into an unrecoverable state due to a default revert.

Also create a new error code, so users can distinguish when forcing
would make a difference, rather than having to blindly request force.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_SNAPSHOT_REVERT_FORCE):
New flag.
* src/libvirt.c (virDomainRevertToSnapshot): Document it.
* include/libvirt/virterror.h (VIR_ERR_SNAPSHOT_REVERT_RISKY): New
error value.
* src/util/virterror.c (virErrorMsg): Implement it.
* tools/virsh.c (cmdDomainSnapshotRevert): Add --force to virsh.
* tools/virsh.pod (snapshot-revert): Document it.
2011-10-05 11:33:36 -06:00
Jiri Denemark
11c6e094e4 logging: Add date to log timestamp 2011-09-29 13:42:50 +02:00
Jiri Denemark
2a449549c1 logging: Do not log timestamp through syslog
Syslog puts the timestamp to every message anyway so this removes
redundant data.
2011-09-29 13:42:34 +02:00
Michal Privoznik
45ad3d6962 debug: Annotate some variables as unused
as they are not used with debugging turned off.
2011-09-27 10:16:46 +02:00
ajia@redhat.com
d02c4a1877 util: avoid memory leak
Leak in pciGetVirtualFunctionIndex present since commit 17d64ca.

* src/util/pci.c: fix memory leak.

Signed-off-by: Alex Jia <ajia@redhat.com>
2011-09-19 13:40:21 -06:00
Peter Krempa
79cf07af7c Avoid using "devname" as an identifier.
/usr/lib/stdlib.h in Mac OS X and probably also in BSD's
exports this symbol :(
2011-09-16 20:49:04 +08:00
Michal Privoznik
d1a366be05 Threadpool: Initialize new dynamic workers
Although we were initializing worker threads during pool creating,
we missed this during virThreadPoolSendJob. This bug led to segmenation
fault as worker thread free() given argument.
2011-09-07 14:23:26 +02:00
Peter Krempa
c246b02586 link-state: util: Add equality comparison functions for structures
This patch adds functions to compare structures containing network
device configuration for equality. They serve for the purpose of
disallowing unsupported changes to live network devices.
2011-09-06 16:05:53 +08:00
Peter Krempa
9fd3bb7a88 XML: Improve XML parsing error messages
This patch modifies error handling function for the XML parser provided
by libxml2.

Originaly only a line number and error message were logged. With this
new error handler function, the user is provided with a more complex
description of the parsing error.

Context of the error is printed in libXML2 style and filename of the
file, that caused the error is printed. Example of an parse error:

13:41:36.262: 16032: error : catchXMLError:706 :
/etc/libvirt/qemu/rh_bad.xml:58: Opening and ending tag mismatch: name
line 2 and domain
</domain>
---------^

Context of the error gives the user hints that may help to quickly
locate a corrupt xml file.

fixes BZs:
----------
Bug 708735 - [RFE] Show column and line on XML parsing error
https://bugzilla.redhat.com/show_bug.cgi?id=708735

Bug 726771 - libvirt does not specify problem file if persistent xml is
invalid
https://bugzilla.redhat.com/show_bug.cgi?id=726771
2011-09-06 15:48:22 +08:00
Michal Privoznik
597fe3cee6 daemon: Create priority workers pool
This patch annotates APIs with low or high priority.
In low set MUST be all APIs which might eventually access monitor
(and thus block indefinitely). Other APIs may be marked as high
priority. However, some must be (e.g. domainDestroy).

For high priority calls (HPC), there are some high priority workers
(HPW) created in the pool. HPW can execute only HPC, although normal
worker can process any call regardless priority. Therefore, only those
APIs which are guaranteed to end in reasonable small amount of time
can be marked as HPC.

The size of this HPC pool is static, because HPC are expected to end
quickly, therefore jobs assigned to this pool will be served quickly.
It can be configured in libvirtd.conf via prio_workers variable.
Default is set to 5.

To mark API with low or high priority, append priority:{low|high} to
it's comment in src/remote/remote_protocol.x. This is similar to
autogen|skipgen. If not marked, the generator assumes low as default.
2011-09-05 18:14:08 +02:00
Osier Yang
27758859c7 storage: Add fs pool formatting
This patch adds the ability to make the filesystem for a filesystem
pool during a pool build.

The patch adds two new flags, no overwrite and overwrite, to control
when mkfs gets executed.  By default, the patch preserves the
current behavior, i.e., if no flags are specified, pool build on a
filesystem pool only makes the directory on which the filesystem
will be mounted.

If the no overwrite flag is specified, the target device is checked
to determine if a filesystem of the type specified in the pool is
present.  If a filesystem of that type is already present, mkfs is
not executed and the build call returns an error.  Otherwise, mkfs
is executed and any data present on the device is overwritten.

If the overwrite flag is specified, mkfs is always executed, and any
existing data on the target device is overwritten unconditionally.
2011-09-02 21:16:58 +08:00
Daniel P. Berrange
c32536e7da Don't leak memory if a cgroup is mounted multiple times
It is possible (expected/likely in Fedora 15) for a cgroup controller
to be mounted in multiple locations at the same time, due to bind
mounts. Currently we leak memory if this happens, because we overwrite
the previous 'mountPoint' string. Instead just accept the first match
we find.

* src/util/cgroup.c: Only accept first match for a cgroup
  controller mount
2011-08-31 17:51:09 +01:00
Eric Blake
71a0beaf3a build: simplify use of verify
Back in 2008 when this line of util.h was written, gnulib's verify
module didn't allow the use of multiple verify() in one file
in combination with our choice of gcc -W options.  But that has
since been fixed in gnulib, and newer gnulib even maps verify()
to the C1x feature of _Static_assert, which gives even nicer
diagnostics with a new enough compiler, so we might as well go
with the simpler verify().

* src/util/util.h (VIR_ENUM_IMPL): Use simpler verify, now that
gnulib module is smarter.
2011-08-30 09:23:20 -06:00
Matthias Bolte
4d6e6f4aa9 hyperv: Add driver skeleton 2011-08-26 17:52:55 +02:00
Michal Privoznik
6c7299d47d virterror: Fix error message for VIR_ERR_INVALID_ARG
When a detail message is presented, nobody expects prefix 'invalid
argument in' but something more general, like 'invalid argument:'.
2011-08-26 16:40:42 +02:00
Daniel P. Berrange
ce93f64b1e Fix keymap used to talk with QEMU
The QEMU 'sendkey' command expects keys to be encoded in the same
way as the RFB extended keycode set. Specifically it wants extended
keys to have the high bit of the first byte set, while the Linux
XT KBD driver codeset uses the low bit of the second byte. To deal
with this we introduce a new keymap 'RFB' and use that in the QEMU
driver

* include/libvirt/libvirt.h.in: Add VIR_KEYCODE_SET_RFB
* src/qemu/qemu_driver.c: Use RFB keycode set instead of XT KBD
* src/util/virkeycode-mapgen.py: Auto-generate the RFB keycode
  set from the XT KBD set
* src/util/virkeycode.c: Add RFB keycode entry to table. Add a
  verify check on cardinality of the codeOffset table
2011-08-26 14:18:57 +01:00
Laine Stump
b1643dc15c util: only fchown newly created files in virFileOpenAs
virFileOpenAs takes desired uid:gid as arguments, and not only uses
them for a fork/setuid/setgid when retrying failed open operations,
but additionally always forces the opened file to be owned by the
given uid:gid.

One example of the problems this causes is that, when restoring a
domain from a file that is owned by the qemu user, opening the file
chowns it to root. if dynamic_ownership=1 this is coincidentally
expected, but if dynamic_ownership=0, no existing file should ever
have its ownership changed.

This patch adds an extra check before calling fchown() - it only does
it if O_CREAT was passed to virFileOpenAs() in the openflags.
2011-08-24 15:32:00 -04:00
Eric Blake
3a52b864dd maint: fix comment typos
* src/qemu/qemu_driver.c (qemuDomainSaveInternal): Fix typo.
* src/conf/domain_event.c (virDomainEventDispatchMatchCallback):
Likewise.
* daemon/libvirtd.c (daemonRunStateInit): Likewise.
* src/lxc/lxc_container.c (lxcContainerChildMountSort): Likewise.
* src/util/virterror.c (virCopyError, virRaiseErrorFull): Likewise.
* src/xenxs/xen_sxpr.c (xenParseSxprSound): Likewise.
2011-08-23 11:31:28 -06:00
KAMEZAWA Hiroyuki
9f5afc732c send-key: fix scan keycode map
Now, bad key-code in send-key can cause segmentation fault in libvirt.
(example)
 % virsh send-key --codeset win32 12
   error: End of file while reading data: Input/output error

This is caused by overrun at scanning keycode array.

Fix it.

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
2011-08-22 07:24:15 -06:00
Eric Blake
751304e367 xml: add another convenience function
Often, we want to use XPath functions on the just-parsed document;
fold this into the parser function for convenience.

* src/util/xml.h (virXMLParseHelper): Add argument.
(virXMLParseStrHelper, virXMLParseFileHelper): Delete.
(virXMLParseCtxt, virXMLParseStringCtxt, virXMLParseFileCtxt): New
macros.
* src/libvirt_private.syms (xml.h): Remove deleted functions.
* src/util/xml.c (virXMLParseHelper): Add argument.
(virXMLParseStrHelper, virXMLParseFileHelper): Delete.
2011-08-19 09:13:54 -06:00
Eric Blake
c811de8fb7 build: fix virpidfile on mingw
Regression introduced in commit b7e5ca4.

Mingw lacks kill(), but we were only using it for a sanity check;
so we can go with one less check.

Also, on OOM error, this function should outright fail rather than
claim that the pid file was successfully read.

* src/util/virpidfile.c (virPidFileReadPathIfAlive): Skip kill
call where unsupported, and report error on OOM.
2011-08-17 11:51:24 -06:00
Stefan Berger
57c7b40b76 maint: fix some compilation issues on non-linux platforms (part 2)
Get rid of the #if __linux__ check in virPidFileReadPathIfAlive that
was preventing a check of a symbolic link in /proc/<pid>/exe on
non-linux platforms against an expected executable. Replace
this with a run-time check testing whether the /proc/<pid>/exe is a
symbolic link and if so call the function doing the comparison
against the expected file the link is supposed to point to.
2011-08-16 15:36:22 -04:00
Stefan Berger
f4765b691d maint: fix some compilation issues on non-linux platforms
This patch fixes *some* compilation issues on non-Linux platforms (cygwin).
2011-08-16 13:54:15 -04:00
Roopa Prabhu
5abbf7b958 macvtap: Fix getPhysfn to get the PF of a direct attach network interface
This patch renames getPhysfn to getPhysfnDev and adds code to get the
Physical function and Virtual Function index of the direct attach linkdev (if
the direct attach interface is a SRIOV VF). The idea is to send the port
profile message to a PF if the direct attach interface is a SRIOV VF.

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
Signed-off-by: Christian Benvenuti <benve@cisco.com>
Signed-off-by: David Wang <dwang2@cisco.com>
2011-08-16 11:59:00 -04:00
Roopa Prabhu
cd5544d412 interface: Add functions to get sriov PF/VF relationship of a net interface
This patch adds the following functions to get PF/VF relationship of an SRIOV
network interface:
ifaceIsVirtualFunction: Function to check if a network interface is a SRIOV VF
ifaceGetVirtualFunctionIndex: Function to get VF index if a network interface is a SRIOV VF
ifaceGetPhysicalFunction: Function to get the PF net interface name of a SRIOV VF net interface

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
Signed-off-by: Christian Benvenuti <benve@cisco.com>
Signed-off-by: David Wang <dwang2@cisco.com>
2011-08-16 11:59:00 -04:00
Roopa Prabhu
17d64cab16 pci: Add helper functions for sriov devices
This patch adds the following helper functions:
pciDeviceIsVirtualFunction: Function to check if a pci device is a sriov VF
pciGetVirtualFunctionIndex: Function to get the VF index of a sriov VF
pciDeviceNetName: Function to get the network device name of a pci device
pciConfigAddressCompare: Function to compare pci config addresses

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
Signed-off-by: Christian Benvenuti <benve@cisco.com>
Signed-off-by: David Wang <dwang2@cisco.com>
Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2011-08-16 11:59:00 -04:00
Roopa Prabhu
03172265d3 pci: Move some pci sriov helper code out of node device driver to util/pci
This patch moves some of the sriov related pci code from node_device driver
to src/util/pci.[ch]. Some functions had to go thru name and argument list
change to accommodate the move.

Signed-off-by: Roopa Prabhu <roprabhu@cisco.com>
Signed-off-by: Christian Benvenuti <benve@cisco.com>
Signed-off-by: David Wang <dwang2@cisco.com>
2011-08-16 11:59:00 -04:00
Eric Blake
be427e8b0b build: fix recent build failures
With gcc 4.5.1:

util/virpidfile.c: In function 'virPidFileAcquirePath':
util/virpidfile.c:308:66: error: nested extern declaration of '_gl_verify_function2' [-Wnested-externs]

Then in tests/commandtest.c, the new virPidFile APIs need to be used.

* src/util/virpidfile.c (virPidFileAcquirePath): Move verify to
top level.
* tests/commandtest.c: Use new pid APIs.
2011-08-12 16:16:29 -06:00
Daniel P. Berrange
e1da464d88 Add some APIs which use locking for crashsafe pidfile handling
In daemons using pidfiles to protect against concurrent
execution there is a possibility that a crash may leave a stale
pidfile on disk, which then prevents later restart of the daemon.

To avoid this problem, introduce a pair of APIs which make
use of virFileLock to ensure crash-safe & race condition-safe
pidfile acquisition & releae

* src/libvirt_private.syms, src/util/virpidfile.c,
  src/util/virpidfile.h: Add virPidFileAcquire and virPidFileRelease
2011-08-12 20:37:00 +01:00
Daniel P. Berrange
b7e5ca48f8 Introduce functions for checking whether a pidfile is valid
In some cases the caller of virPidFileRead might like extra checks
to determine whether the pid just read is really the one they are
expecting. This adds virPidFileReadIfAlive which will check whether
the pid is still alive with kill(0, -1), and (on linux only) will
look at /proc/$PID/path

* libvirt_private.syms, util/virpidfile.c, util/virpidfile.h: Add
  virPidFileReadIfValid and virPidFileReadPathIfValid
* network/bridge_driver.c: Use new APIs to check PID validity
2011-08-12 20:37:00 +01:00
Daniel P. Berrange
f80a4ed77a Move pidfile functions into util/virpidfile.{c,h}
The functions for manipulating pidfiles are in util/util.{c,h}.
We will shortly be adding some further pidfile related functions.
To avoid further growing util.c, this moves the pidfile related
functions into a dedicated virpidfile.{c,h}. The functions are
also all renamed to have 'virPidFile' as their name prefix

* util/util.h, util/util.c: Remove all pidfile code
* util/virpidfile.c, util/virpidfile.h: Add new APIs for pidfile
  handling.
* lxc/lxc_controller.c, lxc/lxc_driver.c, network/bridge_driver.c,
  qemu/qemu_process.c: Add virpidfile.h include and adapt for API
  renames
2011-08-12 20:37:00 +01:00
Daniel P. Berrange
e48427051d Add virFileLock and virFileUnlock APIs
Add some simple wrappers around the fcntl() discretionary file
locking capability.

* src/util/util.c, src/util/util.h, src/libvirt_private.syms: Add
  virFileLock and virFileUnlock APIs
2011-08-12 20:37:00 +01:00
Eric Blake
c86827a243 util: plug memory leak
Leak detected by Coverity; only possible on unlikely ptsname_r
failure.  Additionally, the man page for ptsname_r states that
failure is merely non-zero, not necessarily -1.

* src/util/util.c (virFileOpenTtyAt): Avoid leak on ptsname_r
failure.
2011-08-02 16:39:02 -06:00
Eric Blake
d69b79ab72 interface: drop dead code
Coverity detected that ifaceGetNthParent had already dereferenced
'nth' prior to the conditional; all callers already complied with
passing a non-NULL pointer so make this part of the contract.

* src/util/interface.h (ifaceGetNthParent): Add annotations.
* src/util/interface.c (ifaceGetNthParent): Drop useless null check.
2011-08-02 16:39:01 -06:00
Eric Blake
44ebb18ec2 build: silence coverity false positives
Coverity complained that 395 out of 409 virAsprintf calls are
checked, and therefore assumed that the remaining cases are bugs
waiting to happen.  But in each of these cases, a failed virAsprintf
will properly set the target string to NULL, and pass on that
failure to the caller, without wasting efforts to check the call.
Adding the ignore_value silences Coverity.

* src/conf/domain_audit.c (virDomainAuditGetRdev): Ignore
virAsprintf return value, when it behaves like we need.
* src/network/bridge_driver.c (networkDnsmasqLeaseFileNameDefault)
(networkRadvdConfigFileName, networkBridgeDummyNicName)
(networkRadvdPidfileBasename): Likewise.
* src/util/storage_file.c (absolutePathFromBaseFile): Likewise.
* src/openvz/openvz_driver.c (openvzGenerateContainerVethName):
Likewise.
* src/util/command.c (virCommandTranslateStatus): Likewise.
2011-08-02 16:39:01 -06:00
Osier Yang
ef765169dd utils: More useful error message for hook script failure
Commit 3709a386 ported hooks codes to new command execution API,
together with the useful error message removed. Though we can't
get "errbuf" from the new command execution API anymore, still
we can give a more useful error.

https://bugzilla.redhat.com/show_bug.cgi?id=726398
2011-07-29 22:40:47 +08:00
Michal Privoznik
fe957f0a6f bandwidth: Integrate bandwidth into portgroups
Every DomainNetDef has a bandwidth, as does every portgroup.
Whenever a DomainNetDef of type NETWORK is about to be used, a call is
made to networkAllocateActualDevice(). This function chooses the "best"
bandwidth object and places it in the DomainActualNetDef.
From that point on, whenever some code needs to use the bandwidth data
for the interface, it's retrieved with virDomainNetGetActualBandwidth(),
which will always return the "best" info as determined in the
previous step.
2011-07-27 10:26:25 +02:00
Laine Stump
d6354c1696 util: change virFile*Pid functions to return < 0 on failure
Although most functions in libvirt return 0 on success and < 0 on
failure, there are a few functions lingering around that return errno
(a positive value) on failure, and sometimes code calling those
functions incorrectly assumes the <0 standard. I noticed one of these
the other day when auditing networkStartDhcpDaemon after Guido Gunther
found a place where success was improperly returned on failure (that
patch has been acked and is pending a push). The problem was that it
expected the return value from virFileReadPid to be < 0 on failure,
but it was actually positive (it was also neglected to set the return
code in this case, similar to the bug found by Guido).

This all led to the fact that *all* of the virFile*Pid functions in
util.c are returning errno on failure. This patch remedies that
problem by changing them all to return -errno on failure, and makes
any necessary changes to callers of the functions. (In the meantime, I
also properly set the return code on failure of virFileReadPid in
networkStartDhcpDaemon).
2011-07-25 16:56:26 -04:00
Michal Privoznik
90074ecfa7 bandwidth: Implement functions to enable and disable QoS
These function executes 'tc' with appropriate arguments to set
desired QoS setting on interface or bridge during its creation.
2011-07-25 13:49:55 +08:00
Michal Privoznik
aaa98b08ff bandwidth: Create format functions 2011-07-25 13:49:44 +08:00
Michal Privoznik
e2ed67a8b6 bandwidth: Add parsing and free functions
These functions parse given XML node and return pointer to the
output. Unknown elements are silently ignored. Attributes must
be integer and must fit in unsigned long long.

Free function frees elements of virBandwidth structure.
2011-07-25 13:49:33 +08:00
Michal Privoznik
7373188219 bandwidth: Declare internal structures 2011-07-25 13:49:18 +08:00
Laine Stump
c5d1592e20 util: add an ifaceGetIPAddress to the interface utilities
This function uses ioctl(SIOCGIFADDR), which limits it to returning
the first IPv4 address of an interface, but that's what we want right
now (the place we're going to use the address only accepts one).
2011-07-25 13:48:37 +08:00
Matthias Bolte
1a80a4e0d4 build: Use $(PYTHON) instead of python for the keycode map generator
Also prepend $(AM_V_GEN) to the command line, mark virkeycode-mapgen.py
as executable and switch the shebang line from /bin/python to the
commonly use /usr/bin/python.
2011-07-22 16:16:33 +02:00
Laine Stump
f7e18208e1 util: make interface.c functions consistently return < 0 on error
All of the functions in util/interface.c were returning 0 on success,
but some returned -1 on error, and some returned a positive value
(usually the value of errno, but sometimes just 1). Libvirt's standard
is to return < 0 on error (in the case of functions that need to
return errno, -errno is returned.

This patch modifies all functions in interface.c to consistently
return < 0 on error, and makes changes to callers of those functions
where necessary.
2011-07-22 09:27:07 -04:00
Eric Blake
519a1c4379 save: add virFileDirectFd wrapper type
O_DIRECT has stringent requirements.  Rather than make lots of changes
at each site that wants to use O_DIRECT, it is easier to offload
the work through a helper process that mirrors the I/O between a
pipe and the actual direct fd, so that the other end of the pipe
no longer has to worry about constraints.

Plus, if the kernel ever gains better posix_fadvise support, then we
only have to touch a single file to let all callers benefit from a
more efficient way to avoid file system caching.

* src/util/virfile.h (virFileDirectFdFlag, virFileDirectFdNew)
(virFileDirectFdClose, virFileDirectFdFree): New prototypes.
* src/util/virdirect.c: Implement new wrapper object.
* src/libvirt_private.syms (virfile.h): Export new symbols.
* cfg.mk (useless_free_options): Add to list.
* po/POTFILES.in: Add new translations.
2011-07-21 16:24:08 -06:00
Eric Blake
12291656b1 save: let iohelper work on O_DIRECT fds
Required for a coming patch where iohelper will operate on O_DIRECT
fds.  There, the user-space memory must be aligned to file system
boundaries (at least 512, but using page-aligned works better, and
some file systems prefer 64k).  Made tougher by the fact that
VIR_ALLOC won't work on void *, but posix_memalign won't work on
char * and isn't available everywhere.

This patch makes some simplifying assumptions - namely, output
to an O_DIRECT fd will only be attempted on an empty seekable
file (hence, no need to worry about preserving existing data
on a partial block, and ftruncate will work to undo the effects
of having to round up the size of the last block written), and
input from an O_DIRECT fd will only be attempted on a complete
seekable file with the only possible short read at EOF.

* configure.ac (AC_CHECK_FUNCS_ONCE): Check for posix_memalign.
* src/util/iohelper.c (runIO): Use aligned memory, and handle
quirks of O_DIRECT on last write.
2011-07-21 16:24:08 -06:00
Eric Blake
1eb6647979 save: let iohelper handle inherited fd
Rather than making the iohelper subject to a race in reopening
the file, it is nicer to pass an already-open fd by inheritance.

The old synopsis form must continue to work - if someone updates
their libvirt package and installs a new libvirt_iohelper but
without restarting the old libvirtd daemon, then the daemon can
still make calls using the old syntax but the new iohelper.

* src/util/iohelper.c (runIO): Split code for open...
(prepare): ...to new function.
(usage): Update synopsis.
(main): Allow alternate calling form.
* src/fdstream.c (virFDStreamOpenFileInternal): Use alternate form.
2011-07-21 16:24:08 -06:00
Eric Blake
1700345708 error: add new error type for reflecting partial API support
VIR_ERR_INVALID_ARG implies that an argument cannot possibly
be correct, given the current state of the API.
VIR_ERR_CONFIG_UNSUPPORTED implies that a configuration is
wrong, but arguments aren't configuration.
VIR_ERR_NO_SUPPORT implies that a function is completely
unimplemented.

But in the case of a function that is partially implemented,
yet the full power of the API is not available for that
driver, none of the above messages make sense.  Hence a new
error message, implying that the argument is known to comply
with the current state of the API, and that while the driver
supports aspects of the function, it does not support that
particular use of the argument.

A good use case for this is a driver that supports
virDomainSaveFlags, but not the dxml argument of that API.

It might be feasible to also use this new error for all functions
that check flags, and which accept fewer flags than what is possible
in the public API.  But doing so would get complicated, since
neither libvirt.c nor the remote driver may do flag filtering,
and every other driver would have to do a two-part check, first
using virCheckFlags on all public flags (which gives
VIR_ERR_INVALID_ARG for an impossible flag), followed by a
particular mask check for VIR_ERR_ARGUMENT_UNSUPPORTED (for a
possible public flag but unsupported by this driver).

* include/libvirt/virterror.h (VIR_ERR_ARGUMENT_UNSUPPORTED): New
error.
* src/util/virterror.c (virErrorMsg): Give it a message.
Suggested by Daniel P. Berrange.
2011-07-21 16:04:56 -06:00
Laine Stump
524655eea2 conf: virDomainNetDef points to (rather than contains) virtPortProfile
The virtPortProfile in the domain interface struct is now a separately
allocated object *pointed to by* (rather than contained in) the main
virDomainNetDef object. This is done to make it easier to figure out
when a virtualPortProfile has/hasn't been specified in a particular
config.
2011-07-21 14:46:39 -04:00
Laine Stump
a3d95b550b conf: put virtPortProfile struct / functions in a common location
virtPortProfiles are currently only used in the domain XML, but will
soon also be used in the network XML. To prepare for that change, this
patch moves the structure definition into util/network.h and the parse
and format functions into util/network.c (I decided that this was a
better choice than macvtap.h/c for something that needed to always be
available on all platforms).
2011-07-21 14:46:33 -04:00
Laine Stump
6fe5fde292 util: define MAX
If util.h is going to have a MIN, it may as well also have MAX.
2011-07-21 14:45:20 -04:00
Eric Blake
8e22e08935 build: rename files.h to virfile.h
In preparation for a future patch adding new virFile APIs.

* src/util/files.h, src/util/files.c: Move...
* src/util/virfile.h, src/util/virfile.c: ...here, and rename
functions to virFile prefix.  Macro names are intentionally
left alone.
* *.c: All '#include "files.h"' uses changed.
* src/Makefile.am (UTIL_SOURCES): Reflect rename.
* cfg.mk (exclude_file_name_regexp--sc_prohibit_close): Likewise.
* src/libvirt_private.syms: Likewise.
* docs/hacking.html.in: Likewise.
* HACKING: Regenerate.
2011-07-21 10:34:51 -06:00
Eric Blake
5d804ffae4 command: avoid leaking fds across fork
Since libvirt is multi-threaded, we should use FD_CLOEXEC as much
as possible in the parent, and only relax fds to inherited after
forking, to avoid leaking an fd created in one thread to a fork
run in another thread.  This gets us closer to that ideal, by
making virCommand automatically clear FD_CLOEXEC on fds intended
for the child, as well as avoiding a window of time with non-cloexec
pipes created for capturing output.

* src/util/command.c (virExecWithHook): Use CLOEXEC in parent.  In
child, guarantee that all fds to pass to child are inheritable.
(getDevNull): Use CLOEXEC.
(prepareStdFd): New helper function.
(virCommandRun, virCommandRequireHandshake): Use pipe2.
* src/qemu/qemu_command.c (qemuBuildCommandLine): Simplify caller.
2011-07-21 10:34:51 -06:00
Eric Blake
4289114518 command: move all docs into .c file
We already have a precedent of function documentation in C files,
where it is closer to the implementation (witness libvirt.h vs.
libvirt.c); maintaining docs in both files risks docs going stale.

While I was at it, I used consistent doxygen style on all comments.

* src/util/command.h: Remove duplicate docs, and move unique
documentation...
* src/util/command.c: ...here.
Suggested by Matthias Bolte.
2011-07-21 10:34:51 -06:00
Eric Blake
979b784be2 error: preserve errno when saving last error
It is common to see the sequence:

virErrorPtr save_err = virSaveLastError();
// do cleanup
virSetError(save_err);
virFreeError(save_err);

on cleanup paths.  But for functions where it is desirable to
return the errno that caused failure, this sequence can clobber
that errno.  virFreeError was already safe; this makes the other
two functions in the sequence safe as well, assuming all goes
well (on OOM, errno will be clobbered, but then again, save_err
won't reflect the real error that happened, so you are no longer
preserving the real situation - that's life with OOM).

* src/util/virterror.c (virSaveLastError, virSetError): Preserve
errno.
2011-07-21 07:24:33 -06:00
Wen Congyang
fd7c172340 cgroup: Implement cpu.cfs_period_us and cpu.cfs_quota_us tuning API
This patch provides 4 APIs to get and set cpu.cfs_period_us and cpu.cfs_quota_us.
2011-07-21 17:11:12 +08:00
Wen Congyang
8e64f87306 Introduce the function virCgroupForVcpu
Introduce the function virCgroupForVcpu() to create sub directory for each vcpu.
2011-07-21 17:11:12 +08:00
Lai Jiangshan
0bbf87e91e util: add virtkeycode module
Add virtkey lib for usage-improvment and keycode translating.
Add 4 internal API for the aim

const char *virKeycodeSetTypeToString(int codeset);
int virKeycodeSetTypeFromString(const char *name);
int virKeycodeValueFromString(virKeycodeSet codeset, const char *keyname);
int virKeycodeValueTranslate(virKeycodeSet from_codeset,
                             virKeycodeSet to_offset,
                             int key_value);

* include/libvirt/libvirt.h.in: extend virKeycodeSet enum
* src/Makefile.am: add new virtkeycode module and rule to generate
  virkeymaps.h
* src/util/virkeycode.c src/util/virkeycode.h: new module
* src/util/virkeycode-mapgen.py: python generator for virkeymaps.h
  out of keymaps.csv
* src/libvirt_private.syms: extend private symbols for new module
* .gitignore: add generated virkeymaps.h
2011-07-21 15:57:47 +08:00
Lai Jiangshan
1151f0eee8 util: Add keymaps.csv
Should keep it as the same as:
http://git.gnome.org/browse/gtk-vnc/commit/src/keymaps.csv

All master  keymaps are defined in a CSV file. THis covers
Linux keycodes, OSX keycodes, AT set1, 2 & 3, XT keycodes,
the XT encoding used by the Linux KBD driver, USB keycodes,
Win32 keycodes, the XT encoding used by Xorg on Cygwin,
the XT encoding used by Xorg on Linux with kbd driver.

* src/Makefile.am: added to EXTRA_DIST
* src/util/keymaps.csv: new file
2011-07-21 15:02:52 +08:00
Eric Blake
a71434054c maint: fix typos on guaranteed
* src/conf/domain_event.c (virDomainEventDispatch): Fix typo.
* src/internal.h (ATTRIBUTE_FMT_PRINTF): Likewise.
* src/libvirt.c (virStreamEventUpdateCallback): Likewise.
* src/remote/remote_driver.c (doRemoteOpen): Likewise.
* src/storage/storage_backend_fs.c (virStorageBackendProbeTarget):
Likewise.
* src/util/virterror.c (virConnCopyLastError, virCopyLastError):
Likewise.
* src/xen/xend_internal.h (xend_wait_for_devices): Likewise.
2011-07-20 16:53:31 -06:00
Michal Privoznik
670c9f770b sysinfo: Don't try to run dmidecode on archs missing it
DMI table is Intel & Intel-compatible specific. Therefore other
architectures miss dmidecode command. So we always fail in searching
for that command on non-Intel architectures.
2011-07-20 17:14:24 +02:00
Eric Blake
f81f63cd04 maint: fix spelling of Red Hat
* cfg.mk (sc_copyright_format): Add to rule.
* src/util/files.h: Fix offenders.
* src/util/files.c: Likewise.
2011-07-19 12:25:19 -06:00
Alex Jia
463e8c2ff0 util: avoid fds leak when virEventPollAddHandle fail
* src/util/event_poll.c: avoid file descriptors leak when
  virEventPollAddHandle fail on virEventPollInit function.
2011-07-19 07:22:27 -06:00
Eric Blake
761bbb17c7 build: add syntax check for proper flags use
Enforce the recent flags cleanups - we want to use 'unsigned int flags'
in any of our APIs (except where backwards compatibility is important,
in the public migration APIs), and that all flags are checked for
validity (except when there are stub functions that completely
ignore the flags argument).

There are a few minor tweaks done here to avoid false positives:
signed arguments passed to open() are renamed oflags, and flags
arguments that are legitimately ignored are renamed flags_unused.

* cfg.mk (sc_flags_usage): New rule.
(exclude_file_name_regexp--sc_flags_usage): And a few exemptions.
(sc_flags_debug): Tweak wording.
* src/util/iohelper.c (runIO, main): Rename variable.
* src/util/util.c (virSetInherit): Likewise.
* src/fdstream.h (virFDStreamOpenFile, virFDStreamCreateFile):
Likewise.
* src/fdstream.c (virFDStreamOpenFileInternal)
(virFDStreamOpenFile, virFDStreamCreateFile): Likewise.
* src/util/command.c (virExecWithHook) [WIN32]: Likewise.
* src/util/util.c (virFileOpenAs, virDirCreate) [WIN32]: Likewise.
* src/locking/lock_manager.c (virLockManagerPluginNew)
[!HAVE_DLFCN_H]: Likewise.
* src/locking/lock_driver_nop.c (virLockManagerNopNew)
(virLockManagerNopAddResource, virLockManagerNopAcquire)
(virLockManagerNopRelease, virLockManagerNopInquire): Likewise.
2011-07-15 16:37:30 -06:00
Eric Blake
e208c38b49 command: introduce virPidWait, virPidAbort
When using virCommandRunAsync and saving the pid for later, it
is useful to be able to reap that pid in the same way that it
would have been auto-reaped by virCommand if we had passed
NULL for the pid argument in the first place.

* src/util/command.c (virPidWait, virPidAbort): New functions,
created from...
(virCommandWait, virCommandAbort): ...bodies of these.
(includes): Drop duplicate <stdlib.h>.  Ensure that our pid_t
assumptions hold.
(virCommandRunAsync): Improve documentation.
* src/util/command.h (virPidWait, virPidAbort): New prototypes.
* src/libvirt_private.syms: Export them.
* docs/internals/command.html.in: Document them.
2011-07-14 11:56:30 -06:00
Michal Privoznik
85aa40e26d storage: Avoid memory leak on metadata fetching
Getting metadata on storage allocates a memory (path) which need to
be freed after use otherwise it gets leaked. This means after use of
virStorageFileGetMetadataFromFD or virStorageFileGetMetadata one
must call virStorageFileFreeMetadata to free it. This function frees
structure internals and structure itself.
2011-07-14 16:39:42 +02:00
Eric Blake
088473b29f build: avoid ATTRIBUTE_UNUSED in headers
The compiler might optimize based on our declaration that something
is unused.  Putting that declaration in the header risks getting
out of sync with the actual implementation, so it belongs better
only in the .c files.  We were mostly compliant, and a new syntax
check will help us in the future.

* cfg.mk (sc_avoid_attribute_unused_in_header): New syntax check.
* src/nodeinfo.h (nodeGetCPUStats, nodeGetMemoryStats): Delete
attribute already present in .c file.
* src/qemu/qemu_domain.h (qemuDomainEventFlush): Likewise.
* src/util/virterror_internal.h (virReportErrorHelper): Parameters
are actually used by .c file.
* src/xenxs/xen_sxpr.h (xenFormatSxprDisk): Adjust prototype.
* src/xenxs/xen_sxpr.c (xenFormatSxprDisk): Delete unused argument.
(xenFormatSxpr): Adjust caller.
* src/xen/xend_internal.c (xenDaemonAttachDeviceFlags)
(xenDaemonUpdateDeviceFlags): Likewise.
Suggested by Daniel Veillard.
2011-07-14 07:51:30 -06:00
Jiri Denemark
3e75c5ec85 util: Avoid duplicating virFileOpenAsNoFork in virFileOpenAs
In 2f4d2496a8 I didn't notice that one
part of virFileOpenAs doesn't actually call to virFileOpenAsNoFork but
rather includes a copy of the code from there.
2011-07-14 11:04:16 +08:00
Eric Blake
ff98359d51 build: don't hand-roll cloexec code
No need to repeat common code.

* bootstrap.conf (gnulib_modules): Import calloc-posix.
* src/util/bridge.c (brInit): Use virSetCloseExec.
(brSetInterfaceUp): Adjust flags name.
* src/uml/uml_driver.c (umlSetCloseExec): Delete.
(umlStartVMDaemon): Use util version instead.
2011-07-13 17:44:08 -06:00
Eric Blake
833fe8abec util: reject unknown flags, and prefer unsigned flags
Silently ignored flags get in the way of new features that
use those flags.  Also, an upcoming syntax check will favor
unsigned flags.

* src/nodeinfo.h (nodeGetCPUStats, nodeGetMemoryStats): Drop
unused attribute.
* src/interface/netcf_driver.c (interfaceOpenInterface)
(interfaceDefineXML, interfaceCreate, interfaceDestroy): Reject
unknown flags.
* src/network/bridge_driver.c (networkOpenNetwork)
(networkGetXMLDesc): Likewise.
* src/nwfilter/nwfilter_driver.c (nwfilterOpen): Likewise.
* src/secret/secret_driver.c (secretOpen, secretDefineXML)
(secretGetXMLDesc, secretSetValue): Likewise.
* src/util/logging.c (virLogDefineFilter, virLogDefineOutput)
(virLogMessage): Likewise; also use unsigned flags.
* src/util/logging.h (virLogDefineFilter, virLogDefineOutput)
(virLogMessage): Change signature.
* src/util/command.c (virExecWithHook): Likewise.
2011-07-13 09:04:54 -06:00
Eric Blake
51fc56553f util: honor anchored names when searching for executables
I got bit in a debugging session on an uninstalled libvirtd; the
code tried to call out to the installed $LIBEXECDIR/libvirt_iohelper
instead of my just-built version.  So I set a breakpoint and altered
the binary name to be "./src/libvirt_iohelper", and it still failed
because I don't have "." on my PATH.

According to POSIX, execvp only searches PATH if the name does
not contain a slash.  Since we are trying to mimic that behavior,
an anchored name should be relative to the current working dir.

This tightens existing behavior, but most callers already pass
an absolute name or a name with no slashes, so it probably won't
be noticeable.

* src/util/util.c (virFindFileInPath): Anchored relative names do
not invoke a PATH search.
2011-07-13 07:30:42 -06:00
Daniel P. Berrange
accfe952eb Keep pidfile path in qemuDomainObjPrivate struct
Avoid re-formatting the pidfile path everytime we need it. Create
it once when starting the guest, and preserve it until the guest
is shutdown.

* src/libvirt_private.syms, src/util/util.c,
  src/util/util.h: Add virFileReadPidPath
* src/qemu/qemu_domain.h: Add pidfile field
* src/qemu/qemu_process.c: Store pidfile path in qemuDomainObjPrivate
2011-07-12 15:39:03 +01:00
Eric Blake
2ceb35e1cd maint: rename virtaudit to match file contents
* src/util/virtaudit.[ch]: Rename...
* src/util/viraudit.[ch]: ...to match virAudit* API.
* src/Makefile.am (UTIL_SOURCES): Reflect rename.
* daemon/libvirtd.c: Likewise.
* po/POTFILES.in: Likewise.
* src/libvirt_private.syms: Likewise.
* src/qemu/qemu_audit.c: Likewise.
2011-07-12 07:24:43 -06:00
Jiri Denemark
2f4d2496a8 util: Don't try to fchown files opened as non-root
When virFileOpenAs is called with VIR_FILE_OPEN_AS_UID flag and uid/gid
different from root/root while libvirtd is running as root, we fork a
new child, change its effective UID/GID to uid/gid and run
virFileOpenAsNoFork. It doesn't make any sense to fchown() the opened
file in this case since we already know that uid/gid can access the file
when open succeeds and one of the following situations may happen:

- the file is already owned by uid/gid and we skip fchown even before
  this patch
- the file is owned by uid but not gid because it was created in a
  directory with SETGID set, in which case it is desirable not to change
  the group
- the file may be owned by a completely different user and/or group
  because it was created on a root-squashed or even all-squashed NFS
  filesystem, in which case fchown would most likely fail anyway
2011-07-08 16:43:55 +02:00
Eric Blake
17da0669e0 util: drop unused safezero argument
No caller was using the flags argument, and this function is internal
only, so we might as well skip it.

* src/util/util.h (safezero): Update signature.
* src/util/util.c (safezero): Update function.
* src/locking/lock_driver_sanlock.c
(virLockManagerSanlockSetupLockspace)
(virLockManagerSanlockCreateLease): Update all callers.
* src/storage/storage_backend.c (createRawFile): Likewise.
2011-07-07 14:15:38 -06:00
Eric Blake
8437e738fa build: use gnulib pthread_sigmask
Gnulib finally learned how to do pthread_sigmask on mingw.

* .gnulib: Update to latest, for pthread_sigmask.
* bootstrap.conf (gnulib_modules): Add pthread_sigmask.
* configure.ac (AC_CHECK_FUNCS): Drop redundant check.
* src/rpc/virnetclient.c (virNetClientSetTLSSession)
(virNetClientIOEventLoop): Make code unconditional.
* src/util/command.c (virFork): Likewise.
* tools/virsh.c (doMigrate, cmdMigrate): Likewise.
2011-07-07 13:12:44 -06:00
Laine Stump
24442b60b9 util: close the ioctl socket at the end of if(Get|Set)MacAddress
Otherwise this will leak an fd each time one of these functions is
called.
2011-07-06 20:16:51 -04:00
Laine Stump
de796a328d util: rename err_exit to cleanup in interface.c
This brings it in line with the recommendations in HACKING.
2011-07-06 20:16:51 -04:00
Minoru Usui
107ee906ff sysinfo: delete unnecessary white space of sysinfo.
* Trim each element and delete null entry of sysinfo by
  virSkipSpacesBackwards().

Signed-off-by: Minoru Usui <usui@mxm.nes.nec.co.jp>
2011-07-06 15:19:28 -06:00
Eric Blake
01374ec8b1 util: add virTrimSpaces
The next patch wants to adjust an end pointer to trim trailing
spaces but without modifying the underlying string, but a more
generally useful ability to trim trailing spaces in place is
also worth providing.

* src/util/util.h (virTrimSpaces, virSkipSpacesBackwards): New
prototypes.
* src/util/util.c (virTrimSpaces, virSkipSpacesBackwards): New
functions.
* src/libvirt_private.syms (util.h): Export new functions.
Inspired by a patch by Minoru Usui.
2011-07-06 15:17:14 -06:00
Eric Blake
82162316b6 util: fix virSkipSpaces
Most clients of virSkipSpaces don't want to omit backslashes.
Also, open-coding the list of spaces is not as nice as using
c_isspace.

* src/util/util.c (virSkipSpaces): Use c_isspace.
(virSkipSpacesAndBackslash): New function.
* src/util/util.h (virSkipSpacesAndBackslash): New prototype.
* src/xen/xend_internal.c (sexpr_to_xend_topology): Update caller.
* src/libvirt_private.syms (util.h): Export new function.
2011-07-06 14:52:43 -06:00
Matthias Bolte
cd9a4232e5 Reduce code duplication in virFileMakePath(Helper)
Move stat and mkdir to virFileMakePathHelper.

Also use the stat result to detect whether the existing path
is a directory and set errno accordingly if it's not.
2011-07-06 16:03:12 +02:00
Matthias Bolte
e123e1ee6b Fix return value semantic of virFileMakePath
Some callers expected virFileMakePath to set errno, some expected
it to return an errno value. Unify this to return 0 on success and
-1 on error. Set errno to report detailed error information.

Also optimize virFileMakePath if stat fails with an errno different
from ENOENT.
2011-07-06 09:27:06 +02:00
Guannan Ren
416814e66a pci: initialize state values on reattach
add a new API pciDeviceReAttachInit() in pci.c to initialize state values for nodedev reattach

Initialize three state value of device driver to 1. This is just for a new call to
qemudNodeDeviceReAttach()
2011-07-05 11:42:38 -06:00
Eric Blake
3f81f8e4c1 cgroup: silence coverity warning
Coverity noted that most clients reacted to failure to hash; but in
a best-effort kill loop, we can ignore failure.

* src/util/cgroup.c (virCgroupKillInternal): Ignore hash failure.
2011-07-04 10:28:27 +08:00
Eric Blake
95eaf7ba7f pci: avoid memory leak on error
Detected by Coverity.  Some, but not all, error paths were clean;
but they were repetitive so I refactored them.

* src/util/pci.c (pciGetDevice): Plug leak.
2011-07-01 16:46:20 -06:00
Eric Blake
9e8b7c1523 interface: avoid memory leak on parse error
Detected by Coverity.  Unlikely to hit unless the file contents
were corrupted.

* src/util/interface.c (ifaceRestoreMacAddress): Plug leak.
2011-07-01 16:46:20 -06:00
Eric Blake
8ce1afff88 util: choose whether to require micro in version strings
To avoid regressions, we let callers specify whether to require a
minor and micro version.  Callers that were parsing uname() output
benefit from defaulting to 0, whereas callers that were parsing
version strings from other sources should not change in behavior.

* src/util/util.c (virParseVersionString): Allow caller to choose
whether to fail if minor or micro is missing.
* src/util/util.h (virParseVersionString): Update signature.
* src/esx/esx_driver.c (esxGetVersion): Update callers.
* src/lxc/lxc_driver.c (lxcVersion): Likewise.
* src/openvz/openvz_conf.c (openvzExtractVersionInfo): Likewise.
* src/uml/uml_driver.c (umlGetVersion): Likewise.
* src/vbox/vbox_MSCOMGlue.c (vboxLookupVersionInRegistry):
Likewise.
* src/vbox/vbox_tmpl.c (vboxExtractVersion): Likewise.
* src/vmware/vmware_conf.c (vmwareExtractVersion): Likewise.
* src/xenapi/xenapi_driver.c (xenapiGetVersion): Likewise.
Reported by Matthias Bolte.
2011-07-01 11:22:11 -06:00
Scott Moser
d42b749abf fix virParseVersionString with linux 3.0
linux 3.0 has no micro version number, and that is causing problems
for virParseVersionString.  The patch below should allow for:
  major
  major.minor
  major.minor.micro

If major or minor are not present they just default to zero.
We found this in Ubuntu (https://bugs.launchpad.net/bugs/802977)
2011-07-01 07:09:48 -06:00
Eric Blake
0ac385bd6c build: remove dead variables
Detected by Coverity.  No real harm in leaving these, but fixing
them cuts down on the noise for future analysis.

* src/rpc/virnetserver.c (virNetServerAddService): Delete unused
entry.
* src/util/sysinfo.c (virSysinfoRead): Delete dead assignment to
base.
2011-07-01 06:48:33 -06:00
Daniel P. Berrange
09a882bd4d Remove bogus warning message in JSON code
* src/util/json.c: Remove warning message
2011-06-30 18:04:01 +01:00
Minoru Usui
72882bc9d9 sysinfo: fix illegal NULL return
If virSysinfoParse{BIOS,System,Processor,Memory}()
can't find newline('\n'), these return NULL.
This patch fixes this.

Signed-off-by: Minoru Usui <usui@mxm.nes.nec.co.jp>
2011-06-29 09:12:38 -06:00
Matthias Bolte
8cce5436dd dnsmasq: Fix errno handling and don't unlink non-existing files
addnhostsSave and hostsfileSave expect < 0 return value on error from
addnhostsWrite and hostsfileWrite but then pass err instead of -err
to virReportSystemError that expects an errno value.

Also addnhostsWrite returns -ENOMEM and errno, change this to -errno.

addnhostsWrite and hostsfileWrite tried to unlink the tempfile after
renaming it, making both fail on the final step. Remove the unnecessary
unlink calls.
2011-06-29 11:38:36 +02:00
Matthias Bolte
eb9dee2b10 network: Don't ignore errors in dnsmasq config file creation 2011-06-29 02:04:55 +02:00
Matthias Bolte
9523b3c320 network: Fix dnsmasq hostsfile creation logic and related tests
networkSaveDnsmasqHostsfile was added in 8fa9c22142 (Apr 2010).
It has a force flag. If the dnsmasq hostsfile already exists force
needs to be true to overwrite it. networkBuildDnsmasqArgv sets force
to false, networkDefine sets it to true. This results in the
hostsfile being written only in networkDefine in the common case.
If no error occurred networkSaveDnsmasqHostsfile returns true and
networkBuildDnsmasqArgv adds the --dhcp-hostsfile to the dnsmasq
command line.

networkSaveDnsmasqHostsfile was changed in 89ae9849f7 (24 Jun 2011)
to return a new dnsmasqContext instead of reusing one. This change broke
the logic of the force flag as now networkSaveDnsmasqHostsfile returns
NULL on error, but the early return -- if force was not set and the
hostsfile exists -- returns 0. This turned the early return in an error
case and networkBuildDnsmasqArgv didn't add the --dhcp-hostsfile option
anymore if the hostsfile already exists. It did because networkDefine
created the hostsfile already.

Then 9d4e2845d4 fixed the return 0 case in networkSaveDnsmasqHostsfile
but didn't apply the force option correctly to the new addnhosts file.
Now force doesn't control an early return anymore, but influences the
handling of the hostsfile context creation and dnsmasqSave is always
called now. This commit also added test cases that reveal several
problems. First, the tests now calls functions that try to write the
dnsmasq config files to disk. If someone runs this tests as root this
might overwrite actively used dnsmasq config files, this is a no-go. Also
the tests depend on configure --localstatedir, this needs to be fixed as
well, because it makes the tests fail when localstatedir is different
from /var.

This patch does several things to fix this:

1) Move dnsmasqContext creation and saving out of networkBuildDnsmasqArgv
to the caller to separate the command line generation from the config
file writing. This makes the command line generation testable without the
risk of interfering with system files, because the tests just don't call
dnsmasqSave.

2) This refactoring of networkSaveDnsmasqHostsfile makes the force flag
useless as the saving happens somewhere else now. This fixes the wrong
usage of the force flag in combination with then newly added addnhosts
file by removing the force flag.

3) Adapt the wrong test cases to the correct behavior, by adding the
missing --dhcp-hostsfile option. Both affected tests contain DHCP host
elements but missed the necessary --dhcp-hostsfile option.

4) Rename networkSaveDnsmasqHostsfile to networkBuildDnsmasqHostsfile,
because it doesn't save the dnsmasqContext anymore.

5) Move all directory creations in dnsmasq context handling code from
the *New functions to dnsmasqSave to avoid directory creations in system
paths in the test cases.

6) Now that networkBuildDnsmasqArgv doesn't create the dnsmasqContext
anymore the test case can create one with the localstatedir that is
expected by the tests instead of the configure --localstatedir given one.
2011-06-29 01:59:34 +02:00
Eric Blake
c8eaba6491 sysinfo: fix parsing regression
Detected by gcc -O2, introduced in commit 532ce9c2.  If dmidecode
outputs a field unrecognized by the parsers, then the code would
dereference an uninitialized eol variable.

* src/util/sysinfo.c (virSysinfoParseBIOS)
(virSysinfoParseSystem, virSysinfoParseProcessor)
(virSysinfoParseMemory): Avoid uninitialized variable.
2011-06-28 13:49:51 -06:00
Minoru Usui
0a755f66d5 sysinfo: cleanup function/struct names.
Fix lack of 'virSysinfo' prefix of functions/structs in src/util/sysinfo.[ch]
2011-06-27 09:41:03 -06:00
Minoru Usui
a6c85d44e0 sysinfo: fix lack of error check in virSysinfoFormat().
Fix lack of error check in virSysinfoFormat().

Signed-off-by: Minoru Usui <usui@mxm.nes.nec.co.jp>
2011-06-27 09:40:38 -06:00
Eric Blake
4a27eb1398 buf: protect against integer overflow
It's unlikely that we'll ever want to escape a string as long as
INT_MAX/6, but adding this check can't hurt.

* src/util/buf.c (virBufferEscapeSexpr, virBufferEscapeString):
Check for (unlikely) overflow.
2011-06-24 16:01:56 -06:00
Matthias Bolte
d95f673ad2 Rename iface(G|S)etMacaddr to iface(G|S)etMacAddress for consistency 2011-06-24 23:06:56 +02:00
Michal Novotny
91b7924eee Network: Add additional hosts internal infrastructure
Signed-off-by: Michal Novotny <minovotn@redhat.com>
2011-06-24 16:15:33 -04:00
Minoru Usui
b46832971c Add Memory Device Information to virSysinfoRead() from dmidecode type 17
* src/util/sysinfo.[ch]: also parse and save all the SMBIOS informations
  about memory modules
2011-06-24 22:22:09 +08:00
Minoru Usui
49156a7a11 Add Processor Information to virSysinfoRead() from dmidecode type 4
* src/util/sysinfo.c: add parsing and formatting of processor
  information data
2011-06-24 22:22:09 +08:00
Minoru Usui
532ce9c22f Cleanup virSysinfoRead()
* src/util/sysinfo.c: Separate BIOSInfo and SystemInfo part from
                      virSysinfoRead()
2011-06-24 22:22:09 +08:00
Stefan Berger
f7ed693666 build: fix compilation on systems missing libnl and new includes
This patch fixes the compilation of netlink.c and interface.c on those
systems missing either libnl or that have an older linux/if_link.h
include file not supporting macvtap or VF_PORTS.

WITH_MACVTAP is '1' if newer include files were detected, '0' otherwise.

IFLA_PORT_MAX is defined in linux/if_link.h if yet more functionality is
supported.
2011-06-23 11:54:11 -04:00