qemu_blockjob.c 51.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * qemu_blockjob.c: helper functions for QEMU block jobs
 *
 * Copyright (C) 2006-2015 Red Hat, Inc.
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "internal.h"

#include "qemu_blockjob.h"
27
#include "qemu_block.h"
28
#include "qemu_domain.h"
29
#include "qemu_alias.h"
30
#include "qemu_backup.h"
31 32 33 34 35 36

#include "conf/domain_conf.h"
#include "conf/domain_event.h"

#include "virlog.h"
#include "virstoragefile.h"
37 38
#include "virthread.h"
#include "virtime.h"
39
#include "locking/domain_lock.h"
40
#include "viralloc.h"
41
#include "virstring.h"
42
#include "qemu_security.h"
43 44 45 46 47

#define VIR_FROM_THIS VIR_FROM_QEMU

VIR_LOG_INIT("qemu.qemu_blockjob");

48 49 50 51 52 53 54 55 56
/* Note that qemuBlockjobState and qemuBlockjobType values are formatted into
 * the status XML */
VIR_ENUM_IMPL(qemuBlockjobState,
              QEMU_BLOCKJOB_STATE_LAST,
              "completed",
              "failed",
              "cancelled",
              "ready",
              "new",
57
              "running",
58 59 60
              "concluded",
              "aborting",
              "pivoting");
61 62 63 64 65 66 67 68

VIR_ENUM_IMPL(qemuBlockjob,
              QEMU_BLOCKJOB_TYPE_LAST,
              "",
              "pull",
              "copy",
              "commit",
              "active-commit",
P
Peter Krempa 已提交
69
              "backup",
70
              "",
71 72
              "create",
              "broken");
73

74 75 76
static virClassPtr qemuBlockJobDataClass;


77 78 79 80 81
static void
qemuBlockJobDataDisposeJobdata(qemuBlockJobDataPtr job)
{
    if (job->type == QEMU_BLOCKJOB_TYPE_CREATE)
        virObjectUnref(job->data.create.src);
82 83 84 85 86

    if (job->type == QEMU_BLOCKJOB_TYPE_BACKUP) {
        virObjectUnref(job->data.backup.store);
        g_free(job->data.backup.bitmap);
    }
87 88 89
}


90 91
static void
qemuBlockJobDataDispose(void *obj)
92
{
93
    qemuBlockJobDataPtr job = obj;
94

95 96 97
    virObjectUnref(job->chain);
    virObjectUnref(job->mirrorChain);

98
    qemuBlockJobDataDisposeJobdata(job);
99

100 101
    g_free(job->name);
    g_free(job->errmsg);
102 103 104 105 106 107 108 109 110 111 112 113 114
}


static int
qemuBlockJobDataOnceInit(void)
{
    if (!VIR_CLASS_NEW(qemuBlockJobData, virClassForObject()))
        return -1;

    return 0;
}


115
VIR_ONCE_GLOBAL_INIT(qemuBlockJobData);
116

117
qemuBlockJobDataPtr
118 119
qemuBlockJobDataNew(qemuBlockJobType type,
                    const char *name)
120
{
121
    g_autoptr(qemuBlockJobData) job = NULL;
122

123 124 125
    if (qemuBlockJobDataInitialize() < 0)
        return NULL;

126 127
    if (!(job = virObjectNew(qemuBlockJobDataClass)))
        return NULL;
128

129
    job->name = g_strdup(name);
130

131
    job->state = QEMU_BLOCKJOB_STATE_NEW;
132
    job->newstate = -1;
133 134
    job->type = type;

J
Ján Tomko 已提交
135
    return g_steal_pointer(&job);
136 137 138
}


139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
/**
 * qemuBlockJobMarkBroken:
 * @job: job to mark as broken
 *
 * In case when we are unable to parse the block job data from the XML
 * successfully we'll need to mark the job as broken and then attempt to abort
 * it. This function marks the job as broken.
 */
static void
qemuBlockJobMarkBroken(qemuBlockJobDataPtr job)
{
    qemuBlockJobDataDisposeJobdata(job);
    job->brokentype = job->type;
    job->type = QEMU_BLOCKJOB_TYPE_BROKEN;
}


156 157 158 159 160 161 162 163 164
/**
 * qemuBlockJobRegister:
 * @job: job to register
 * @vm: domain to register @job with
 * @disk: disk to register @job with
 * @savestatus: save the status XML after registering
 *
 * This function registers @job with @disk and @vm and records it into the status
 * xml (if @savestatus is true).
165 166
 *
 * Note that if @job also references a separate chain e.g. for disk mirroring,
167
 * then job->mirrorchain needs to be set manually.
168
 */
169
int
170
qemuBlockJobRegister(qemuBlockJobDataPtr job,
171
                     virDomainObjPtr vm,
172 173
                     virDomainDiskDefPtr disk,
                     bool savestatus)
174
{
175 176
    qemuDomainObjPrivatePtr priv = vm->privateData;

177 178 179 180 181 182
    if (disk && QEMU_DOMAIN_DISK_PRIVATE(disk)->blockjob) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("disk '%s' has a blockjob assigned"), disk->dst);
        return -1;
    }

183 184 185 186 187
    if (virHashAddEntry(priv->blockjobs, job->name, virObjectRef(job)) < 0) {
        virObjectUnref(job);
        return -1;
    }

188 189
    if (disk) {
        job->disk = disk;
190
        job->chain = virObjectRef(disk->src);
191 192 193
        QEMU_DOMAIN_DISK_PRIVATE(disk)->blockjob = virObjectRef(job);
    }

194 195 196
    if (savestatus)
        qemuDomainSaveStatus(vm);

197 198 199 200 201
    return 0;
}


static void
202 203
qemuBlockJobUnregister(qemuBlockJobDataPtr job,
                       virDomainObjPtr vm)
204
{
205
    qemuDomainObjPrivatePtr priv = vm->privateData;
206 207 208 209 210 211 212 213 214 215 216 217
    qemuDomainDiskPrivatePtr diskPriv;

    if (job->disk) {
        diskPriv = QEMU_DOMAIN_DISK_PRIVATE(job->disk);

        if (job == diskPriv->blockjob) {
            virObjectUnref(diskPriv->blockjob);
            diskPriv->blockjob = NULL;
        }

        job->disk = NULL;
    }
218 219 220

    /* this may remove the last reference of 'job' */
    virHashRemoveEntry(priv->blockjobs, job->name);
221 222

    qemuDomainSaveStatus(vm);
223 224 225
}


226 227 228 229 230 231 232 233 234
/**
 * qemuBlockJobDiskNew:
 * @disk: disk definition
 *
 * Start/associate a new blockjob with @disk.
 *
 * Returns 0 on success and -1 on failure.
 */
qemuBlockJobDataPtr
235 236
qemuBlockJobDiskNew(virDomainObjPtr vm,
                    virDomainDiskDefPtr disk,
237 238
                    qemuBlockJobType type,
                    const char *jobname)
239
{
240
    g_autoptr(qemuBlockJobData) job = NULL;
241

242
    if (!(job = qemuBlockJobDataNew(type, jobname)))
243
        return NULL;
244

245
    if (qemuBlockJobRegister(job, vm, disk, true) < 0)
246
        return NULL;
247

J
Ján Tomko 已提交
248
    return g_steal_pointer(&job);
249 250 251
}


252 253 254 255 256 257
qemuBlockJobDataPtr
qemuBlockJobDiskNewPull(virDomainObjPtr vm,
                        virDomainDiskDefPtr disk,
                        virStorageSourcePtr base)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
