Commit Graph

1506 Commits

Author SHA1 Message Date
Daniel P. Berrange
ec04914c47 Add missing c-ctype.h to virfile.c
The virfile.c file uses c_isalpha on Win32 platforms, so must
include c-ctype.h

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-17 17:09:29 +01:00
Guannan Ren
6459af6a43 qemu: report useful error failling to destroy domain gracefully
Resolves:https://bugzilla.redhat.com/show_bug.cgi?id=927620

 #kill -STOP `pidof qemu-kvm`
 #virsh destroy $guest --graceful
 error: Failed to destroy domain testVM
 error: An error occurred, but the cause is unknown

With --graceful, SIGTERM always is emitted to kill driver
process, but it won't success till burning out waiting time
in case of process being stopped.
But domain destroy without --graceful can work, SIGKILL will
be emitted to the stopped process after 10 secs which always
kills a process even one that is currently stopped.
So report an error after burning out waiting time in this case.
2013-05-17 22:22:46 +08:00
Daniel P. Berrange
c2cf5f1c2a Fix failure to detect missing cgroup partitions
Change bbe97ae968 caused the
QEMU driver to ignore ENOENT errors from cgroups, in order
to cope with missing /proc/cgroups. This is not good though
because many other things can cause ENOENT and should not
be ignored. The callers expect to see ENXIO when cgroups
are not present, so adjust the code to report that errno
when /proc/cgroups is missing

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-17 10:25:15 +01:00
Osier Yang
28d3ad952f utils: Add a helper to get the device name that sg device mapped to
E.g.

% sg_map
/dev/sg0  /dev/sda
/dev/sg1  /dev/sr0

What the helper gets for /dev/sg0 is /dev/sda, it will be used by
later patch.
2013-05-16 23:50:00 +08:00
Jiri Denemark
c431f06587 util: Fix build without devmapper
stdlib.h header file needed for getenv was only transitively included
through libdevmapper.h.
2013-05-16 12:15:38 +02:00
Martin Kletzander
84d9142495 Fix invalid argument reference in virnetdev.h
Commit ccff335f added ATTRIBUTE_NONNULL for an attribute which is not
a pointer and made files including virnetdev.h not compilable, so fix
that.
2013-05-14 18:27:51 +02:00
Eric Blake
547a7c778a json: support removing a value from an object
In an upcoming patch, I need the way to safely transfer a nested
virJSON object out of its parent container for independent use,
even after the parent is freed.

* src/util/virjson.h (virJSONValueObjectRemoveKey): New function.
(_virJSONObject, _virJSONArray): Use correct type.
* src/util/virjson.c (virJSONValueObjectRemoveKey): Implement it.
* src/libvirt_private.syms (virjson.h): Export it.
* tests/jsontest.c (mymain): Test it.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-13 15:15:54 -06:00
Gene Czarcinski
ccff335f83 Support for static routes on a virtual bridge
network: static route support for <network>

This patch adds the <route> subelement of <network> to define a static
route.  the address and prefix (or netmask) attribute identify the
destination network, and the gateway attribute specifies the next hop
address (which must be directly reachable from the containing
<network>) which is to receive the packets destined for
"address/(prefix|netmask)".

These attributes are translated into an "ip route add" command that is
executed when the network is started. The command used is of the
following form:

  ip route add <address>/<prefix> via <gateway> \
               dev <virbr-bridge> proto static metric <metric>

Tests are done to validate that the input data are correct.  For
example, for a static route ip definition, the address must be a
network address and not a host address.  Additional checks are added
to ensure that the specified gateway is directly reachable via this
network (i.e. that the gateway IP address is in the same subnet as one
of the IP's defined for the network).

prefix='0' is supported for both family='ipv4' address='0.0.0.0'
netmask='0.0.0.0' or prefix='0', and for family='ipv6' address='::',
prefix=0', although care should be taken to not override a desired
system default route.

Anytime an attempt is made to define a static route which *exactly*
duplicates an existing static route (for example, address=::,
prefix=0, metric=1), the following error message will be sent to
syslog:

    RTNETLINK answers: File exists

This can be overridden by decreasing the metric value for the route
that should be preferred, or increasing the metric for the route that
shouldn't be preferred (and is thus in place only in anticipation that
the preferred route may be removed in the future).  Caution should be
used when manipulating route metrics, especially for a default route.

Note: The use of the command-line interface should be replaced by
direct use of libnl so that error conditions can be handled better.  But,
that is being left as an exercise for another day.

Signed-off-by: Gene Czarcinski <gene@czarc.net>
Signed-off-by: Laine Stump <laine@laine.org>
2013-05-13 16:14:40 -04:00
Daniel P. Berrange
3407e3b3a2 Don't overwrite useful message when creating macvlan fails
Currently we report a bogus error message when macvlan
creation fails:

error: Failed to start domain migtest
error: operation failed: Unable to create macvlan device

With this removed, we see the real error:

error: Failed to start domain migtest
error: Unable to get index for interface p31p1: No such device

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 17:32:55 +01:00
Daniel P. Berrange
8845d8dfa3 Remove & ban use of select() for waiting for I/O
Use of the select() system call is inherantly dangerous since
applications will hit a buffer overrun if any FD number exceeds
the size of the select set size (typically 1024). Replace the
two uses of select() with poll() and use cfg.mk to ban any
future use of select().

NB: This changes the phyp driver so that it uses an infinite
timeout, instead of busy-waiting for 1ms at a time.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 17:32:43 +01:00
Jim Fehlig
bbe97ae968 Fix starting domains when kernel has no cgroups support
Found that I was unable to start existing domains after updating
to a kernel with no cgroups support

  # zgrep CGROUP /proc/config.gz
  # CONFIG_CGROUPS is not set
  # virsh start test
  error: Failed to start domain test
  error: Unable to initialize /machine cgroup: Cannot allocate memory

virCgroupPartitionNeedsEscaping() correctly returns errno (ENOENT) when
attempting to open /proc/cgroups on such a system, but it was being
dropped in virCgroupSetPartitionSuffix().

Change virCgroupSetPartitionSuffix() to propagate errors returned by
its callees.  Also check for ENOENT in qemuInitCgroup() when determining
if cgroups support is available.
2013-05-13 09:27:46 -06:00
Daniel P. Berrange
0ced83dcfb Escaping leading '.' in cgroup names
Escaping a leading '.' with '_' in the cgroup names

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 14:28:46 +01:00
Daniel P. Berrange
8aabd597b3 Add a helper API for setting up a NBD device with qemu-nbd
Add a virFileNBDDeviceAssociate method, which given a filename
will setup a NBD device, using qemu-nbd as the server.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 13:15:19 +01:00
Daniel P. Berrange
1eeff53d7d Fix error handling of readdir() in virFileLoopDeviceOpen
To correctly handle errors from readdir() you must set 'errno'
to zero before invoking it & check its value afterwards to
distinguish error from EOF.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 13:15:19 +01:00
Han Cheng
7486584c9f utils: util functions for scsi hostdev
This patch adds util functions for scsi hostdev.

Signed-off-by: Han Cheng <hanc.fnst@cn.fujitsu.com>
Signed-off-by: Osier Yang <jyang@redhat.com>
2013-05-13 18:40:50 +08:00
Osier Yang
b7ab719528 util: Honor the passed sysfs_prefix
The helper works for default sysfs_prefix, but for user specified
prefix, it doesn't work. (Detected when writing test cases. A later
patch will add the test cases for fc_host).
2013-05-13 17:19:54 +08:00
Osier Yang
1a59ae919d util: Update the comment for virGetFCHostNameByWWN
The returned result is something like "host5" acutally.
2013-05-13 17:18:52 +08:00
Osier Yang
c56c273be6 util: Change virIsCapable* to return bool
Function name with "aIsB" generally means its return value is
in Bi-state (true/false).
2013-05-13 17:17:26 +08:00
Osier Yang
b595588fef util: Don't miss the slash in constructed path
In case of the caller can pass a "prefix" (or "sysfs_prefix")
without the trailing slash, and Unix-Like system always eats
up the redundant "slash" in the filepath, let's add it explicitly.
2013-05-13 17:14:51 +08:00
Osier Yang
e106c0112a util: Fix regression introduced by commit 4360a09844
Which refactored the old code, and introduced new helper
virIsCapableVport, but the path for checking with access() is not
correctly constructed.
2013-05-13 17:12:55 +08:00
Osier Yang
b76284afb1 util: Fix regression of wwn reading
Introduced by commit 244ce462e2, which refactored the helper for wwn
reading, however, it forgot to change the old "strndup" and "sizeof(buf)",
"sizeof(buf)" operates on the fixed length array ("buf") in the old code,
but now "buf" is a pointer.

Before the fix:

% virsh nodedev-dumpxml scsi_host5
<device>
  <name>scsi_host5</name>
  <parent>pci_0000_04_00_1</parent>
  <capability type='scsi_host'>
    <host>5</host>
    <capability type='fc_host'>
      <wwnn>2001001b</wwnn>
      <wwpn>2101001b</wwpn>
      <fabric_wwn>2001000d</fabric_wwn>
    </capability>
  </capability>
</device>

With the fix:

% virsh nodedev-dumpxml scsi_host5
<device>
  <name>scsi_host5</name>
  <parent>pci_0000_04_00_1</parent>
  <capability type='scsi_host'>
    <host>5</host>
    <capability type='fc_host'>
      <wwnn>0x2001001b32a9da4e</wwnn>
      <wwpn>0x2101001b32a9da4e</wwpn>
      <fabric_wwn>0x2001000dec9877c1</fabric_wwn>
    </capability>
  </capability>
</device>
2013-05-13 17:10:59 +08:00
Eric Blake
d34ef01779 build: fix use of mmap
Commit bfe7721d introduced a regression, but only on platforms
like FreeBSD that lack posix_fallocate and where mmap serves as
a nice fallback for safezero.

util/virfile.c: In function 'safezero':
util/virfile.c:837: error: 'PROT_READ' undeclared (first use in this function)

* src/util/virutil.c (includes): Move use of <sys/mman.h>...
* src/util/virfile.c (includes): ...to the file that uses mmap.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-10 20:52:57 -06:00
Daniel P. Berrange
69c6a58a1d Add a virGetLastErrorMessage() function
Apps using libvirt will often have code like

   if (virXXXX() < 0) {
      virErrorPtr err = virGetLastError();
      fprintf(stderr, "Something failed: %s\n",
              err && err->message ? err->message :
              "unknown error");
      return -1;
   }

Checking for a NULL error object or message leads to very
verbose code. A virGetLastErrorMessage() helper from libvirt
can simplify this to

   if (virXXXX() < 0) {
      fprintf(stderr, "Something failed: %s\n",
              virGetLastErrorMessage());
      return -1;
   }

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-10 19:57:18 +01:00
Roman Bogorodskiy
95934171fb portability: fix virNetDevSetMAC and virNetDevExists on BSD
- provide virNetDevSetMAC() implementation based on SIOCSIFLLADDR
  ioctl.
- adjust virNetDevExists() to check for ENXIO error because
  FreeBSD throws it when device doesn't exist

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-10 11:13:21 -06:00
Laine Stump
bfe7721d50 util: move virFile* functions from virutil.c to virfile.c
These all existed before virfile.c was created, and for some reason
weren't moved.

This is mostly straightfoward, although the syntax rule prohibiting
write() had to be changed to have an exception for virfile.c instead
of virutil.c.

This movement pointed out that there is a function called
virBuildPath(), and another almost identical function called
virFileBuildPath(). They really should be a single function, which
I'll take care of as soon as I figure out what the arglist should look
like.
2013-05-10 13:09:30 -04:00
Laine Stump
a2c1bedbd8 util: fix virFileOpenAs return value and resulting error logs
This resolves:

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

The first problem was that virFileOpenAs was returning fd (-1) in one
of the error cases rather than ret (-errno), so the caller thought
that the error was EPERM rather than ENOENT.

The second problem was that some log messages in the general purpose
qemuOpenFile() function would always say "Failed to create" even if
the caller hadn't included O_CREAT (i.e. they were trying to open an
existing file).

This fixes virFileOpenAs to jump down to the error return (which
returns ret instead of fd) in the previously mentioned incorrect
failure case of virFileOpenAs(), removes all error logging from
virFileOpenAs() (since the callers report it), and modifies
qemuOpenFile to appropriately use "open" or "create" in its log
messages.

NB: I seriously considered removing logging from all callers of
virFileOpenAs(), but there is at least one case where the caller
doesn't want virFileOpenAs() to log any errors, because it's just
going to try again (qemuOpenFile()). We can't simply make a silent
variation of virFileOpenAs() though, because qemuOpenFile() can't make
the decision about whether or not it wants to retry until after
virFileOpenAs() has already returned an error code.

Likewise, I also considered changing virFileOpenAs() to return -1 with
errno set on return, and may still do that, but only as a separate
patch, as it obscures the intent of this patch too much.
2013-05-10 13:09:25 -04:00
Daniel P. Berrange
4a044d0256 Separate internal node suspend APIs from public API
The individual hypervisor drivers were directly referencing
APIs in virnodesuspend.c in their virDriverPtr struct. Separate
these methods, so there is always a wrapper in the hypervisor
driver. This allows the unused virConnectPtr args to be removed
from the virnodesuspend.c file. Again this will ensure that
ACL checks will only be performed on invocations that are
directly associated with public API usage.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:47 +01:00
Daniel P. Berrange
ead630319d Separate virGetHostname() API contract from driver APIs
Currently the virGetHostname() API has a bogus virConnectPtr
parameter. This is because virtualization drivers directly
reference this API in their virDriverPtr tables, tieing its
API design to the public virConnectGetHostname API design.

This also causes problems for access control checks since
these must only be done for invocations from the public
API, not internal invocation.

Remove the bogus virConnectPtr parameter, and make each
hypervisor driver provide a dedicated function for the
driver API impl. This will allow access control checks
to be easily inserted later.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:47 +01:00
Daniel P. Berrange
979e9c56a7 Include process start time when doing polkit checks
Since PIDs can be reused, polkit prefers to be given
a (PID,start time) pair. If given a PID on its own,
it will attempt to lookup the start time in /proc/pid/stat,
though this is subject to races.

It is safer if the client app resolves the PID start
time itself, because as long as the app has the client
socket open, the client PID won't be reused.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:45 +01:00
Daniel P. Berrange
b1d753fe40 Rename "security context" to "selinux context"
There are various methods named "virXXXXSecurityContext",
which are specific to SELinux. Rename them all to
"virXXXXSELinuxContext". They will still raise errors at
runtime if SELinux is not compiled in

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:21:01 +01:00
Eric Blake
6b74a9f5d9 string: make VIR_STRDUP easier to use
While reviewing proposed VIR_STRDUP conversions, I've already noticed
several places that do:

if (str && VIR_STRDUP(dest, str) < 0)