258
    g_autoptr(qemuBlockJobData) job = NULL;
259
    g_autofree char *jobname = NULL;
260 261

    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV)) {
262
        jobname = g_strdup_printf("pull-%s-%s", disk->dst, disk->src->nodeformat);
263 264 265 266 267 268 269 270 271 272 273 274 275
    } else {
        if (!(jobname = qemuAliasDiskDriveFromDisk(disk)))
            return NULL;
    }

    if (!(job = qemuBlockJobDataNew(QEMU_BLOCKJOB_TYPE_PULL, jobname)))
        return NULL;

    job->data.pull.base = base;

    if (qemuBlockJobRegister(job, vm, disk, true) < 0)
        return NULL;

J
Ján Tomko 已提交
276
    return g_steal_pointer(&job);
277 278 279
}


280 281 282 283 284
qemuBlockJobDataPtr
qemuBlockJobDiskNewCommit(virDomainObjPtr vm,
                          virDomainDiskDefPtr disk,
                          virStorageSourcePtr topparent,
                          virStorageSourcePtr top,
285 286
                          virStorageSourcePtr base,
                          bool delete_imgs)
287 288
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
289
    g_autoptr(qemuBlockJobData) job = NULL;
290
    g_autofree char *jobname = NULL;
291 292 293 294 295 296
    qemuBlockJobType jobtype = QEMU_BLOCKJOB_TYPE_COMMIT;

    if (topparent == NULL)
        jobtype = QEMU_BLOCKJOB_TYPE_ACTIVE_COMMIT;

    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV)) {
297
        jobname = g_strdup_printf("commit-%s-%s", disk->dst, top->nodeformat);
298 299 300 301 302 303 304 305 306 307 308
    } else {
        if (!(jobname = qemuAliasDiskDriveFromDisk(disk)))
            return NULL;
    }

    if (!(job = qemuBlockJobDataNew(jobtype, jobname)))
        return NULL;

    job->data.commit.topparent = topparent;
    job->data.commit.top = top;
    job->data.commit.base = base;
309
    job->data.commit.deleteCommittedImages = delete_imgs;
310 311 312 313

    if (qemuBlockJobRegister(job, vm, disk, true) < 0)
        return NULL;

J
Ján Tomko 已提交
314
    return g_steal_pointer(&job);
315 316 317
}


318 319 320 321 322 323
qemuBlockJobDataPtr
qemuBlockJobNewCreate(virDomainObjPtr vm,
                      virStorageSourcePtr src,
                      virStorageSourcePtr chain,
                      bool storage)
{
324
    g_autoptr(qemuBlockJobData) job = NULL;
325
    g_autofree char *jobname = NULL;
326 327 328 329 330
    const char *nodename = src->nodeformat;

    if (storage)
        nodename = src->nodestorage;

331
    jobname = g_strdup_printf("create-%s", nodename);
332 333 334 335 336 337 338 339 340 341 342 343

    if (!(job = qemuBlockJobDataNew(QEMU_BLOCKJOB_TYPE_CREATE, jobname)))
        return NULL;

    if (virStorageSourceIsBacking(chain))
        job->chain = virObjectRef(chain);

     job->data.create.src = virObjectRef(src);

    if (qemuBlockJobRegister(job, vm, NULL, true) < 0)
        return NULL;

J
Ján Tomko 已提交
344
    return g_steal_pointer(&job);
345 346 347
}


348 349 350 351 352 353 354 355
qemuBlockJobDataPtr
qemuBlockJobDiskNewCopy(virDomainObjPtr vm,
                        virDomainDiskDefPtr disk,
                        virStorageSourcePtr mirror,
                        bool shallow,
                        bool reuse)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
356
    g_autoptr(qemuBlockJobData) job = NULL;
357
    g_autofree char *jobname = NULL;
358 359

    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV)) {
360
        jobname = g_strdup_printf("copy-%s-%s", disk->dst, disk->src->nodeformat);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    } else {
        if (!(jobname = qemuAliasDiskDriveFromDisk(disk)))
            return NULL;
    }

    if (!(job = qemuBlockJobDataNew(QEMU_BLOCKJOB_TYPE_COPY, jobname)))
        return NULL;

    job->mirrorChain = virObjectRef(mirror);

    if (shallow && !reuse)
        job->data.copy.shallownew = true;

    if (qemuBlockJobRegister(job, vm, disk, true) < 0)
        return NULL;

J
Ján Tomko 已提交
377
    return g_steal_pointer(&job);
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
}


qemuBlockJobDataPtr
qemuBlockJobDiskNewBackup(virDomainObjPtr vm,
                          virDomainDiskDefPtr disk,
                          virStorageSourcePtr store,
                          const char *bitmap)
{
    g_autoptr(qemuBlockJobData) job = NULL;
    g_autofree char *jobname = NULL;

    jobname = g_strdup_printf("backup-%s-%s", disk->dst, disk->src->nodeformat);

    if (!(job = qemuBlockJobDataNew(QEMU_BLOCKJOB_TYPE_BACKUP, jobname)))
        return NULL;

    job->data.backup.bitmap = g_strdup(bitmap);
    job->data.backup.store = virObjectRef(store);

    /* backup jobs are usually started in bulk by transaction so the caller
     * shall save the status XML */
    if (qemuBlockJobRegister(job, vm, disk, false) < 0)
        return NULL;

    return g_steal_pointer(&job);
404 405 406
}


407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
/**
 * qemuBlockJobDiskGetJob:
 * @disk: disk definition
 *
 * Get a reference to the block job data object associated with @disk.
 */
qemuBlockJobDataPtr
qemuBlockJobDiskGetJob(virDomainDiskDefPtr disk)
{
    qemuBlockJobDataPtr job = QEMU_DOMAIN_DISK_PRIVATE(disk)->blockjob;

    if (!job)
        return NULL;

    return virObjectRef(job);
}


/**
 * qemuBlockJobStarted:
 * @job: job data
 *
 * Mark @job as started in qemu.
 */
void
432 433
qemuBlockJobStarted(qemuBlockJobDataPtr job,
                    virDomainObjPtr vm)
434
{
435 436
    if (job->state == QEMU_BLOCKJOB_STATE_NEW)
        job->state = QEMU_BLOCKJOB_STATE_RUNNING;
437 438

    qemuDomainSaveStatus(vm);
439 440 441 442 443 444 445 446 447 448 449 450
}


/**
 * qemuBlockJobStartupFinalize:
 * @job: job being started
 *
 * Cancels and clears the job private data if the job was not started with
 * qemu (see qemuBlockJobStarted) or just clears up the local reference
 * to @job if it was started.
 */
void
451 452
qemuBlockJobStartupFinalize(virDomainObjPtr vm,
                            qemuBlockJobDataPtr job)
453 454 455 456
{
    if (!job)
        return;

457
    if (job->state == QEMU_BLOCKJOB_STATE_NEW)
458
        qemuBlockJobUnregister(job, vm);
459 460 461 462 463

    virObjectUnref(job);
}


464 465 466 467
bool
qemuBlockJobIsRunning(qemuBlockJobDataPtr job)
{
    return job->state == QEMU_BLOCKJOB_STATE_RUNNING ||
468 469 470
           job->state == QEMU_BLOCKJOB_STATE_READY ||
           job->state == QEMU_BLOCKJOB_STATE_ABORTING ||
           job->state == QEMU_BLOCKJOB_STATE_PIVOTING;
471 472 473
}


474 475 476
/* returns 1 for a job we didn't reconnect to */
static int
qemuBlockJobRefreshJobsFindInactive(const void *payload,
J
Ján Tomko 已提交
477 478
                                    const void *name G_GNUC_UNUSED,
                                    const void *data G_GNUC_UNUSED)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
{
    const qemuBlockJobData *job = payload;

    return !job->reconnected;
}


int
qemuBlockJobRefreshJobs(virQEMUDriverPtr driver,
                        virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuMonitorJobInfoPtr *jobinfo = NULL;
    size_t njobinfo = 0;
    qemuBlockJobDataPtr job = NULL;
    int newstate;
    size_t i;
    int ret = -1;
    int rc;

    qemuDomainObjEnterMonitor(driver, vm);

    rc = qemuMonitorGetJobInfo(priv->mon, &jobinfo, &njobinfo);

    if (qemuDomainObjExitMonitor(driver, vm) < 0 || rc < 0)
        goto cleanup;

    for (i = 0; i < njobinfo; i++) {
        if (!(job = virHashLookup(priv->blockjobs, jobinfo[i]->id))) {
            VIR_DEBUG("ignoring untracked job '%s'", jobinfo[i]->id);
            continue;
        }

        /* try cancelling invalid jobs - this works only if the job is not
         * concluded. In such case it will fail. We'll leave such job linger
         * in qemu and just forget about it in libvirt because there's not much
         * we coud do besides killing the VM */
        if (job->invalidData) {
517 518 519

            qemuBlockJobMarkBroken(job);

520 521 522 523 524 525 526 527 528 529 530
            qemuDomainObjEnterMonitor(driver, vm);

            rc = qemuMonitorJobCancel(priv->mon, job->name, true);
            if (rc == -1 && jobinfo[i]->status == QEMU_MONITOR_JOB_STATUS_CONCLUDED)
                VIR_WARN("can't cancel job '%s' with invalid data", job->name);

            if (qemuDomainObjExitMonitor(driver, vm) < 0)
                goto cleanup;

            if (rc < 0)
                qemuBlockJobUnregister(job, vm);
531 532
            else
                job->reconnected = true;
533 534 535 536 537 538 539 540 541 542 543 544 545
            continue;
        }

        if ((newstate = qemuBlockjobConvertMonitorStatus(jobinfo[i]->status)) < 0)
            continue;

        if (newstate != job->state) {
            if ((job->state == QEMU_BLOCKJOB_STATE_FAILED ||
                 job->state == QEMU_BLOCKJOB_STATE_COMPLETED)) {
                /* preserve the old state but allow the job to be bumped to
                 * execute the finishing steps */
                job->newstate = job->state;
            } else if (newstate == QEMU_BLOCKJOB_STATE_CONCLUDED) {
546
                job->errmsg = g_strdup(jobinfo[i]->error);
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

                if (job->errmsg)
                    job->newstate = QEMU_BLOCKJOB_STATE_FAILED;
                else
                    job->newstate = QEMU_BLOCKJOB_STATE_COMPLETED;
            } else if (newstate == QEMU_BLOCKJOB_STATE_READY) {
                /* Apply _READY state only if it was not applied before */
                if (job->state == QEMU_BLOCKJOB_STATE_NEW ||
                    job->state == QEMU_BLOCKJOB_STATE_RUNNING)
                    job->newstate = newstate;
            }
            /* don't update the job otherwise */
        }

        job->reconnected = true;

        if (job->newstate != -1)
            qemuBlockJobUpdate(vm, job, QEMU_ASYNC_JOB_NONE);
    }

    /* remove data for job which qemu didn't report (the algorithm is
     * inefficient, but the possibility of such jobs is very low */
569 570
    while ((job = virHashSearch(priv->blockjobs, qemuBlockJobRefreshJobsFindInactive, NULL, NULL))) {
        VIR_WARN("dropping blockjob '%s' untracked by qemu", job->name);
571
        qemuBlockJobUnregister(job, vm);
572
    }
573 574 575 576 577 578 579 580 581 582 583 584

    ret = 0;

 cleanup:
    for (i = 0; i < njobinfo; i++)
        qemuMonitorJobInfoFree(jobinfo[i]);
    VIR_FREE(jobinfo);

    return ret;
}


585 586 587 588
/**
 * qemuBlockJobEmitEvents:
 *
 * Emits the VIR_DOMAIN_EVENT_ID_BLOCK_JOB and VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2
589
 * for a block job. The former event is emitted only for local disks.
590 591 592 593 594 595 596 597 598 599 600
 */
static void
qemuBlockJobEmitEvents(virQEMUDriverPtr driver,
                       virDomainObjPtr vm,
                       virDomainDiskDefPtr disk,
                       virDomainBlockJobType type,
                       virConnectDomainEventBlockJobStatus status)
{
    virObjectEventPtr event = NULL;
    virObjectEventPtr event2 = NULL;

601 602 603 604
    /* don't emit events for jobs without disk */
    if (!disk)
        return;

605 606 607 608 609
    /* don't emit events for internal jobs and states */
    if (type >= VIR_DOMAIN_BLOCK_JOB_TYPE_LAST ||
        status >= VIR_DOMAIN_BLOCK_JOB_LAST)
        return;

610 611 612 613 614 615
    if (virStorageSourceIsLocalStorage(disk->src) &&
        !virStorageSourceIsEmpty(disk->src)) {
        event = virDomainEventBlockJobNewFromObj(vm, virDomainDiskGetSource(disk),
                                                 type, status);
        virObjectEventStateQueue(driver->domainEventState, event);
    }
616 617 618 619 620

    event2 = virDomainEventBlockJob2NewFromObj(vm, disk->dst, type, status);
    virObjectEventStateQueue(driver->domainEventState, event2);
}

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
/**
 * qemuBlockJobCleanStorageSourceRuntime:
 * @src: storage source to clean from runtime data
 *
 * Remove all runtime related data from the storage source.
 */
static void
qemuBlockJobCleanStorageSourceRuntime(virStorageSourcePtr src)
{
    src->id = 0;
    src->detected = false;
    VIR_FREE(src->relPath);
    VIR_FREE(src->backingStoreRaw);
    VIR_FREE(src->nodestorage);
    VIR_FREE(src->nodeformat);
    VIR_FREE(src->tlsAlias);
    VIR_FREE(src->tlsCertdir);
}

640

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
/**
 * qemuBlockJobRewriteConfigDiskSource:
 * @vm: domain object
 * @disk: live definition disk
 * @newsrc: new source which should be also considered for the new disk
 *
 * For block jobs which modify the running disk source it is required that we
 * try our best to update the config XML's disk source as well in most cases.
 *
 * This helper finds the disk from the persistent definition corresponding to
 * @disk and updates its source to @newsrc.
 */
static void
qemuBlockJobRewriteConfigDiskSource(virDomainObjPtr vm,
                                    virDomainDiskDefPtr disk,
                                    virStorageSourcePtr newsrc)
{
    virDomainDiskDefPtr persistDisk = NULL;
659
    g_autoptr(virStorageSource) copy = NULL;
660
    virStorageSourcePtr n;
661 662 663 664

    if (!vm->newDef)
        return;

665
    if (!(persistDisk = virDomainDiskByTarget(vm->newDef, disk->dst)))
666 667
        return;

668 669 670
    if (!virStorageSourceIsSameLocation(disk->src, persistDisk->src))
        return;

671
    if (!(copy = virStorageSourceCopy(newsrc, true)) ||
672 673 674 675 676 677
        virStorageSourceInitChainElement(copy, persistDisk->src, true) < 0) {
        VIR_WARN("Unable to update persistent definition on vm %s after block job",
                 vm->def->name);
        return;
    }

678 679 680 681 682 683 684 685 686 687 688
    for (n = copy; virStorageSourceIsBacking(n); n = n->backingStore) {
        qemuBlockJobCleanStorageSourceRuntime(n);

        /* discard any detected backing store */
        if (virStorageSourceIsBacking(n->backingStore) &&
            n->backingStore->detected) {
            virObjectUnref(n->backingStore);
            n->backingStore = NULL;
            break;
        }
    }
689

690
    virObjectUnref(persistDisk->src);
691
    persistDisk->src = g_steal_pointer(&copy);
692 693 694
}