which can be simplified by allowing str to be NULL (something that
strdup() doesn't allow).  Meanwhile, code that wants to ensure a
non-NULL dest regardless of the source can check for <= 0.

Also, make it part of the VIR_STRDUP contract that macro arguments
are evaluated exactly once.

* src/util/virstring.h (VIR_STRDUP, VIR_STRDUP_QUIET, VIR_STRNDUP)
(VIR_STRNDUP_QUIET): Improve contract.
* src/util/virstring.c (virStrdup, virStrndup): Change return
conventions.
* docs/hacking.html.in: Document this.
* HACKING: Regenerate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-07 13:21:31 -06:00
Eric Blake
ddcfc5492a alloc: make VIR_APPEND_ELEMENT safer
VIR_APPEND_ELEMENT(array, size, elem) was not safe if the expression
for 'size' had side effects.  While no one in the current code base
was trying to pass side effects, we might as well be robust and
explicitly document our intentions.

* src/util/viralloc.c (virInsertElementsN): Add special case.
* src/util/viralloc.h (VIR_APPEND_ELEMENT): Use it.
(VIR_ALLOC, VIR_ALLOC_N, VIR_REALLOC_N, VIR_EXPAND_N)
(VIR_RESIZE_N, VIR_SHRINK_N, VIR_INSERT_ELEMENT)
(VIR_DELETE_ELEMENT, VIR_ALLOC_VAR, VIR_FREE): Document
which macros are safe in the presence of side effects.
* docs/hacking.html.in: Document this.
* HACKING: Regenerate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-07 13:21:31 -06:00
Ján Tomko
dcea5a492f get rid of virBufferAsprintf where possible
Use virBufferAddLit or virBufferAddChar instead.
2013-05-07 17:38:58 +02:00
Michal Privoznik
c3abb5c459 virstring: Introduce VIR_STRDUP and VIR_STRNDUP
The code adaptation is not done right now, but in subsequent patches.
Hence I am not implementing syntax-check rule as it would break
compilation. Developers are strongly advised to use these new macros.
They are similar to VIR_ALLOC() logic: VIR_STRDUP(dst, src) returns zero
on success, -1 otherwise. In case you don't want to report OOM error,
use the _QUIET variant of a macro.
2013-05-05 12:08:54 +02:00
Eric Blake
22d12905e6 build: avoid non-portable cast of pthread_t
POSIX says pthread_t is opaque.  We can't guarantee if it is scaler
or a pointer, nor what size it is; and BSD differs from Linux.
We've also had reports of gcc complaining on attempts to cast it,
if we use a cast to the wrong type (for example, pointers have to be
cast to void* or intptr_t before being narrowed; while casting a
function return of scalar pthread_t to void* triggers a different
warning).

Give up on casts, and use unions to get at decent bits instead.  And
rather than futz around with figuring which 32 bits of a potentially
64-bit pointer are most likely to be unique, convert the rest of
the code base to use 64-bit values when using a debug id.

Based on a report by Guido Günther against kFreeBSD, but with a
fix that doesn't regress commit 4d970fd29 for FreeBSD.

* src/util/virthreadpthread.c (virThreadSelfID, virThreadID): Use
union to get at a decent bit representation of thread_t bits.
* src/util/virthread.h (virThreadSelfID, virThreadID): Alter
signature.
* src/util/virthreadwin32.c (virThreadSelfID, virThreadID):
Likewise.
* src/qemu/qemu_domain.h (qemuDomainJobObj): Alter type of owner.
* src/qemu/qemu_domain.c (qemuDomainObjTransferJob)
(qemuDomainObjSetJobPhase, qemuDomainObjReleaseAsyncJob)
(qemuDomainObjBeginNestedJob, qemuDomainObjBeginJobInternal): Fix
clients.
* src/util/virlog.c (virLogFormatString): Likewise.
* src/util/vireventpoll.c (virEventPollInterruptLocked):
Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-03 06:30:22 -06:00
Eric Blake
05f79a3894 build: fix mingw build of virprocess.c
Commit 776d49f4 added a static function that is only called
conditionally; leading to this compile error on mingw:

  CC       libvirt_util_la-virprocess.lo
../../src/util/virprocess.c:624:26: error: 'struct rlimit' declared inside parameter list [-Werror]
../../src/util/virprocess.c:624:26: error: its scope is only this definition or declaration, which is probably not what you want [-Werror]
../../src/util/virprocess.c:622:1: error: 'virProcessPrLimit' defined but not used [-Werror=unused-function]

* src/util/virprocess.c (virProcessPrLimit): Only declare
virProcessPrLimit when used.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 15:46:19 -06:00
Eric Blake
348ac06133 build: fix FreeBSD build
Commit 7c9a2d88 cleaned up too many headers; FreeBSD builds
failed due to:

util/virutil.c:556: warning: implicit declaration of function 'canonicalize_file_name'

(Not sure which Linux header leaked this declaration, but gnulib
only guarantees it in stdlib.h)

libvirt.c:956: warning: implicit declaration of function 'virGetUserConfigDirectory'

(Here, a build on Linux was picking up virutil.h indirectly via
one of the conditional driver headers, where that driver was not
being built on my FreeBSD setup)

* src/util/virutil.c (includes): Need <stdlib.h> for
canonicalize_file_name.
* src/libvirt.c (includes): Use "virutil.h" unconditionally,
rather than relying on conditional indirect inclusion.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 15:41:21 -06:00
Eric Blake
25ae3d3015 build: avoid useless virAsprintf
virAsprintf(&foo, "%s", bar) is wasteful compared to
foo = strdup(bar) (or eventually, VIR_STRDUP(foo, bar),
but one thing at a time...).

Noticed while reviewing Laine's attempt to clean up broken
qemu:///session.

* cfg.mk (sc_prohibit_asprintf): Enhance rule.
* src/esx/esx_storage_backend_vmfs.c
(esxStorageBackendVMFSVolumeLookupByKey): Fix offender.
* src/network/bridge_driver.c (networkStateInitialize): Likewise.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopDHCPOpen):
Likewise.
* src/storage/storage_backend_sheepdog.c
(virStorageBackendSheepdogRefreshVol): Likewise.
* src/util/vircgroup.c (virCgroupAddTaskStrController): Likewise.
* src/util/virdnsmasq.c (addnhostsAdd): Likewise.
* src/xen/block_stats.c (xenLinuxDomainDeviceID): Likewise.
* src/xen/xen_driver.c (xenUnifiedConnectOpen): Likewise.
* tools/virsh.c (vshGetTypedParamValue): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 13:35:26 -06:00
Michal Privoznik
7c9a2d88cd virutil: Move string related functions to virstring.c
The source code base needs to be adapted as well. Some files
include virutil.h just for the string related functions (here,
the include is substituted to match the new file), some include
virutil.h without any need (here, the include is removed), and
some require both.
2013-05-02 16:56:55 +02:00
Guido Günther
ca75c44310 virInitctlRequest: unbreak make syntax check
introduced by dcf97846d5

To trigger this cppi needs to be installed.
2013-05-02 10:20:33 +02:00
Guido Günther
a1365d7351 virInitctlRequest: unbreak make syntax check
introduced by dcf97846d5
2013-05-02 09:22:41 +02:00
Guido Günther
dcf97846d5 virInitctlRequest: Don't hardcode 384 bytes size
When MAXHOSTNAMELEN is set we have to take it's value into account.
Otherwise the build fails on kFreeBSD (FreeBSD kernel and GNU userland)
2013-05-02 08:18:42 +02:00
Laine Stump
e482693b24 pci: autolearn name of stub driver, remove from arglist
virPCIDeviceReattach and virPCIDeviceUnbindFromStub (called by
virPCIDeviceReattach) had previously required the name of the stub
driver as input. This is unnecessary, because the name of the driver
the device is currently bound to can be found by looking at the link:

  /sys/bus/pci/dddd:bb:ss.ff/driver

Instead of requiring that the name of the expected stub driver name
and only unbinding if that one name is matched, we no longer take a
driver name in the arglist for either of these
functions. virPCIDeviceUnbindFromStub just compares the name of the
currently bound driver to a list of "well known" stubs (right now
contains "pci-stub" and "vfio-pci" for qemu, and "pciback" for xen),
and only performs the unbind if it's one of those devices.

This allows virsh nodedevice-reattach to work properly across a
libvirtd restart, and fixes a couple of cases where we were
erroneously still hard-coding "pci-stub" as the drive name.

For some unknown reason, virPCIDeviceReattach had been calling
modprobe on the stub driver prior to unbinding the device. This was
problematic because we no longer know the name of the stub driver in
that function. However, it is pointless to probe for the stub driver
at that time anyway - because the device is bound to the stub driver,
we are guaranteed that it is already loaded, and so that call to
modprobe has been removed.
2013-05-02 02:09:29 -04:00
Eric Blake
7fecc8e36f build: fix cygwin build in virnetdev
On cygwin, compilation failed because SIOCSIFHWADDR is undefined.

* src/util/virnetdev.c (virNetDevSetMAC): Cygwin can query but not
set mac address.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 15:16:22 -06:00
Roman Bogorodskiy
5295e35f58 portability: handle ifreq differences in virnetdev
FreeBSD (and maybe other BSDs) have different member
names in struct ifreq when compared to Linux, such as:

 - uses ifr_data instead of ifr_newname for setting
   interface names
 - uses ifr_index instead of ifr_ifindex for interface
   index

Also, add a check for SIOCGIFHWADDR for virNetDevValidateConfig().

Use AF_LOCAL if AF_PACKET is not available.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 09:42:22 -06:00
Eric Blake
b376dea91f build: mark conditionally unused variables
These fixes solve a compilation failure on FreeBSD:

util/virnetdevtap.c: In function 'virNetDevTapGetName':
util/virnetdevtap.c:56: warning: unused parameter 'tapfd' [-Wunused-parameter]
util/virnetdevtap.c:56: warning: unused parameter 'ifname' [-Wunused-parameter]

* src/util/virnetdevtap.c (virNetDevTapGetName): Add attributes
when TUNGETIFF is not present.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 08:21:26 -06:00
Paolo Bonzini
740d98a17d virnetdevtap: add virNetDevTapGetName
This will be used on a tap file descriptor returned by the bridge helper
to populate the <target> element, because the helper does not provide
the interface name.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2013-04-26 15:37:15 -06:00
Laine Stump
776d49f492 util: new virCommandSetMax(MemLock|Processes|Files)
This patch adds two sets of functions:

1) lower level virProcessSet*() functions that will immediately set
the RLIMIT_MEMLOCK. RLIMIT_NPROC, or RLIMIT_NOFILE of either the
current process (using setrlimit()) or any other process (using
prlimit()). "current process" is indicated by passing a 0 for pid.

2) functions for virCommand* that will setup a virCommand object to
set those limits at a later time just after it has forked a new
process, but before it execs the new program.

configure.ac has prlimit and setrlimit added to the list of functions
to check for, and the low level functions log an "unsupported" error)
on platforms that don't support those functions.
2013-04-26 10:23:46 -04:00
Daniel P. Berrange
f3662737b1 Do proper escaping of cgroup resource partitions
If a user cgroup name begins with "cgroup.", "_" or with any of
the controllers from /proc/cgroups followed by a dot, then they
need to be prefixed with a single underscore. eg if there is
an object "cpu.service", then this would end up as "_cpu.service"
in the cgroup filesystem tree, however, "waldo.service" would
stay "waldo.service", at least as long as nobody comes up with
a cgroup controller called "waldo".

Since we require a '.XXXX' suffix on all partitions, there is
no scope for clashing with the kernel 'tasks' and 'release_agent'
files.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-26 13:52:02 +01:00
Daniel P. Berrange
9ddfe7eea6 Ensure all cgroup partitions have a suffix of ".partition"
If the partition named passed in the XML does not already have
a suffix, ensure it gets a '.partition' added to each component.
The exceptions are /machine, /user and /system which do not need
to have a suffix, since they are fixed partitions at the top
level.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-26 13:52:02 +01:00
Daniel P. Berrange
824e86e723 Change VM cgroup suffix from '{lxc,qemu}.libvirt' to 'libvirt-{lxc,qemu}'
Recently we changed to create VM cgroups with the naming pattern
$VMNAME.$DRIVER.libvirt. Following discussions with the systemd
community it was decided that only having a single '.' in the
names is preferrable. So this changes the naming scheme to be
$VMNAME.libvirt-$DRIVER. eg for LXC 'mycontainer.libvirt-lxc' or
for KVM 'myvm.libvirt-qemu'.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-26 13:52:02 +01:00
Laine Stump
b210208f97 util: new function virPCIDeviceGetVFIOGroupDev
Given a virPCIDevice, this function returns the path for the device
that controls the vfio group the device belongs to,
e.g. "/dev/vfio/15".
2013-04-25 21:28:43 -04:00
Laine Stump
be64199e17 pci: keep a stubDriver in each virPCIDevice
This can be set when the virPCIDevice is created and placed on a list,
then used later when traversing the list to determine which stub
driver to bind/unbind for managed devices.