695 696 697
static void
qemuBlockJobEventProcessLegacyCompleted(virQEMUDriverPtr driver,
                                        virDomainObjPtr vm,
698
                                        qemuBlockJobDataPtr job,
699 700
                                        int asyncJob)
{
701
    virDomainDiskDefPtr disk = job->disk;
702

703 704 705
    if (!disk)
        return;

706
    if (disk->mirrorState == VIR_DOMAIN_DISK_MIRROR_STATE_PIVOT) {
707
        qemuBlockJobRewriteConfigDiskSource(vm, disk, disk->mirror);
708 709 710 711 712 713
        /* XXX We want to revoke security labels as well as audit that
         * revocation, before dropping the original source.  But it gets
         * tricky if both source and mirror share common backing files (we
         * want to only revoke the non-shared portion of the chain); so for
         * now, we leak the access to the original.  */
        virDomainLockImageDetach(driver->lockManager, vm, disk->src);
714 715

        /* Move secret driver metadata */
716 717 718 719 720 721 722 723
        if (qemuSecurityMoveImageMetadata(driver, vm, disk->src, disk->mirror) < 0) {
            VIR_WARN("Unable to move disk metadata on "
                     "vm %s from %s to %s (disk target %s)",
                     vm->def->name,
                     NULLSTR(disk->src->path),
                     NULLSTR(disk->mirror->path),
                     disk->dst);
        }
724

725
        virObjectUnref(disk->src);
726 727
        disk->src = disk->mirror;
    } else {
728
        if (disk->mirror) {
729
            virDomainLockImageDetach(driver->lockManager, vm, disk->mirror);
730 731 732 733

            /* Ideally, we would restore seclabels on the backing chain here
             * but we don't know if somebody else is not using parts of it.
             * Remove security driver metadata so that they are not leaked. */
734
            qemuBlockRemoveImageMetadata(driver, vm, disk->dst, disk->mirror);
735

736
            virObjectUnref(disk->mirror);
737
        }
738

739
        qemuBlockRemoveImageMetadata(driver, vm, disk->dst, disk->src);
740 741 742 743 744 745 746 747 748 749 750
    }

    /* Recompute the cached backing chain to match our
     * updates.  Better would be storing the chain ourselves
     * rather than reprobing, but we haven't quite completed
     * that conversion to use our XML tracking. */
    disk->mirror = NULL;
    disk->mirrorState = VIR_DOMAIN_DISK_MIRROR_STATE_NONE;
    disk->mirrorJob = VIR_DOMAIN_BLOCK_JOB_TYPE_UNKNOWN;
    disk->src->id = 0;
    virStorageSourceBackingStoreClear(disk->src);
751
    ignore_value(qemuDomainDetermineDiskChain(driver, vm, disk, NULL, true));
752
    ignore_value(qemuBlockNodeNamesDetect(driver, vm, asyncJob));
753
    qemuBlockJobUnregister(job, vm);
754
    qemuDomainSaveConfig(vm);
755 756 757
}


758
/**
759
 * qemuBlockJobEventProcessLegacy:
760 761
 * @driver: qemu driver
 * @vm: domain
762
 * @job: job to process events for
763 764 765 766 767
 *
 * Update disk's mirror state in response to a block job event
 * from QEMU. For mirror state's that must survive libvirt
 * restart, also update the domain's status XML.
 */
768
static void
769 770
qemuBlockJobEventProcessLegacy(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
771 772
                               qemuBlockJobDataPtr job,
                               int asyncJob)
773
{
774
    virDomainDiskDefPtr disk = job->disk;
775

776
    VIR_DEBUG("disk=%s, mirrorState=%s, type=%d, state=%d, newstate=%d",
777 778
              disk->dst,
              NULLSTR(virDomainDiskMirrorStateTypeToString(disk->mirrorState)),
779
              job->type,
780
              job->state,
781
              job->newstate);
782

783 784 785
    if (job->newstate == -1)
        return;

786
    qemuBlockJobEmitEvents(driver, vm, disk, job->type, job->newstate);
787

788 789 790
    job->state = job->newstate;
    job->newstate = -1;

791 792
    /* If we completed a block pull or commit, then update the XML
     * to match.  */
793
    switch ((virConnectDomainEventBlockJobStatus) job->state) {
794
    case VIR_DOMAIN_BLOCK_JOB_COMPLETED:
795
        qemuBlockJobEventProcessLegacyCompleted(driver, vm, job, asyncJob);
796 797 798 799
        break;

    case VIR_DOMAIN_BLOCK_JOB_READY:
        disk->mirrorState = VIR_DOMAIN_DISK_MIRROR_STATE_READY;
800
        qemuDomainSaveStatus(vm);
801 802 803 804
        break;

    case VIR_DOMAIN_BLOCK_JOB_FAILED:
    case VIR_DOMAIN_BLOCK_JOB_CANCELED:
805 806
        if (disk->mirror) {
            virDomainLockImageDetach(driver->lockManager, vm, disk->mirror);
807 808 809 810

            /* Ideally, we would restore seclabels on the backing chain here
             * but we don't know if somebody else is not using parts of it.
             * Remove security driver metadata so that they are not leaked. */
811
            qemuBlockRemoveImageMetadata(driver, vm, disk->dst, disk->mirror);
812

813
            virObjectUnref(disk->mirror);
814 815
            disk->mirror = NULL;
        }
816
        disk->mirrorState = VIR_DOMAIN_DISK_MIRROR_STATE_NONE;
817
        disk->mirrorJob = VIR_DOMAIN_BLOCK_JOB_TYPE_UNKNOWN;
818
        qemuBlockJobUnregister(job, vm);
819 820 821 822 823 824
        break;

    case VIR_DOMAIN_BLOCK_JOB_LAST:
        break;
    }
}
825 826


827 828 829 830 831 832
static void
qemuBlockJobEventProcessConcludedRemoveChain(virQEMUDriverPtr driver,
                                             virDomainObjPtr vm,
                                             qemuDomainAsyncJob asyncJob,
                                             virStorageSourcePtr chain)
{
J
Ján Tomko 已提交
833
    g_autoptr(qemuBlockStorageSourceChainData) data = NULL;
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848

    if (!(data = qemuBlockStorageSourceChainDetachPrepareBlockdev(chain)))
        return;

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return;

    qemuBlockStorageSourceChainDetach(qemuDomainGetMonitor(vm), data);
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return;

    qemuDomainStorageSourceChainAccessRevoke(driver, vm, chain);
}


849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
/**
 * qemuBlockJobGetConfigDisk:
 * @vm: domain object
 * @disk: disk from the running definition
 * @diskChainBottom: the last element of backing chain of @disk which is relevant
 *
 * Finds and returns the disk corresponding to @disk in the inactive definition.
 * The inactive disk must have the backing chain starting from the source until
 * @@diskChainBottom identical. If @diskChainBottom is NULL the whole backing
 * chains of both @disk and the persistent config definition equivalent must
 * be identical.
 */
static virDomainDiskDefPtr
qemuBlockJobGetConfigDisk(virDomainObjPtr vm,
                          virDomainDiskDefPtr disk,
                          virStorageSourcePtr diskChainBottom)
{
    virStorageSourcePtr disksrc = NULL;
    virStorageSourcePtr cfgsrc = NULL;
    virDomainDiskDefPtr ret = NULL;

    if (!vm->newDef || !disk)
        return NULL;

    disksrc = disk->src;

875
    if (!(ret = virDomainDiskByTarget(vm->newDef, disk->dst)))
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
        return NULL;

    cfgsrc = ret->src;

    while (disksrc && cfgsrc) {
        if (!virStorageSourceIsSameLocation(disksrc, cfgsrc))
            return NULL;

        if (diskChainBottom && diskChainBottom == disksrc)
            return ret;

        disksrc = disksrc->backingStore;
        cfgsrc = cfgsrc->backingStore;
    }

    if (disksrc || cfgsrc)
        return NULL;

    return ret;
}


/**
 * qemuBlockJobClearConfigChain:
 * @vm: domain object
 * @disk: disk object from running definition of @vm
 *
 * In cases when the backing chain definitions of the live disk differ from
 * the definition for the next start config and the backing chain would touch
 * it we'd not be able to restore the chain in the next start config properly.
 *
 * This function checks that the source of the running disk definition and the
 * config disk definition are the same and if such it clears the backing chain
 * data.
 */
static void
qemuBlockJobClearConfigChain(virDomainObjPtr vm,
                             virDomainDiskDefPtr disk)
{
    virDomainDiskDefPtr cfgdisk = NULL;

    if (!vm->newDef || !disk)
        return;

920
    if (!(cfgdisk = virDomainDiskByTarget(vm->newDef, disk->dst)))
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
        return;

    if (!virStorageSourceIsSameLocation(disk->src, cfgdisk->src))
        return;

    virObjectUnref(cfgdisk->src->backingStore);
    cfgdisk->src->backingStore = NULL;
}


/**
 * qemuBlockJobProcessEventCompletedPull:
 * @driver: qemu driver object
 * @vm: domain object
 * @job: job data
 * @asyncJob: qemu asynchronous job type (for monitor interaction)
 *
 * This function executes the finalizing steps after a successful block pull job
 * (block-stream in qemu terminology. The pull job copies all the data from the
 * images in the backing chain up to the 'base' image. The 'base' image becomes
 * the backing store of the active top level image. If 'base' was not used
 * everything is pulled into the top level image and the top level image will
 * cease to have backing store. All intermediate images between the active image
 * and base image are no longer required and can be unplugged.
 */
static void
qemuBlockJobProcessEventCompletedPull(virQEMUDriverPtr driver,
                                      virDomainObjPtr vm,
                                      qemuBlockJobDataPtr job,
                                      qemuDomainAsyncJob asyncJob)
{
    virStorageSourcePtr baseparent = NULL;
    virDomainDiskDefPtr cfgdisk = NULL;
    virStorageSourcePtr cfgbase = NULL;
    virStorageSourcePtr cfgbaseparent = NULL;
    virStorageSourcePtr n;
    virStorageSourcePtr tmp;

    VIR_DEBUG("pull job '%s' on VM '%s' completed", job->name, vm->def->name);

    /* if the job isn't associated with a disk there's nothing to do */
    if (!job->disk)
        return;

    if ((cfgdisk = qemuBlockJobGetConfigDisk(vm, job->disk, job->data.pull.base)))
        cfgbase = cfgdisk->src->backingStore;

    if (!cfgdisk)
        qemuBlockJobClearConfigChain(vm, job->disk);

    /* when pulling if 'base' is right below the top image we don't have to modify it */
    if (job->disk->src->backingStore == job->data.pull.base)
        return;

    if (job->data.pull.base) {
        for (n = job->disk->src->backingStore; n && n != job->data.pull.base; n = n->backingStore) {
            /* find the image on top of 'base' */

            if (cfgbase) {
                cfgbaseparent = cfgbase;
                cfgbase = cfgbase->backingStore;
            }

            baseparent = n;
        }
    }

    tmp = job->disk->src->backingStore;
    job->disk->src->backingStore = job->data.pull.base;
    if (baseparent)
        baseparent->backingStore = NULL;
    qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob, tmp);
    virObjectUnref(tmp);

    if (cfgdisk) {
        tmp = cfgdisk->src->backingStore;
        cfgdisk->src->backingStore = cfgbase;
        if (cfgbaseparent)
            cfgbaseparent->backingStore = NULL;
        virObjectUnref(tmp);
    }
}


1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
/**
 * qemuBlockJobDeleteImages:
 * @driver: qemu driver object
 * @vm: domain object
 * @disk: disk object that the chain to be deleted is associated with
 * @top: top snapshot of the chain to be deleted
 *
 * Helper for removing snapshot images.  Intended for callers like
 * qemuBlockJobProcessEventCompletedCommit() and
 * qemuBlockJobProcessEventCompletedActiveCommit() as it relies on adjustments
 * these functions perform on the 'backingStore' chain to function correctly.
 *
 * TODO look into removing backing store for non-local snapshots too
 */
static void
qemuBlockJobDeleteImages(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         virDomainDiskDefPtr disk,
                         virStorageSourcePtr top)
{
    virStorageSourcePtr p = top;
    g_autoptr(virQEMUDriverConfig) cfg = virQEMUDriverGetConfig(driver);
    uid_t uid;
    gid_t gid;

    for (; p != NULL; p = p->backingStore) {
        if (virStorageSourceGetActualType(p) == VIR_STORAGE_TYPE_FILE) {

            qemuDomainGetImageIds(cfg, vm, p, disk->src, &uid, &gid);

            if (virFileRemove(p->path, uid, gid) < 0) {
                VIR_WARN("Unable to remove snapshot image file '%s' (%s)",
                         p->path, g_strerror(errno));
            }
        }
    }
}

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
/**
 * qemuBlockJobProcessEventCompletedCommit:
 * @driver: qemu driver object
 * @vm: domain object
 * @job: job data
 * @asyncJob: qemu asynchronous job type (for monitor interaction)
 *
 * This function executes the finalizing steps after a successful block commit
 * job. The commit job moves the blocks from backing chain images starting from
 * 'top' into the 'base' image. The overlay of the 'top' image ('topparent')
 * then directly references the 'base' image. All intermediate images can be
 * removed/deleted.
 */
static void
qemuBlockJobProcessEventCompletedCommit(virQEMUDriverPtr driver,
                                        virDomainObjPtr vm,
                                        qemuBlockJobDataPtr job,
                                        qemuDomainAsyncJob asyncJob)
{
    virStorageSourcePtr baseparent = NULL;
    virDomainDiskDefPtr cfgdisk = NULL;
    virStorageSourcePtr cfgnext = NULL;
    virStorageSourcePtr cfgtopparent = NULL;
    virStorageSourcePtr cfgtop = NULL;
    virStorageSourcePtr cfgbase = NULL;
    virStorageSourcePtr cfgbaseparent = NULL;
    virStorageSourcePtr n;

    VIR_DEBUG("commit job '%s' on VM '%s' completed", job->name, vm->def->name);

    /* if the job isn't associated with a disk there's nothing to do */
    if (!job->disk)
        return;

    if ((cfgdisk = qemuBlockJobGetConfigDisk(vm, job->disk, job->data.commit.base)))
        cfgnext = cfgdisk->src;

    if (!cfgdisk)
        qemuBlockJobClearConfigChain(vm, job->disk);

    for (n = job->disk->src; n && n != job->data.commit.base; n = n->backingStore) {
        if (cfgnext) {
            if (n == job->data.commit.topparent)
                cfgtopparent = cfgnext;

            if (n == job->data.commit.top)
                cfgtop = cfgnext;

            cfgbaseparent = cfgnext;
            cfgnext = cfgnext->backingStore;
        }
        baseparent = n;
    }

    if (!n)
        return;

    /* revert access to images */
    qemuDomainStorageSourceAccessAllow(driver, vm, job->data.commit.base, true, false);
    if (job->data.commit.topparent != job->disk->src)
        qemuDomainStorageSourceAccessAllow(driver, vm, job->data.commit.topparent, true, false);

    baseparent->backingStore = NULL;
    job->data.commit.topparent->backingStore = job->data.commit.base;

    qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob, job->data.commit.top);