The existing Detach and Attach functions' signatures haven't been
changed (they still accept a stub driver name in the arg list), but if
the arg list has NULL for stub driver and one is available in the
device's object, that will be used. (we may later deprecate and remove
the arg from those functions).
2013-04-25 21:28:10 -04:00
Eric Blake
1fbf190554 build: avoid unsafe functions in libgen.h
POSIX says that both basename() and dirname() may return static
storage (aka they need not be thread-safe); and that they may but
not must modify their input argument.  Furthermore, <libgen.h>
is not available on all platforms.  For these reasons, you should
never use these functions in a multi-threaded library.

Gnulib instead recommends a way to avoid the portability nightmare:
gnulib's "dirname.h" provides useful thread-safe counterparts.  The
obvious dir_name() and base_name() are GPL (because they malloc(),
but call exit() on failure) so we can't use them; but the LGPL
variants mdir_name() (malloc's or returns NULL) and last_component
(always points into the incoming string without modifying it,
differing from basename semantics only on corner cases like the
empty string that we shouldn't be hitting in the first place) are
already in use in libvirt.  This finishes the swap over to the safe
functions.

* cfg.mk (sc_prohibit_libgen): New rule.
* src/util/vircgroup.c: Fix offenders.
* src/parallels/parallels_storage.c (parallelsPoolAddByDomain):
Likewise.
* src/parallels/parallels_network.c (parallelsGetBridgedNetInfo):
Likewise.
* src/node_device/node_device_udev.c (udevProcessSCSIHost)
(udevProcessSCSIDevice): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskDeleteVol): Likewise.
* src/util/virpci.c (virPCIGetDeviceAddressFromSysfsLink):
Likewise.
* src/util/virstoragefile.h (_virStorageFileMetadata): Avoid false
positive.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-25 14:47:01 -06:00
Osier Yang
148edcce66 util: Error out if the numa nodeset is out of range
Instead of a silent warning, it's better to error out if the
numa nodeset is out of range. Just like for numa node larger
than NUMA_NUM_NODES.
2013-04-24 23:23:31 +08:00
Peter Krempa
fa006c4fdd qemu: Fix setting of memory tunables
Refactoring done in 19c6ad9ac7 didn't
correctly take into account the order cgroup limit modification needs to
be done in. This resulted into errors when decreasing the limits.

The operations need to take place in this order:

decrease hard limit
change swap hard limit

or

change swap hard limit
increase hard limit

This patch also fixes the check if the hard_limit is less than
swap_hard_limit to print better error messages. For this purpose I
introduced a helper function virCompareLimitUlong to compare limit
values where value of 0 is equal to unlimited. Additionally the check is
now applied also when the user does not provide all of the tunables
through the API and in that case the currently set values are used.

This patch resolves:
https://bugzilla.redhat.com/show_bug.cgi?id=950478
2013-04-23 07:10:56 +02:00
Jiri Denemark
fd2e55302b logging: Make log regexp more compact (and readable) 2013-04-22 20:13:40 +02:00
Gene Czarcinski
bd7c7c1b3c create virSocketAddrGetIpPrefix utility function
Create the utility function virSocketAddrGetIpPrefix() to
determine the prefix for this network.  The code in this
function was adapted from virNetworkIpDefPrefix().

Update virNetworkIpDefPrefix() in src/conf/network_conf.c
to use the new utility function.

Signed-off-by: Gene Czarcinski <gene@czarc.net>
2013-04-22 14:10:53 -04:00
Eric Blake
1bf25ba249 docs: fix usage of 'onto'
http://www.uhv.edu/ac/newsletters/writing/grammartip2009.07.01.htm
(and several other sites) give hints that 'onto' is best used if
you can also add 'up' just before it and still make sense. In many
cases in the code base, we really want the two-word form, or even
a simplification to just 'on' or 'to'.

* docs/hacking.html.in: Use correct 'on to'.
* python/libvirt-override.c: Likewise.
* src/lxc/lxc_controller.c: Likewise.
* src/util/virpci.c: Likewise.
* daemon/THREADS.txt: Use simpler 'on'.
* docs/formatdomain.html.in: Better usage.
* docs/internals/rpc.html.in: Likewise.
* src/conf/domain_event.c: Likewise.
* src/rpc/virnetclient.c: Likewise.
* tests/qemumonitortestutils.c: Likewise.
* HACKING: Regenerate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-19 14:31:16 -06:00
Paolo Bonzini
5c1cfea403 util: allow using virCommandAllowCap with setuid helpers
When running unprivileged, virSetUIDGIDWithCaps will fail because it
tries to add the requested capabilities to the permitted and effective
sets.

Detect this case, and invoke the child with cleared permitted and
effective sets.  If it is a setuid program, it will get them.

Some care is needed also because you cannot drop capabilities from the
bounding set without CAP_SETPCAP.  Because of that, ignore errors from
setting the bounding set.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2013-04-18 14:52:23 -06:00
Paolo Bonzini
658718454a util: simplify virSetUIDGIDWithCaps
The need_prctl variable is not really needed.  If it is false,
capng_apply will be called twice with the same set, causing
a little extra work but no problem.  This keeps the code a bit
simpler.

It is also clearer to invoke capng_apply(CAPNG_SELECT_BOUNDS)
separately, to make sure it is done while we have CAP_SETPCAP.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2013-04-18 14:33:28 -06:00
Osier Yang
09d2547f96 qemu: Allow the disk wwn to have "0x" prefix
The recent qemu requires "0x" prefix for the disk wwn, this patch
changes virValidateWWN to allow the prefix, and prepend "0x" if
it's not specified. E.g.

qemu-kvm: -device scsi-hd,bus=scsi0.0,channel=0,scsi-id=0,lun=0,\
drive=drive-scsi0-0-0-0,id=scsi0-0-0-0,wwn=6000c60016ea71ad:
Property 'scsi-hd.wwn' doesn't take value '6000c60016ea71ad'

Though it's a qemu regression, but it's nice to allow the prefix,
and doesn't hurt for us to always output "0x".
2013-04-17 23:05:56 +08:00
Osier Yang
2d25fd4f41 cleanup: Don't include libvirt/libvirt.h
Which is already included by "internal.h", later patch will add
syntax-check to avoid it.
2013-04-17 15:50:53 +08:00
Osier Yang
bc95be5dea cleanup: Remove the duplicate header
Detected by a simple Shell script:

for i in $(git ls-files -- '*.[ch]'); do
    awk 'BEGIN {
        fail=0
    }
    /# *include.*\.h/{
        match($0, /["<][^">]*[">]/)
        arr[substr($0, RSTART+1, RLENGTH-2)]++
    }
    END {
        for (key in arr) {
            if (arr[key] > 1) {
                fail=1
                printf("%d %s\n", arr[key], key)
            }
        }
        if (fail == 1)
            exit 1
    }' $i

    if test $? != 0; then
        echo "Duplicate header(s) in $i"
    fi
done;

A later patch will add the syntax-check to avoid duplicate
headers.
2013-04-17 15:49:35 +08:00
Stefan Berger
0cb171f60f Fix compilation error in util/vircgroup.c
Fix the error

util/vircgroup.c: In function 'virCgroupNewDomainPartition':
util/vircgroup.c:1299:11: error: declaration of 'dirname' shadows a global declaration [-Werror=shadow]


Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2013-04-16 08:16:37 -04:00
John Ferlan
d94a3cfcfb Fix build breaker with ATTRIBUTE_NONNULL defs
Using "./autogen.sh --system lv_cv_static_analysis=yes" for my daily
Coverity builds resulted in the following error when building:

In file included from util/vircgrouppriv.h:32:0,
                 from util/vircgroup.c:44:
util/vircgroup.h:59:5: error: nonnull argument with out-of-range operand number (argument 1, operand 5)
util/vircgroup.h:74:5: error: nonnull argument references non-pointer operand (argument 1, operand 4)
make[3]: *** [libvirt_util_la-vircgroup.lo] Error 1
make[3]: Leaving directory `/home/jferlan/libvirt.cov.curr/src'
make[2]: *** [all] Error 2
make[2]: Leaving directory `/home/jferlan/libvirt.cov.curr/src'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/jferlan/libvirt.cov.curr'
make: *** [all] Error 2
2013-04-16 07:17:00 -04:00
Daniel P. Berrange
e7d8ab016b Add support for perf_event and net_cls cgroup controllers
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:32 +01:00
Daniel P. Berrange
1da631ecf3 Add an API for re-mounting cgroups, to isolate the process location
Add a virCgroupIsolateMount method which looks at where the
current process is place in the cgroups (eg /system/demo.lxc.libvirt)
and then remounts the cgroups such that this sub-directory
becomes the root directory from the current process' POV.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:32 +01:00
Daniel P. Berrange
83336118db Track symlinks for co-mounted cgroup controllers
If a cgroup controller is co-mounted with another, eg

   /sys/fs/cgroup/cpu,cpuacct

Then it is a requirement that there exist symlinks at

   /sys/fs/cgroup/cpu
   /sys/fs/cgroup/cpuacct

pointing to the real mount point. Add support to virCgroupPtr
to detect and track these symlinks

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:32 +01:00
Daniel P. Berrange
767596bdb4 Remove non-functional code for setting up non-root cgroups
The virCgroupNewDriver method had a 'bool privileged' param.
If a false value was ever passed in, it would simply not
work, since non-root users don't have any privileges to create
new cgroups. Just delete this broken code entirely and make
the QEMU driver skip cgroup setup in non-privileged mode

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
aa8604dd45 Add a new virCgroupNewPartition for setting up resource partitions
A resource partition is an absolute cgroup path, ignoring the
current process placement. Expose a virCgroupNewPartition API
for constructing such cgroups

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
109554d714 Cleanup if creating cgroup directories fails
Currently if virCgroupMakeGroup fails, we can get in a situation
where some controllers have been setup, but others not. Ensure
we call virCgroupRemove to remove what we've done upon failure

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
854a004fd6 Add misc extra debugging into cgroups code
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
8d1c141a8d Refactor cgroups internal data structures
Currently the virCgroupPtr struct contains 3 pieces of
information

 - path - path of the cgroup, relative to current process'
   cgroup placement
 - placement - current process' placement in each controller
 - mounts - mount point of each controller

When reading/writing cgroup settings, the path & placement
strings are combined to form the file path. This approach
only works if we assume all cgroups will be relative to
the current process' cgroup placement.

To allow support for managing cgroups at any place in the
heirarchy a change is needed. The 'placement' data should
reflect the absolute path to the cgroup, and the 'path'
value should no longer be used to form the paths to the
cgroup attribute files.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
04c18d25f1 Rename virCgroupForXXX to virCgroupNewXXX
Rename all the virCgroupForXXX methods to use the form
virCgroupNewXXX since they are all constructors. Also
make sure the output parameter is the last one in the
list, and annotate all pointers as non-null. Fix up
all callers, and make sure they use true/false not 0/1
for the boolean parameters

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
f0e5f92434 Pull definition of structs out of vircgroup.c to vircgrouppriv.h
The definition of structs for cgroups are kept in vircgroup.c since
they are intended to be private from users of the API. To enable
effective testing, however, they need to be accessible. To address
the latter issue, without compronmising the former, this introduces
a new vircgrouppriv.h file to hold the struct definitions.

To prevent other files including this private header, it requires
that __VIR_CGROUP_ALLOW_INCLUDE_PRIV_H__ be defined before inclusion

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
c9b8cdfec1 Add missing param to virCgroupForDriver stub
The virCgroupForDriver method recently gained an 'int controllers'
parameter, but the stub impl did not

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
035cdaa00b Introduce a virFileDeleteTree method
Introduce a method virFileDeleteTree for recursively deleting
an entire directory tree

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:31 +01:00
Daniel P. Berrange
3f85de5292 Fix signature of dummy virNetlinkCommand stub
The second param of virNetlinkCommand should be
struct nlmsghdr, not unsigned char.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:30 +01:00
Daniel P. Berrange
fd856af62b Add empty stub for virThreadCancel on Win32
Win32 does not like undefined symbols, so define an
empty virThreadCancel impl.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-15 17:35:30 +01:00
Osier Yang
b1ea781eaa Use unsigned int instead of unsigned
Though they are the same thing, mixed use of them is uncomfortable.
"unsigned" is used a lot in old codes, this just tries to change the
ones in utils.
2013-04-15 23:07:08 +08:00
Stefan Berger
06ba4bff91 Helper functions for host TPM support
Implement helper function to create the TPM's sysfs cancel file.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
Reviewed-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
Tested-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
2013-04-12 16:55:45 -04:00
Stefan Berger
069219577b Add function to find a needle in a string array
Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
Reviewed-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
Tested-by: Corey Bryant <coreyb@linux.vnet.ibm.com>
2013-04-12 16:55:45 -04:00
Osier Yang
cc7da958c8 Cleanup: Change datatype of origstate's members to boolean
Members of struct virPCIDevice are changed together.
2013-04-11 11:35:17 +08:00
Osier Yang
9fda2f5cc9 Cleanup: Change datatype of hostdev->managed to boolean 2013-04-11 11:31:02 +08:00
Laine Stump
9579b6bc20 Fix crash in virNetDevGetVirtualFunctions
Commit 9a3ff01d7f (which was ACKed at
the end of January, but for some reason didn't get pushed until during
the 1.0.4 freeze) fixed the logic in virPCIGetVirtualFunctions().
Unfortunately, a typo in the fix (replacing VIR_REALLOC_N with
VIR_ALLOC_N during code movement) caused not only a memory leak, but
also resulted in most of the elements of the result array being
replaced with NULL. virNetDevGetVirtualFunctions() assumed (and I think
rightly so) that virPCIGetVirtualFunctions() wouldn't return any NULL
elements in the array, so it ended up segfaulting.

This was found when attempting to use a virtual network with an
auto-created pool of SRIOV VFs, e.g.:

    <forward mode='hostdev' managed='yes'>
      <pf dev='eth4'/>
    </forward>

(the pool of PCI addresses is discovered by calling
virNetDevGetVirtualFunctions() on the PF dev).
2013-04-09 14:26:12 -04:00
Milos Vyletel
396c4d34f8 Generate RFC4122 compliant UUIDs
Even though http://libvirt.org/formatdomain.html#elementsMetadata
states that it requires RFC4122 compliance UUIDs that are generated
by virUUIDGenerate() are not. Following patch modifies generated
UUIDs to conform to rules described in RFC.

Signed-off-by: Milos Vyletel <milos.vyletel@sde.cz>
2013-04-08 13:18:07 -06:00
Daniel P. Berrange
dca927c82f Rename virCgroupMounted to virCgroupHasController & make it more robust
The virCgroupMounted method is badly named, since a controller can be
mounted, but disabled in the current object. Rename the method to be
virCgroupHasController. Also make it tolerant to a  NULL virCgroupPtr
and out-of-range controller index, to avoid duplication of these
checks in all callers

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-08 14:49:12 +01:00
Osier Yang
f5a610872a storage: Guess the parent if it's not specified for vHBA
This finds the parent for vHBA by iterating over all the HBA
which supports vport_ops capability on the host, and return
the first one which is online, not saturated (vports in use
is less than max_vports).
2013-04-08 18:41:07 +08:00
Osier Yang
b52fbad150 util: Add helper to get the scsi host name by iterating over sysfs
The helper iterates over sysfs, to find out the matched scsi host
name by comparing the wwnn,wwpn pair. It will be used by checkPool
and refreshPool of storage scsi backend. New helper getAdapterName
is introduced in storage_backend_scsi.c, which uses the new util
helper virGetFCHostNameByWWN to get the fc_host adapter name.
2013-04-08 18:41:06 +08:00
Daniel P. Berrange
c4f9edf1a1 Use VIR_ALLOC_VAR instead of VIR_ALLOC_N for creating virObject
The current way virObject instances are allocated using
VIR_ALLOC_N causes alignment warnings

util/virobject.c: In function 'virObjectNew':
util/virobject.c:195:11: error: cast increases required alignment of target type [-Werror=cast-align]

Changing to use VIR_ALLOC_VAR will avoid the need todo
the casts entirely.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-08 10:03:21 +01:00
Daniel P. Berrange
e95de74d4c Avoid casts between unsigned char * and struct nlmsghdr
The virNetlinkCommand() method takes an 'unsigned char **'
parameter to be filled with the received netlink message.
The callers then immediately cast this to 'struct nlmsghdr',
triggering (bogus) warnings about increasing alignment
requirements

util/virnetdev.c: In function 'virNetDevLinkDump':
util/virnetdev.c:1300:12: warning: cast increases required alignment of target type [-Wcast-align]
     resp = (struct nlmsghdr *)*recvbuf;
            ^
util/virnetdev.c: In function 'virNetDevSetVfConfig':
util/virnetdev.c:1429:12: warning: cast increases required alignment of target type [-Wcast-align]
     resp = (struct nlmsghdr *)recvbuf;

Since all callers cast to 'struct nlmsghdr' we can avoid
the warning problem entirely by simply changing the
signature of virNetlinkCommand to return a 'struct nlmsghdr **'
instead of 'unsigned char **'. The way we do the cast inside
virNetlinkCommand does not have any alignment issues.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-08 10:03:21 +01:00
Daniel P. Berrange
d27efd8e5d Rewrite keycode map to avoid a struct
Playing games with field offsets in a struct causes all sorts
of alignment warnings on ARM platforms

util/virkeycode.c: In function '__virKeycodeValueFromString':
util/virkeycode.c:26:7: warning: cast increases required alignment of target type [-Wcast-align]
     (*(typeof(field_type) *)((char *)(object) + field_offset))
       ^
util/virkeycode.c:91:28: note: in expansion of macro 'getfield'
         const char *name = getfield(virKeycodes + i, const char *, name_offset);
                            ^
util/virkeycode.c:26:7: warning: cast increases required alignment of target type [-Wcast-align]
     (*(typeof(field_type) *)((char *)(object) + field_offset))
       ^
util/virkeycode.c:94:20: note: in expansion of macro 'getfield'
             return getfield(virKeycodes + i, unsigned short, code_offset);
                    ^
util/virkeycode.c: In function '__virKeycodeValueTranslate':
util/virkeycode.c:26:7: warning: cast increases required alignment of target type [-Wcast-align]
     (*(typeof(field_type) *)((char *)(object) + field_offset))
       ^
util/virkeycode.c:127:13: note: in expansion of macro 'getfield'
         if (getfield(virKeycodes + i, unsigned short, from_offset) == key_value)
             ^
util/virkeycode.c:26:7: warning: cast increases required alignment of target type [-Wcast-align]
     (*(typeof(field_type) *)((char *)(object) + field_offset))
       ^
util/virkeycode.c:128:20: note: in expansion of macro 'getfield'
             return getfield(virKeycodes + i, unsigned short, to_offset);

There is no compelling reason to use a struct for the keycode
tables. It can easily just use an array of arrays instead,
avoiding all alignment problems

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-08 10:03:20 +01:00
Osier Yang
1acfc171da util: Add a helper to check if all bits of a bitmap are clear 2013-04-06 10:14:21 +08:00
Daniel P. Berrange
56f27b3bbc Don't create dirs in cgroup controllers we don't want to use
Currently when getting an instance of virCgroupPtr we will
create the path in all cgroup controllers. Only at the virt
driver layer are we attempting to filter controllers. This
is bad because the mere act of creating the dirs in the
controllers can have a functional impact on the kernel,
particularly for performance.

Update the virCgroupForDriver() method to accept a bitmask
of controllers to use. Only create dirs in the controllers
that are requested. When creating cgroups for domains,
respect the active controller list from the parent cgroup

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-05 10:41:54 +01:00
Daniel P. Berrange
804a809a06 Rename virCgroupGetAppRoot to virCgroupForSelf
The virCgroupGetAppRoot is not clear in its meaning. Change
to virCgroupForSelf to highlight that this returns the
cgroup config for the caller's process

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-05 10:41:54 +01:00
Daniel P. Berrange
9c29c52c5a Add armv6l architecture to list of valid arches
The Raspberry Pi runs the armv6l architecture and apparently
people are trying to run libvirt LXC on it. So we should allow
that as a valid arch

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-04 11:07:32 +01:00
Daniel P. Berrange
347081effa Implement minimal sysinfo for ARM platforms
Implement the bare minimal sysinfo for ARM platforms by
reading the CPU models from /proc/cpuinfo

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-04 11:07:31 +01:00
Peter Krempa
6bd94a1b59 Use virMacAddrFormat instead of manual mac address formatting
Format the address using the helper instead of having similar code in
multiple places.

This patch also fixes leak of the MAC address string in
ebtablesRemoveForwardAllowIn() and ebtablesAddForwardAllowIn() in
src/util/virebtables.c
2013-04-02 15:53:43 +02:00
Peter Krempa
ab4bf20ead util: Change virMacAddrFormat to lowercase hex characters
The domain XML generator creates the mac addres strings with lowercase
strings with a separate piece of code. This patch changes the formating
helper to do the same stuff to allow using it to normalize a string
provided by the user. After this change some of the tests that are
outputing the mac address will need to be changed.
2013-04-02 15:53:43 +02:00
Michal Privoznik
0e9df6bd10 virutil: Fix compilation on non-linux platforms
There has been a typo in virIsCapbleVport function name.
2013-03-28 13:23:04 +01:00
Osier Yang
5eeb56fb2a util: Fix the conflict type for virIsCapableFCHost
---
Pushed under build-breaker rule.
2013-03-28 20:17:05 +08:00
Stefan Seyfried
e669a65903 net: use newer iptables syntax
iptables-1.4.18 removed the long deprecated "state" match.
Use "conntrack" instead in forwarding rules.
Fixes openSUSE bug https://bugzilla.novell.com/811251 #811251.
2013-03-27 16:20:03 -06:00
Jiri Denemark
a1fe02f0e9 log: Separate thread ID from timestemp in ring buffer
When we write a log message into a log, we separate thread ID from
timestamp using ": ". However, when storing the message into the ring
buffer, we omitted the separator, e.g.:

    2013-02-27 11:49:11.852+00003745: ...
2013-03-27 09:00:35 +01:00
Osier Yang
f90af6914e util: Fix bug of managing vport
The string written to "vport_create" or "vport_delete" should
be "wwnn:wwpn", but not "wwpn:wwnn".
2013-03-25 21:18:14 +08:00
Osier Yang
9a3ff01d7f nodedev: Fix the improper logic when enumerating SRIOV VF
virPCIGetVirtualFunctions returns 0 even if there is no "virtfn"
entry under the device sysfs path.

And virPCIGetVirtualFunctions returns -1 when it fails to get
the PCI config space of one VF, however, with keeping the
the VFs already detected.

That's why udevProcessPCI and gather_pci_cap use logic like:

if (!virPCIGetVirtualFunctions(syspath,
                               &data->pci_dev.virtual_functions,
                               &data->pci_dev.num_virtual_functions) ||
    data->pci_dev.num_virtual_functions > 0)
    data->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_VIRTUAL_FUNCTION;

to tag the PCI device with "virtual_function" cap.

However, this results in a VF will aslo get "virtual_function" cap.

This patch fixes it by:
  * Ignoring the VF which has failure of getting PCI config space
    (given that the successfully detected VFs are kept , it makes
    sense to not give up on the failure of one VF too) with a warning,
    so virPCIGetVirtualFunctions will not return -1 except out of memory.

  * Free the allocated *virtual_functions when out of memory

And thus the logic can be changed to:

    /* Out of memory */
    int ret = virPCIGetVirtualFunctions(syspath,
                                        &data->pci_dev.virtual_functions,
                                        &data->pci_dev.num_virtual_functions);

    if (ret < 0 )
        goto out;
    if (data->pci_dev.num_virtual_functions > 0)
        data->pci_dev.flags |= VIR_NODE_DEV_CAP_FLAG_PCI_VIRTUAL_FUNCTION;
2013-03-25 21:14:48 +08:00
Osier Yang
96d3086a4f nodedev: Abstract nodeDeviceVportCreateDelete as util function
This abstracts nodeDeviceVportCreateDelete as an util function
virManageVport, which can be further used by later storage patches
(to support persistent vHBA, I don't want to create the vHBA
using the public API, which is not good).
2013-03-25 20:46:05 +08:00
Osier Yang
4360a09844 nodedev: Refactor the helpers
This adds two util functions (virIsCapableFCHost and virIsCapableVport),
and rename helper check_fc_host_linux as detect_scsi_host_caps,
check_capable_vport_linux is removed, as it's abstracted to the util
function virIsCapableVport. detect_scsi_host_caps nows detect both
the fc_host and vport_ops capabilities. "stat(2)" is replaced with
"access(2)" for saving.

* src/util/virutil.h:
  - Declare virIsCapableFCHost and virIsCapableVport
* src/util/virutil.c:
  - Implement virIsCapableFCHost and virIsCapableVport
* src/node_device/node_device_linux_sysfs.c:
  - Remove check_capable_vport_linux
  - Rename check_fc_host_linux as detect_scsi_host_caps, and refactor
    it a bit to detect both fc_host and vport_os capabilities
* src/node_device/node_device_driver.h:
  - Change/remove the related declarations
* src/node_device/node_device_udev.c: (Use detect_scsi_host_caps)
* src/node_device/node_device_hal.c: (Likewise)
* src/node_device/node_device_driver.c (Likewise)
2013-03-25 20:46:05 +08:00
Osier Yang
244ce462e2 util: Add one helper virReadFCHost to read the value of fc_host entry
"open_wwn_file" in node_device_linux_sysfs.c is redundant, on one
hand it duplicates work of virFileReadAll, on the other hand, it's
waste to use a function for it, as there is no other users of it.
So I don't see why the file opening work cannot be done in
"read_wwn_linux".

"read_wwn_linux" can be abstracted as an util function. As what all
it does is to read the sysfs entry.

So this patch removes "open_wwn_file", and abstract "read_wwn_linux"
as an util function "virReadFCHost" (a more general name, because
after changes, it can read each of the fc_host entry now).

* src/util/virutil.h: (Declare virReadFCHost)
* src/util/virutil.c: (Implement virReadFCHost)
* src/node_device/node_device_linux_sysfs.c: (Remove open_wwn_file,
  and read_wwn_linux)
src/node_device/node_device_driver.h: (Remove the declaration of
  read_wwn_linux, and the related macros)
src/libvirt_private.syms: (Export virReadFCHost)
2013-03-25 20:46:05 +08:00
Ján Tomko
b8fec67cb5 util: fix virAllocVar's comment 2013-03-22 13:05:46 +01:00
Michal Privoznik
70bc623b58 viralloc: Export virAllocTest*
If users build with --enable-test-oom configure option,
they get this error saying, virAllocTest* functions are
not defined within tests/testutils.c.
2013-03-22 12:45:14 +01:00
Daniel P. Berrange
6e5ad18992 Fix initialization of virIdentityPtr thread locals
Some code mistakenly called virIdentityOnceInit directly
instead of virIdentityInitialize(). This meant that one-time
initializer was run many times with predictably bad results.
2013-03-21 10:58:15 +00:00
Gao feng
8d19a9f578 cgroup: export virCgroupRemoveRecursively
We will use virCgroupRemoveRecursively to remove cgroup
directories in the coming patch.

Signed-off-by: Gao feng <gaofeng@cn.fujitsu.com>
2013-03-20 14:21:27 -06:00
Daniel P. Berrange
f07f9733cb Fix typos s/HAVE_SELINUX/WITH_SELINUX/
The virNetSocket & virIdentity classes accidentally got some
conditionals using HAVE_SELINUX instead of WITH_SELINUX.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-20 13:23:40 +00:00
Gao feng
45e9d27ad8 NUMA: cleanup for numa related codes
Intend to reduce the redundant code,use virNumaSetupMemoryPolicy
to replace virLXCControllerSetupNUMAPolicy and
qemuProcessInitNumaMemoryPolicy.

This patch also moves the numa related codes to the
file virnuma.c and virnuma.h

Signed-off-by: Gao feng <gaofeng@cn.fujitsu.com>
2013-03-20 19:37:00 +08:00
Gao feng
763edb5ebe rename qemuGetNumadAdvice to virNumaGetAutoPlacementAdvice
qemuGetNumadAdvice will be used by LXC driver, rename
it to virNumaGetAutoPlacementAdvice and move it to virnuma.c

Signed-off-by: Gao feng <gaofeng@cn.fujitsu.com>
2013-03-19 15:55:40 -06:00
Daniel P. Berrange
8c5d28c1ad Add API to get the system identity
If no user identity is available, some operations may wish to
use the system identity. ie the identity of the current process
itself. Add an API to get such an identity.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-19 13:45:19 +00:00
Daniel P. Berrange
8726e91b3a Add APIs for associating a virIdentityPtr with the current thread
To allow any internal API to get the current identity, add APIs
to associate a virIdentityPtr with the current thread, via a
thread local

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-19 13:38:44 +00:00
Daniel P. Berrange
3aabe27247 Define internal APIs for managing identities
Introduce a local object virIdentity for managing security
attributes used to form a client application's identity.
Instances of this object are intended to be used as if they
were immutable, once created & populated with attributes

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-19 13:37:37 +00:00
Eric Blake
7af86379ef util: portably check for unchanged uid
We've already scrubbed for comparisons of 'uid_t == -1' (which fail
on platforms where uid_t is a u16), but another one snuck in.