1109 1110 1111 1112

    if (job->data.commit.deleteCommittedImages)
        qemuBlockJobDeleteImages(driver, vm, job->disk, job->data.commit.top);

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    virObjectUnref(job->data.commit.top);
    job->data.commit.top = NULL;

    if (cfgbaseparent) {
        cfgbase = cfgbaseparent->backingStore;
        cfgbaseparent->backingStore = NULL;

        if (cfgtopparent)
            cfgtopparent->backingStore = cfgbase;
        else
            cfgdisk->src = cfgbase;

        virObjectUnref(cfgtop);
    }
}


/**
 * qemuBlockJobProcessEventCompletedActiveCommit:
 * @driver: qemu driver object
 * @vm: domain object
 * @job: job data
 * @asyncJob: qemu asynchronous job type (for monitor interaction)
 *
 * This function executes the finalizing steps after a successful active layer
 * block commit job. The commit job moves the blocks from backing chain images
 * starting from the active disk source image into the 'base' image. The disk
 * source then changes to the 'base' image. All intermediate images can be
 * removed/deleted.
 */
static void
qemuBlockJobProcessEventCompletedActiveCommit(virQEMUDriverPtr driver,
                                              virDomainObjPtr vm,
                                              qemuBlockJobDataPtr job,
                                              qemuDomainAsyncJob asyncJob)
{
    virStorageSourcePtr baseparent = NULL;
    virDomainDiskDefPtr cfgdisk = NULL;
    virStorageSourcePtr cfgnext = NULL;
    virStorageSourcePtr cfgtop = NULL;
    virStorageSourcePtr cfgbase = NULL;
    virStorageSourcePtr cfgbaseparent = NULL;
    virStorageSourcePtr n;

    VIR_DEBUG("active commit job '%s' on VM '%s' completed", job->name, vm->def->name);

    /* if the job isn't associated with a disk there's nothing to do */
    if (!job->disk)
        return;

    if ((cfgdisk = qemuBlockJobGetConfigDisk(vm, job->disk, job->data.commit.base)))
        cfgnext = cfgdisk->src;

    for (n = job->disk->src; n && n != job->data.commit.base; n = n->backingStore) {
        if (cfgnext) {
            if (n == job->data.commit.top)
                cfgtop = cfgnext;

            cfgbaseparent = cfgnext;
            cfgnext = cfgnext->backingStore;
        }
        baseparent = n;
    }

    if (!n)
        return;

    if (!cfgdisk) {
        /* in case when the config disk chain didn't match but the disk top seems
         * to be identical we need to modify the disk source since the active
         * commit makes the top level image invalid.
         */
        qemuBlockJobRewriteConfigDiskSource(vm, job->disk, job->data.commit.base);
    } else {
        cfgbase = cfgbaseparent->backingStore;
        cfgbaseparent->backingStore = NULL;
        cfgdisk->src = cfgbase;
1190
        cfgdisk->src->readonly = cfgtop->readonly;
1191 1192 1193 1194 1195 1196 1197 1198 1199
        virObjectUnref(cfgtop);
    }

    /* Move security driver metadata */
    if (qemuSecurityMoveImageMetadata(driver, vm, job->disk->src, job->data.commit.base) < 0)
        VIR_WARN("Unable to move disk metadata on vm %s", vm->def->name);

    baseparent->backingStore = NULL;
    job->disk->src = job->data.commit.base;
1200
    job->disk->src->readonly = job->data.commit.top->readonly;
1201 1202

    qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob, job->data.commit.top);
1203 1204 1205 1206

    if (job->data.commit.deleteCommittedImages)
        qemuBlockJobDeleteImages(driver, vm, job->disk, job->data.commit.top);

1207 1208 1209 1210 1211 1212 1213
    virObjectUnref(job->data.commit.top);
    job->data.commit.top = NULL;
    /* the mirror element does not serve functional purpose for the commit job */
    virObjectUnref(job->disk->mirror);
    job->disk->mirror = NULL;
}

1214

1215 1216 1217 1218 1219 1220 1221 1222
static void
qemuBlockJobProcessEventConcludedCopyPivot(virQEMUDriverPtr driver,
                                           virDomainObjPtr vm,
                                           qemuBlockJobDataPtr job,
                                           qemuDomainAsyncJob asyncJob)
{
    VIR_DEBUG("copy job '%s' on VM '%s' pivoted", job->name, vm->def->name);

1223 1224 1225
    /* mirror may be NULL for copy job corresponding to migration */
    if (!job->disk ||
        !job->disk->mirror)
1226 1227 1228 1229 1230 1231 1232 1233
        return;

    /* for shallow copy without reusing external image the user can either not
     * specify the backing chain in which case libvirt will open and use the
     * chain the user provided or not specify a chain in which case we'll
     * inherit the rest of the chain */
    if (job->data.copy.shallownew &&
        !virStorageSourceIsBacking(job->disk->mirror->backingStore))
1234
        job->disk->mirror->backingStore = g_steal_pointer(&job->disk->src->backingStore);
1235 1236 1237 1238 1239

    qemuBlockJobRewriteConfigDiskSource(vm, job->disk, job->disk->mirror);

    qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob, job->disk->src);
    virObjectUnref(job->disk->src);
1240
    job->disk->src = g_steal_pointer(&job->disk->mirror);
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
}


static void
qemuBlockJobProcessEventConcludedCopyAbort(virQEMUDriverPtr driver,
                                           virDomainObjPtr vm,
                                           qemuBlockJobDataPtr job,
                                           qemuDomainAsyncJob asyncJob)
{
    VIR_DEBUG("copy job '%s' on VM '%s' aborted", job->name, vm->def->name);

1252 1253 1254
    /* mirror may be NULL for copy job corresponding to migration */
    if (!job->disk ||
        !job->disk->mirror)
1255 1256 1257 1258 1259 1260 1261 1262
        return;

    qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob, job->disk->mirror);
    virObjectUnref(job->disk->mirror);
    job->disk->mirror = NULL;
}


1263
static void
1264 1265
qemuBlockJobProcessEventFailedActiveCommit(virQEMUDriverPtr driver,
                                           virDomainObjPtr vm,
1266 1267
                                           qemuBlockJobDataPtr job)
{
1268 1269
    virDomainDiskDefPtr disk = job->disk;

1270 1271
    VIR_DEBUG("active commit job '%s' on VM '%s' failed", job->name, vm->def->name);

1272
    if (!disk)
1273 1274
        return;

1275 1276 1277
    /* Ideally, we would make the backing chain read only again (yes, SELinux
     * can do that using different labels). But that is not implemented yet and
     * not leaking security driver metadata is more important. */
1278
    qemuBlockRemoveImageMetadata(driver, vm, disk->dst, disk->mirror);
1279 1280 1281

    virObjectUnref(disk->mirror);
    disk->mirror = NULL;
1282 1283 1284
}


1285 1286 1287 1288 1289 1290
static void
qemuBlockJobProcessEventConcludedCreate(virQEMUDriverPtr driver,
                                        virDomainObjPtr vm,
                                        qemuBlockJobDataPtr job,
                                        qemuDomainAsyncJob asyncJob)
{
J
Ján Tomko 已提交
1291
    g_autoptr(qemuBlockStorageSourceAttachData) backend = NULL;
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

    /* if there is a synchronous client waiting for this job that means that
     * it will handle further hotplug of the created volume and also that
     * the 'chain' which was registered is under their control */
    if (job->synchronous) {
        virObjectUnref(job->chain);
        job->chain = NULL;
        return;
    }

    if (!job->data.create.src)
        return;

    if (!(backend = qemuBlockStorageSourceDetachPrepare(job->data.create.src, NULL)))
        return;

    /* the format node part was not attached yet, so we don't need to detach it */
    backend->formatAttached = false;
    if (job->data.create.storage) {
        backend->storageAttached = false;
        VIR_FREE(backend->encryptsecretAlias);
    }

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return;

    qemuBlockStorageSourceAttachRollback(qemuDomainGetMonitor(vm), backend);

    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return;

    qemuDomainStorageSourceAccessRevoke(driver, vm, job->data.create.src);
}


1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
static void
qemuBlockJobProcessEventConcludedBackup(virQEMUDriverPtr driver,
                                        virDomainObjPtr vm,
                                        qemuBlockJobDataPtr job,
                                        qemuDomainAsyncJob asyncJob,
                                        qemuBlockjobState newstate,
                                        unsigned long long progressCurrent,
                                        unsigned long long progressTotal)
{
    g_autoptr(qemuBlockStorageSourceAttachData) backend = NULL;
    g_autoptr(virJSONValue) actions = NULL;

    qemuBackupNotifyBlockjobEnd(vm, job->disk, newstate, progressCurrent, progressTotal);

    if (job->data.backup.store &&
        !(backend = qemuBlockStorageSourceDetachPrepare(job->data.backup.store, NULL)))
        return;

    if (job->data.backup.bitmap) {
        if (!(actions = virJSONValueNewArray()))
            return;

        if (qemuMonitorTransactionBitmapRemove(actions,
                                               job->disk->src->nodeformat,
                                               job->data.backup.bitmap) < 0)
            return;
    }

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return;

    if (backend)
        qemuBlockStorageSourceAttachRollback(qemuDomainGetMonitor(vm), backend);

    if (actions)
        qemuMonitorTransaction(qemuDomainGetMonitor(vm), &actions);

    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return;

1367
    if (job->data.backup.store)
1368 1369 1370 1371
        qemuDomainStorageSourceAccessRevoke(driver, vm, job->data.backup.store);
}


1372 1373 1374 1375
static void
qemuBlockJobEventProcessConcludedTransition(qemuBlockJobDataPtr job,
                                            virQEMUDriverPtr driver,
                                            virDomainObjPtr vm,
1376 1377 1378
                                            qemuDomainAsyncJob asyncJob,
                                            unsigned long long progressCurrent,
                                            unsigned long long progressTotal)
1379
{
1380 1381 1382 1383 1384
    bool success = job->newstate == QEMU_BLOCKJOB_STATE_COMPLETED;

    switch ((qemuBlockJobType) job->type) {
    case QEMU_BLOCKJOB_TYPE_PULL:
        if (success)
1385
            qemuBlockJobProcessEventCompletedPull(driver, vm, job, asyncJob);
1386
        break;
1387

1388 1389
    case QEMU_BLOCKJOB_TYPE_COMMIT:
        if (success)
1390
            qemuBlockJobProcessEventCompletedCommit(driver, vm, job, asyncJob);
1391 1392
        break;

1393 1394 1395 1396
    case QEMU_BLOCKJOB_TYPE_ACTIVE_COMMIT:
        if (success)
            qemuBlockJobProcessEventCompletedActiveCommit(driver, vm, job, asyncJob);
        else
1397
            qemuBlockJobProcessEventFailedActiveCommit(driver, vm, job);
1398
        break;
1399

1400 1401 1402
    case QEMU_BLOCKJOB_TYPE_CREATE:
        qemuBlockJobProcessEventConcludedCreate(driver, vm, job, asyncJob);
        break;
1403

1404 1405 1406 1407
    case QEMU_BLOCKJOB_TYPE_COPY:
        if (job->state == QEMU_BLOCKJOB_STATE_PIVOTING && success)
            qemuBlockJobProcessEventConcludedCopyPivot(driver, vm, job, asyncJob);
        else
1408
            qemuBlockJobProcessEventConcludedCopyAbort(driver, vm, job, asyncJob);
1409 1410
        break;

P
Peter Krempa 已提交
1411
    case QEMU_BLOCKJOB_TYPE_BACKUP:
1412 1413 1414
        qemuBlockJobProcessEventConcludedBackup(driver, vm, job, asyncJob,
                                                job->newstate, progressCurrent,
                                                progressTotal);
P
Peter Krempa 已提交
1415
        break;
1416 1417

    case QEMU_BLOCKJOB_TYPE_BROKEN:
1418 1419 1420
    case QEMU_BLOCKJOB_TYPE_NONE:
    case QEMU_BLOCKJOB_TYPE_INTERNAL:
    case QEMU_BLOCKJOB_TYPE_LAST:
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
    default:
        break;
    }

    qemuBlockJobEmitEvents(driver, vm, job->disk, job->type, job->newstate);
    job->state = job->newstate;
    job->newstate = -1;
}


static void
qemuBlockJobEventProcessConcluded(qemuBlockJobDataPtr job,
                                  virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
                                  qemuDomainAsyncJob asyncJob)
{
    qemuMonitorJobInfoPtr *jobinfo = NULL;
    size_t njobinfo = 0;
    size_t i;
    bool refreshed = false;
1441 1442
    unsigned long long progressCurrent = 0;
    unsigned long long progressTotal = 0;
1443 1444 1445 1446 1447 1448

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        goto cleanup;

    /* we need to fetch the error state as the event does not propagate it */
    if (job->newstate == QEMU_BLOCKJOB_STATE_CONCLUDED &&
1449
        qemuMonitorGetJobInfo(qemuDomainGetMonitor(vm), &jobinfo, &njobinfo) == 0) {
1450 1451 1452 1453 1454

        for (i = 0; i < njobinfo; i++) {
            if (STRNEQ_NULLABLE(job->name, jobinfo[i]->id))
                continue;

1455 1456 1457
            progressCurrent = jobinfo[i]->progressCurrent;
            progressTotal = jobinfo[i]->progressTotal;

1458
            job->errmsg = g_strdup(jobinfo[i]->error);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

            if (job->errmsg)
                job->newstate = QEMU_BLOCKJOB_STATE_FAILED;
            else
                job->newstate = QEMU_BLOCKJOB_STATE_COMPLETED;

            refreshed = true;

            break;
        }

1470
        if (i == njobinfo)
1471 1472 1473 1474
            VIR_WARN("failed to refresh job '%s'", job->name);
    }

    /* dismiss job in qemu */
1475
    ignore_value(qemuMonitorJobDismiss(qemuDomainGetMonitor(vm), job->name));
1476

1477
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
1478 1479
        goto cleanup;

1480 1481
    if ((job->newstate == QEMU_BLOCKJOB_STATE_COMPLETED ||
         job->newstate == QEMU_BLOCKJOB_STATE_FAILED) &&
1482 1483 1484
        job->state == QEMU_BLOCKJOB_STATE_ABORTING)
        job->newstate = QEMU_BLOCKJOB_STATE_CANCELLED;

1485 1486 1487 1488 1489
    if (refreshed)
        qemuDomainSaveStatus(vm);

    VIR_DEBUG("handling job '%s' state '%d' newstate '%d'", job->name, job->state, job->newstate);

1490 1491
    qemuBlockJobEventProcessConcludedTransition(job, driver, vm, asyncJob,
                                                progressCurrent, progressTotal);
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    /* unplug the backing chains in case the job inherited them */
    if (!job->disk) {
        if (job->chain)
            qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob,
                                                         job->chain);
        if (job->mirrorChain)
            qemuBlockJobEventProcessConcludedRemoveChain(driver, vm, asyncJob,
                                                         job->mirrorChain);
    }