* src/util/virutil.c (virSetUIDGIDWithCaps): Correct uid comparison.
* cfg.mk (sc_prohibit_risky_id_promotion): New rule.
2013-03-15 10:55:51 -06:00
Laine Stump
49fa91b3ee util: fix clear_emulator_capabilities=0
My commit 7a2e845a86 (and its
prerequisites) managed to effectively ignore the
clear_emulator_capabilities setting in qemu.conf (visible in the code
as the VIR_EXEC_CLEAR_CAPS flag when qemu is being exec'ed), with the
result that the capabilities are always cleared regardless of the
qemu.conf setting. This patch fixes it by passing the flag through to
virSetUIDGIDWithCaps(), which uses it to decide whether or not to
clear existing capabilities before adding in those that were
requested.

Note that the existing capabilities are *always* cleared if the new
process is going to run as non-root, since the whole point of running
non-root is to have the capabilities removed (it's still possible to
maintain individual capabilities as needed using the capBits argument
though).
2013-03-14 14:02:32 -04:00
Ján Tomko
6e46477c23 Fix size probing for VDI images
Commit 027bf2ea used the wrong offset: the text field at the start
of the header has 64 bytes, not 68. [1]

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

[1] https://forums.virtualbox.org/viewtopic.php?p=29267#p29267
2013-03-14 15:12:06 +01:00
Guannan Ren
eb086eb5b5 util: escapes special characters in VIR_LOG_REGEX
In debug mode, the bug failed to start vm
error: Failed to start domain rhel5u9
error: internal error Out of space while reading console log output:
...
2013-03-14 13:28:11 +08:00
Daniel P. Berrange
a299714295 Add API for thread cancellation
Add a virThreadCancel function. This functional is inherently
dangerous and not something we want to use in general, but
integration with SELinux requires that we provide this stub.
We leave out any Win32 impl to discourage further use and
because obviously SELinux isn't enabled on Win32

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-12 18:07:11 +00:00
Daniel P. Berrange
f3d312f6c8 Add method for checking if a string is (probably) a log message
When reading log output from QEMU/LXC we need to skip over any
libvirt log messages. Currently the QEMU driver checks for a
fixed string, but this is better done with a regex. Add a method
virLogProbablyLogMessage to do a regex check

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-07 18:56:52 +00:00
Daniel P. Berrange
495e3b2b50 Fix conditional build of virNetDevSetupControlFull
The virNetDevSetupControlFull function was protected by a
conditional on SIOCBRADDBR, which is bogus since it does
not use that symbol. Update the conditionals around all
callers to do stricter checks to ensure we always build
succesfully

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-07 18:08:33 +00:00
Daniel P. Berrange
3ed2e54500 Ensure GET_VLAN_VID_CMD is always defined
The RHEL4 vintage header files do not define GET_VLAN_VID_CMD.
Conditionally define it in our source, since the kernel can
raise a runtime error if it isn't supported

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-07 18:08:31 +00:00
Daniel P. Berrange
564e7d38a2 Don't import loop.h unless HAVE_DECL_LO_FLAGS_AUTOCLEAR is defined
The loop.h on RHEL4 is broken and cannot be imported. We already
detect this in configure as a side-effect of looking for whether
LO_FLAGS_AUTOCLEAR is available. We protected the impl with
HAVE_DECL_LO_FLAGS_AUTOCLEAR, but not the header import

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-03-07 18:07:27 +00:00
Eric Blake
2e6322a7a5 viralloc: use consistent naming
Commit 0df3e89 only touched the header, but the .c file had the
same shadowing potential.

* src/util/viralloc.c (virDeleteElementsN): s/remove/toremove/ to
match the header.
2013-03-07 07:53:42 -07:00
Eric Blake
0df3e8966c build: avoid shadowing a function name
Make the same fix as in commit de53eff.

* src/util/viralloc.h (virDeleteElementsN): Cater to old glibc.
2013-03-07 06:45:38 -07:00
Guannan Ren
b38a040a29 util: fix a integer boundary error
A value which is equal to a integer maximum such as LLONG_MAX is
a valid integer value.

The patch fix the following error:
1, virsh memtune vm --swap-hard-limit -1
2, virsh start vm
In debug mode, it shows error like:
virScaleInteger:1813 : numerical overflow:\
                       value too large: 9007199254740991KiB
2013-03-06 11:46:33 +08:00
Guannan Ren
b95c13cd33 util: use string libvirt to prefix error message instead of libvir
BZ:https://bugzilla.redhat.com/show_bug.cgi?id=912021
Without error handler set, virDefaultErrorFunc will be called, the
error message is prefixed with "libvir:". It become a little better
by using prefix "libvirt:" when working with upper application.

For example:
1, stop libvirtd daemon
2, run virt-top.
libvir: XML-RPC error : Failed to connect \
        socket to '/var/run/libvirt/libvirt-sock-ro': \
        No such file or directory
libvirt: VIR_ERR_SYSTEM_ERROR: VIR_FROM_RPC: \
        Failed to connect socket to '/var/run/libvirt/libvirt-sock-ro': \
        No such file or directory
2013-03-04 23:21:20 +08:00
Michal Privoznik
1cf97c87c0 virnetdevmacvlan.c: Introduce mutex for macvlan creation
Currently, after we removed the qemu driver lock, it may happen
that two or more threads will start up a machine with macvlan and
race over virNetDevMacVLanCreateWithVPortProfile(). However,
there's a racy section in which we are generating a sequence of
possible device names and detecting if they exits. If we found
one which doesn't we try to create a device with that name.
However, the other thread is doing just the same. Assume it will
succeed and we must therefore fail. If this happens more than 5
times (which in massive parallel startup surely will) we return
-1 without any error reported. This patch is a simple hack to
both of these problems. It introduces a mutex, so only one thread
will enter the section, and if it runs out of possibilities,
error is reported. Moreover, the number of retries is raised to 20.
2013-03-01 11:33:29 +01:00
Daniel P. Berrange
279336c5d8 Avoid spamming logs with cgroups warnings
The code for putting the emulator threads in a separate cgroup
would spam the logs with warnings

2013-02-27 16:08:26.731+0000: 29624: warning : virCgroupMoveTask:887 : no vm cgroup in controller 3
2013-02-27 16:08:26.731+0000: 29624: warning : virCgroupMoveTask:887 : no vm cgroup in controller 4
2013-02-27 16:08:26.732+0000: 29624: warning : virCgroupMoveTask:887 : no vm cgroup in controller 6

This is because it has only created child cgroups for 3 of the
controllers, but was trying to move the processes from all the
controllers. The fix is to only try to move threads in the
controllers we actually created. Also remove the warning and
make it return a hard error to avoid such lazy callers in the
future.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-02-27 22:51:24 +00:00
Peter Krempa
923e4bf810 util: Add docs for virXMLProp string
To avoid confusion about usage of this function explicitly document that
this function returns copy of the attribute string.
2013-02-27 11:49:03 +01:00
Philipp Hahn
5474870cda storage: cast -1 for uid_t|gid_t
uid_t and gid_t are opaque types, ranging from s32 to u32 to u64.

Explicitly cast the magic -1 to the appropriate type.

Signed-off-by: Philipp Hahn <hahn@univention.de>
2013-02-25 15:46:32 +01:00
Philipp Hahn
7b4b59fa4a util: Fix printf format for uid_t|gid_t
The uid_t|gid_t values are explicitly casted to "unsigned long", but the
printf() still used "%d", which is for signed values.

Change the format to "%u".

Signed-off-by: Philipp Hahn <hahn@univention.de>
2013-02-25 15:46:32 +01:00
Gene Czarcinski
0b73a763f3 use client id for IPv6 DHCP host definition
Originally, only a host name was used to associate a
DHCPv6 request with a specific IPv6 address.  Further testing
demonstrates that this is an unreliable method and, instead,
a client-id or DUID needs to be used.  According to DHCPv6
standards, this id can be a duid-LLT, duid-LL, or duid-UUID
even though dnsmasq will accept almost any text string.

Although validity checking of a specified string makes sure it is
hexadecimal notation with bytes separated by colons, there is no
rigorous check to make sure it meets the standard.

Documentation and schemas have been updated.

Signed-off-by: Gene Czarcinski <gene@czarc.net>
Signed-off-by: Laine Stump <laine@laine.org>
2013-02-25 02:49:06 -05:00
Laine Stump
c720ddd6ac util: fix typo in comment 2013-02-24 23:21:28 -05:00
Natanael Copa
bac8b2ca09 net: use structs for address and port ranges
We pass over the address/port start/end values many times so we put
them in structs.

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Laine Stump <laine@laine.org>
2013-02-19 14:42:18 -05:00
Natanael Copa
1716e7a6c5 net: add support for specifying port range for forward mode nat
Let users set the port range to be used for forward mode NAT:

...
  <forward mode='nat'>
    <nat>
      <port start='1024' end='65535'/>
    </nat>
  </forward>
...

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Laine Stump <laine@laine.org>
2013-02-19 14:42:18 -05:00
Natanael Copa
905629f47e net: support set public ip range for forward mode nat
Support setting which public ip to use for NAT via attribute
address in subelement <nat> in <forward>:

...
  <forward mode='nat'>
      <address start='1.2.3.4' end='1.2.3.10'/>
  </forward>
...

This will construct an iptables line using:

  '-j SNAT --to-source <start>-<end>'

instead of:

  '-j MASQUERADE'

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Laine Stump <laine@laine.org>
2013-02-19 14:42:18 -05:00
Jiri Denemark
ee1d6d91d1 Avoid resetting errors in virTypedParamsFree
The function does not report any errors so there should be no need too
reset an existing error first. Moreover, virTypedParamsFree is mostly
called in cleanup phase where it has the potential to reset any useful
reported earlier.
2013-02-19 10:52:37 +01:00
John Ferlan
277aaeeebf vircommand: Remove unnecessary sa_assert
Changes from commit '3178df9a' removed the need for the sa_assert(infd).
2013-02-16 07:44:35 -05:00
Eric Blake
d1333dd0fb storage: don't follow backing chain symlinks too eagerly
If you have a qcow2 file /path1/to/file pointed to by symlink
/path2/symlink, and pass qemu /path2/symlink, then qemu treats
a relative backing file in the qcow2 metadata as being relative
to /path2, not /path1/to.  Yes, this means that it is possible
to create a qcow2 file where the choice of WHICH directory and
symlink you access its contents from will then determine WHICH
backing file (if any) you actually find; the results can be
rather screwy, but we have to match what qemu does.

Libvirt and qemu default to creating absolute backing file
names, so most users don't hit this.  But at least VDSM uses
symlinks and relative backing names alongside the
--reuse-external flags to libvirt snapshot operations, with the
result that libvirt was failing to follow the intended chain of
backing files, and then backing files were not granted the
necessary sVirt permissions to be opened by qemu.

See https://bugzilla.redhat.com/show_bug.cgi?id=903248 for
more gory details.  This fixes a regression introduced in
commit 8250783.

I tested this patch by creating the following chain:

ls /home/eblake/Downloads/Fedora.iso # raw file for base
cd /var/lib/libvirt/images
qemu-img create -f qcow2 \
  -obacking_file=/home/eblake/Downloads/Fedora.iso,backing_fmt=raw one
mkdir sub
cd sub
ln -s ../one onelink
qemu-img create -f qcow2 \
  -obacking_file=../sub/onelink,backing_fmt=qcow2 two
mv two ..
ln -s ../two twolink
qemu-img create -f qcow2 \
  -obacking_file=../sub/twolink,backing_fmt=qcow2 three
mv three ..
ln -s ../three threelink

then pointing my domain at /var/lib/libvirt/images/sub/threelink.
Prior to this patch, I got complaints about missing backing
files; afterwards, I was able to verify that the backing chain
(and hence DAC and SELinux relabels) of the entire chain worked.

* src/util/virstoragefile.h (_virStorageFileMetadata): Add
directory member.
* src/util/virstoragefile.c (absolutePathFromBaseFile): Drop,
replaced by...
(virFindBackingFile): ...better function.
(virStorageFileGetMetadataInternal): Add an argument.
(virStorageFileGetMetadataFromFD, virStorageFileChainLookup)
(virStorageFileGetMetadata): Update callers.
2013-02-15 16:07:01 -07:00
Eric Blake
2485f92153 storage: refactor metadata lookup
Prior to this patch, we had the callchains:
external users
  \-> virStorageFileGetMetadataFromFD
      \-> virStorageFileGetMetadataFromBuf
virStorageFileGetMetadataRecurse
  \-> virStorageFileGetMetadataFromFD
      \-> virStorageFileGetMetadataFromBuf

However, a future patch wants to add an additional parameter to
the bottom of the chain, for use by virStorageFileGetMetadataRecurse,
without affecting existing external callers.  Since there is only a
single caller of the internal function, we can repurpose it to fit
our needs, with this patch giving us:

external users
  \-> virStorageFileGetMetadataFromFD
      \-> virStorageFileGetMetadataInternal
virStorageFileGetMetadataRecurse /
  \-> virStorageFileGetMetadataInternal

* src/util/virstoragefile.c (virStorageFileGetMetadataFromFD):
Move most of the guts...
(virStorageFileGetMetadataFromBuf): ...here, and rename...
(virStorageFileGetMetadataInternal): ...to this.
(virStorageFileGetMetadataRecurse): Use internal helper.
2013-02-15 16:07:00 -07:00
Eric Blake
b7df4f92d6 storage: prepare for refactoring
virStorageFileGetMetadataFromFD is the only caller of
virStorageFileGetMetadataFromBuf; and it doesn't care about the
difference between a return of 0 (total success) or 1
(metadata was inconsistent, but pointer was populated as best
as possible); only about a return of -1 (could not read metadata
or out of memory).  Changing the return type, and normalizing
the variable names used, will make merging the functions easier
in the next commit.

* src/util/virstoragefile.c (virStorageFileGetMetadataFromBuf):
Change return value, and rename some variables.
(virStorageFileGetMetadataFromFD): Rename some variables.
2013-02-15 16:07:00 -07:00
Eric Blake
5e4946d4d9 storage: rearrange functions
No semantic change; done so the next patch doesn't need a forward
declaration of a static function.

* src/util/virstoragefile.c (virStorageFileProbeFormatFromBuf):
Hoist earlier.
2013-02-15 16:07:00 -07:00
Eric Blake
660db5bf72 build: fix mingw build
Commits 2025356 and ba72cb12 introduced typos.

* src/util/virpci.c (virPCIIsVirtualFunction) [!__linux__]: Fix
function name.
* src/util/virutil.c (virGetDeviceID): Fix attribute spelling.
2013-02-15 15:05:25 -07:00
Eric Blake
ec2cc0f860 build: fix vircommand build on mingw
CC       libvirt_util_la-vircommand.lo
../../src/util/vircommand.c:2358:1: error: 'virCommandHandshakeChild' defined but not used [-Werror=unused-function]

The function is only implemented inside #ifndef WIN32.

* src/util/vircommand.c (virCommandHandshakeChild): Hoist earlier,
so that win32 build doesn't hit an unused forward declaration.
2013-02-15 13:16:46 -07:00