1503
 cleanup:
1504 1505
    qemuBlockJobUnregister(job, vm);
    qemuDomainSaveConfig(vm);
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528

    for (i = 0; i < njobinfo; i++)
        qemuMonitorJobInfoFree(jobinfo[i]);
    VIR_FREE(jobinfo);
}


static void
qemuBlockJobEventProcess(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         qemuBlockJobDataPtr job,
                         qemuDomainAsyncJob asyncJob)

{
    switch ((qemuBlockjobState) job->newstate) {
    case QEMU_BLOCKJOB_STATE_COMPLETED:
    case QEMU_BLOCKJOB_STATE_FAILED:
    case QEMU_BLOCKJOB_STATE_CANCELLED:
    case QEMU_BLOCKJOB_STATE_CONCLUDED:
        qemuBlockJobEventProcessConcluded(job, driver, vm, asyncJob);
        break;

    case QEMU_BLOCKJOB_STATE_READY:
1529 1530
        /* mirror may be NULL for copy job corresponding to migration */
        if (job->disk) {
1531
            job->disk->mirrorState = VIR_DOMAIN_DISK_MIRROR_STATE_READY;
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
            qemuBlockJobEmitEvents(driver, vm, job->disk, job->type, job->newstate);
        }
        job->state = job->newstate;
        job->newstate = -1;
        qemuDomainSaveStatus(vm);
        break;

    case QEMU_BLOCKJOB_STATE_NEW:
    case QEMU_BLOCKJOB_STATE_RUNNING:
    case QEMU_BLOCKJOB_STATE_LAST:
1542 1543 1544
    /* these are never processed as 'newstate' */
    case QEMU_BLOCKJOB_STATE_ABORTING:
    case QEMU_BLOCKJOB_STATE_PIVOTING:
1545 1546 1547 1548 1549 1550
    default:
        job->newstate = -1;
    }
}


1551
/**
1552
 * qemuBlockJobUpdate:
1553
 * @vm: domain
1554 1555
 * @job: job data
 * @asyncJob: current qemu asynchronous job type
1556 1557 1558 1559 1560 1561 1562
 *
 * Update disk's mirror state in response to a block job event stored in
 * blockJobStatus by qemuProcessHandleBlockJob event handler.
 *
 * Returns the block job event processed or -1 if there was no pending event.
 */
int
1563 1564 1565
qemuBlockJobUpdate(virDomainObjPtr vm,
                   qemuBlockJobDataPtr job,
                   int asyncJob)
1566 1567 1568
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

1569 1570 1571
    if (job->newstate == -1)
        return -1;

1572 1573 1574 1575
    if (virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_BLOCKDEV))
        qemuBlockJobEventProcess(priv->driver, vm, job, asyncJob);
    else
        qemuBlockJobEventProcessLegacy(priv->driver, vm, job, asyncJob);
1576

1577
    return job->state;
1578 1579 1580
}


1581
/**
1582 1583
 * qemuBlockJobSyncBegin:
 * @job: block job data
1584 1585 1586
 * @disk: domain disk
 *
 * Begin a new synchronous block job for @disk. The synchronous
1587
 * block job is ended by a call to qemuBlockJobSyncEnd, or by
1588 1589 1590 1591
 * the guest quitting.
 *
 * During a synchronous block job, a block job event for @disk
 * will not be processed asynchronously. Instead, it will be
1592
 * processed only when qemuBlockJobUpdate or qemuBlockJobSyncEnd
1593
 * is called.
1594 1595
 */
void
1596
qemuBlockJobSyncBegin(qemuBlockJobDataPtr job)
1597
{
1598
    const char *diskdst = NULL;
1599

1600 1601 1602 1603
    if (job->disk)
        diskdst = job->disk->dst;

    VIR_DEBUG("disk=%s", NULLSTR(diskdst));
1604
    job->synchronous = true;
1605 1606 1607 1608
}


/**
1609
 * qemuBlockJobSyncEnd:
1610 1611 1612 1613
 * @vm: domain
 * @disk: domain disk
 *
 * End a synchronous block job for @disk. Any pending block job event
1614 1615 1616
 * for the disk is processed. Note that it's not necessary to call this function
 * in case the block job was not started successfully if
 * qemuBlockJobStartupFinalize will be called.
1617 1618
 */
void
1619 1620 1621
qemuBlockJobSyncEnd(virDomainObjPtr vm,
                    qemuBlockJobDataPtr job,
                    int asyncJob)
1622
{
1623
    const char *diskdst = NULL;
1624

1625 1626
    if (job->disk)
        diskdst = job->disk->dst;
1627

1628
    VIR_DEBUG("disk=%s", NULLSTR(diskdst));
1629
    job->synchronous = false;
1630
    qemuBlockJobUpdate(vm, job, asyncJob);
1631
}
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643


qemuBlockJobDataPtr
qemuBlockJobGetByDisk(virDomainDiskDefPtr disk)
{
    qemuBlockJobDataPtr job = QEMU_DOMAIN_DISK_PRIVATE(disk)->blockjob;

    if (!job)
        return NULL;

    return virObjectRef(job);
}
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684


/**
 * @monitorstatus: Status of the blockjob from qemu monitor (qemuMonitorJobStatus)
 *
 * Converts the block job status from the monitor to the one used by
 * qemuBlockJobData. If the status is unknown or does not require any handling
 * QEMU_BLOCKJOB_TYPE_LAST is returned.
 */
qemuBlockjobState
qemuBlockjobConvertMonitorStatus(int monitorstatus)
{
    qemuBlockjobState ret = QEMU_BLOCKJOB_STATE_LAST;

    switch ((qemuMonitorJobStatus) monitorstatus) {
    case QEMU_MONITOR_JOB_STATUS_READY:
        ret = QEMU_BLOCKJOB_STATE_READY;
        break;

    case QEMU_MONITOR_JOB_STATUS_CONCLUDED:
        ret = QEMU_BLOCKJOB_STATE_CONCLUDED;
        break;

    case QEMU_MONITOR_JOB_STATUS_UNKNOWN:
    case QEMU_MONITOR_JOB_STATUS_CREATED:
    case QEMU_MONITOR_JOB_STATUS_RUNNING:
    case QEMU_MONITOR_JOB_STATUS_PAUSED:
    case QEMU_MONITOR_JOB_STATUS_STANDBY:
    case QEMU_MONITOR_JOB_STATUS_WAITING:
    case QEMU_MONITOR_JOB_STATUS_PENDING:
    case QEMU_MONITOR_JOB_STATUS_ABORTING:
    case QEMU_MONITOR_JOB_STATUS_UNDEFINED:
    case QEMU_MONITOR_JOB_STATUS_NULL:
    case QEMU_MONITOR_JOB_STATUS_LAST:
    default:
        break;
    }

    return ret;

}