You need to sign in or sign up before continuing.
openvz_driver.c 34.2 KB
Newer Older
1 2 3 4 5
/*
 * openvz_driver.c: core driver methods for managing OpenVZ VEs
 *
 * Copyright (C) 2006, 2007 Binary Karma
 * Copyright (C) 2006 Shuveb Hussain
6
 * Copyright (C) 2007 Anoop Joe Cyriac
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
22
 * Authors:
23 24 25
 * Shuveb Hussain <shuveb@binarykarma.com>
 * Anoop Joe Cyriac <anoop@binarykarma.com>
 *
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/wait.h>

50
#include "virterror_internal.h"
51
#include "datatypes.h"
52
#include "openvz_driver.h"
53 54
#include "event.h"
#include "buf.h"
55
#include "util.h"
56
#include "openvz_conf.h"
57
#include "nodeinfo.h"
58
#include "memory.h"
59
#include "bridge.h"
60

61 62 63
#define OPENVZ_MAX_ARG 28
#define CMDBUF_LEN 1488
#define CMDOP_LEN 288
64

D
Daniel Veillard 已提交
65
static int openvzGetProcessInfo(unsigned long long *cpuTime, int vpsid);
66 67 68
static int openvzGetMaxVCPUs(virConnectPtr conn, const char *type);
static int openvzDomainGetMaxVcpus(virDomainPtr dom);
static int openvzDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus);
D
Daniel Veillard 已提交
69

70 71
struct openvz_driver ovz_driver;

72
static void cmdExecFree(const char *cmdExec[])
73 74 75 76
{
    int i=-1;
    while(cmdExec[++i])
    {
77
        VIR_FREE(cmdExec[i]);
78 79 80
    }
}

81 82 83 84 85
/* generate arguments to create OpenVZ container
   return -1 - error
           0 - OK
*/
static int openvzDomainDefineCmd(virConnectPtr conn,
86
                                 const char *args[],
87
                                 int maxarg,
88
                                 virDomainDefPtr vmdef)
89 90 91 92 93 94 95 96
{
    int narg;

    for (narg = 0; narg < maxarg; narg++)
        args[narg] = NULL;

    if (vmdef == NULL){
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
97
                   "%s", _("Container is not defined"));
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        return -1;
    }

#define ADD_ARG(thisarg)                                                \
    do {                                                                \
        if (narg >= maxarg)                                             \
                 goto no_memory;                                        \
        args[narg++] = thisarg;                                         \
    } while (0)

#define ADD_ARG_LIT(thisarg)                                            \
    do {                                                                \
        if (narg >= maxarg)                                             \
                 goto no_memory;                                        \
        if ((args[narg++] = strdup(thisarg)) == NULL)                   \
            goto no_memory;                                             \
    } while (0)

    narg = 0;
    ADD_ARG_LIT(VZCTL);
    ADD_ARG_LIT("--quiet");
    ADD_ARG_LIT("create");
    ADD_ARG_LIT(vmdef->name);
121

122 123
    if (vmdef->nfss) {
        if (vmdef->fss[0]->type != VIR_DOMAIN_FS_TYPE_TEMPLATE) {
124 125 126 127
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                        "%s", _("only filesystem templates are supported"));
            return -1;
        }
128

129
        if (vmdef->nfss > 1) {
130 131 132 133
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                        "%s", _("only one filesystem supported"));
            return -1;
        }
134 135

        ADD_ARG_LIT("--ostemplate");
136
        ADD_ARG_LIT(vmdef->fss[0]->src);
137
    }
138
#if 0
139 140 141 142
    if ((vmdef->profile && *(vmdef->profile))) {
        ADD_ARG_LIT("--config");
        ADD_ARG_LIT(vmdef->profile);
    }
143
#endif
144 145 146 147 148 149 150 151 152 153 154 155

    ADD_ARG(NULL);
    return 0;
 no_memory:
    openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                _("Could not put argument to %s"), VZCTL);
    return -1;
#undef ADD_ARG
#undef ADD_ARG_LIT
}


156
static virDomainPtr openvzDomainLookupByID(virConnectPtr conn,
157
                                           int id) {
158
    struct openvz_driver *driver = conn->privateData;
159
    virDomainObjPtr vm;
160
    virDomainPtr dom = NULL;
161

162
    vm = virDomainFindByID(&driver->domains, id);
163
    if (!vm) {
164
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
165
        goto cleanup;
166 167
    }

168
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
169 170
    if (dom)
        dom->id = vm->def->id;
171

172
cleanup:
173 174 175
    return dom;
}

176
static int openvzGetVersion(virConnectPtr conn, unsigned long *version) {
177
    struct  openvz_driver *driver = conn->privateData;
178 179 180 181
    *version = driver->version;
    return 0;
}

182
static char *openvzGetOSType(virDomainPtr dom)
183
{
184 185 186
    struct  openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
187

188
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
189 190
    if (!vm) {
        openvzError(dom->conn, VIR_ERR_NO_DOMAIN, NULL);
191
        goto cleanup;
192 193 194 195 196
    }

    if (!(ret = strdup(vm->def->os.type)))
        openvzError(dom->conn, VIR_ERR_NO_MEMORY, NULL);

197
cleanup:
198
    return ret;
199 200 201 202
}


static virDomainPtr openvzDomainLookupByUUID(virConnectPtr conn,
203
                                             const unsigned char *uuid) {
204 205 206
    struct  openvz_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
207

208
    vm = virDomainFindByUUID(&driver->domains, uuid);
209
    if (!vm) {
210
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
211
        goto cleanup;
212 213
    }

214
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
215 216
    if (dom)
        dom->id = vm->def->id;
217

218
cleanup:
219 220 221 222
    return dom;
}

static virDomainPtr openvzDomainLookupByName(virConnectPtr conn,
223 224 225 226
                                             const char *name) {
    struct openvz_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
227

228
    vm = virDomainFindByName(&driver->domains, name);
229
    if (!vm) {
230
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
231
        goto cleanup;
232 233
    }

234
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
235 236
    if (dom)
        dom->id = vm->def->id;
237

238
cleanup:
239 240 241 242
    return dom;
}

static int openvzDomainGetInfo(virDomainPtr dom,
243
                               virDomainInfoPtr info) {
244 245 246
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
247

248
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
249
    if (!vm) {
D
Daniel Veillard 已提交
250
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
251
                    "%s", _("no domain with matching uuid"));
252
        goto cleanup;
253 254
    }

255
    info->state = vm->state;
256

257
    if (!virDomainIsActive(vm)) {
D
Daniel Veillard 已提交
258 259 260 261
        info->cpuTime = 0;
    } else {
        if (openvzGetProcessInfo(&(info->cpuTime), dom->id) < 0) {
            openvzError(dom->conn, VIR_ERR_OPERATION_FAILED,
262
                        _("cannot read cputime for domain %d"), dom->id);
263
            goto cleanup;
D
Daniel Veillard 已提交
264 265 266
        }
    }

267 268 269
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
270 271 272 273
    ret = 0;

cleanup:
    return ret;
274 275 276
}


277
static char *openvzDomainDumpXML(virDomainPtr dom, int flags) {
278 279 280
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
281

282
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
283
    if (!vm) {
D
Daniel Veillard 已提交
284
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
285
                    "%s", _("no domain with matching uuid"));
286
        goto cleanup;
287
    }
288

289 290 291 292
    ret = virDomainDefFormat(dom->conn, vm->def, flags);

cleanup:
    return ret;
293
}
294

295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
/*
 * Convenient helper to target a command line argv
 * and fill in an empty slot with the supplied
 * key value. This lets us declare the argv on the
 * stack and just splice in the domain name after
 */
#define PROGRAM_SENTINAL ((char *)0x1)
static void openvzSetProgramSentinal(const char **prog, const char *key)
{
    const char **tmp = prog;
    while (tmp && *tmp) {
        if (*tmp == PROGRAM_SENTINAL) {
            *tmp = key;
            break;
        }
        tmp++;
    }
}
314 315

static int openvzDomainShutdown(virDomainPtr dom) {
316 317 318 319
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *prog[] = {VZCTL, "--quiet", "stop", PROGRAM_SENTINAL, NULL};
    int ret = -1;
320

321
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
322 323
    if (!vm) {
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
324
                    "%s", _("no domain with matching uuid"));
325
        goto cleanup;
326
    }
327

328
    openvzSetProgramSentinal(prog, vm->def->name);
329
    if (vm->state != VIR_DOMAIN_RUNNING) {
D
Daniel Veillard 已提交
330
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
331
                    "%s", _("domain is not in running state"));
332
        goto cleanup;
333
    }
334

335
    if (virRun(dom->conn, prog, NULL) < 0)
336
        goto cleanup;
337

338 339
    vm->def->id = -1;
    vm->state = VIR_DOMAIN_SHUTOFF;
340
    ret = 0;
341

342 343
cleanup:
    return ret;
344 345
}

346 347
static int openvzDomainReboot(virDomainPtr dom,
                              unsigned int flags ATTRIBUTE_UNUSED) {
348 349 350 351
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *prog[] = {VZCTL, "--quiet", "restart", PROGRAM_SENTINAL, NULL};
    int ret = -1;
352

353
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
354
    if (!vm) {
D
Daniel Veillard 已提交
355
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
356
                    "%s", _("no domain with matching uuid"));
357
        goto cleanup;
358
    }
359

360
    openvzSetProgramSentinal(prog, vm->def->name);
361 362
    if (vm->state != VIR_DOMAIN_RUNNING) {
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
363
                    "%s", _("domain is not in running state"));
364
        goto cleanup;
365
    }
366

367
    if (virRun(dom->conn, prog, NULL) < 0)
368 369
        goto cleanup;
    ret = 0;
370

371 372
cleanup:
    return ret;
373 374
}

375 376 377 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 404 405 406 407 408 409 410 411 412 413 414
static char *
openvzGenerateVethName(int veid, char *dev_name_ve)
{
    char    dev_name[32];
    int     ifNo = 0;

    if (sscanf(dev_name_ve, "%*[^0-9]%d", &ifNo) != 1)
        return NULL;
    if (snprintf(dev_name, sizeof(dev_name), "veth%d.%d", veid, ifNo) < 7)
        return NULL;
    return strdup(dev_name);
}

static char *
openvzGenerateContainerVethName(int veid)
{
    int     ret;
    char    temp[1024];

    /* try to get line "^NETIF=..." from config */
    if ( (ret = openvzReadConfigParam(veid, "NETIF", temp, sizeof(temp))) <= 0) {
        snprintf(temp, sizeof(temp), "eth0");
    } else {
        char   *s;
        int     max = 0;

        /* get maximum interface number (actually, it is the last one) */
        for (s=strtok(temp, ";"); s; s=strtok(NULL, ";")) {
            int x;

            if (sscanf(s, "ifname=eth%d", &x) != 1) return NULL;
            if (x > max) max = x;
        }

        /* set new name */
        snprintf(temp, sizeof(temp), "eth%d", max+1);
    }
    return strdup(temp);
}

D
Daniel Veillard 已提交
415 416
static int
openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid,
417 418
                       virDomainNetDefPtr net,
                       virBufferPtr configBuf)
D
Daniel Veillard 已提交
419 420
{
    int rc = 0, narg;
421
    const char *prog[OPENVZ_MAX_ARG];
422
    char macaddr[VIR_MAC_STRING_BUFLEN];
423
    struct openvz_driver *driver =  conn->privateData;
424
    char *opt = NULL;
D
Daniel Veillard 已提交
425 426 427 428 429 430 431 432 433 434 435 436 437 438

#define ADD_ARG_LIT(thisarg)                                            \
    do {                                                                \
        if (narg >= OPENVZ_MAX_ARG)                                             \
                 goto no_memory;                                        \
        if ((prog[narg++] = strdup(thisarg)) == NULL)                   \
            goto no_memory;                                             \
    } while (0)


    if (net == NULL)
       return 0;
    if (vpsid == NULL) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
439
                    "%s", _("Container ID is not specified"));
D
Daniel Veillard 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        return -1;
    }

    for (narg = 0; narg < OPENVZ_MAX_ARG; narg++)
        prog[narg] = NULL;

    narg = 0;

    if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE ||
        net->type == VIR_DOMAIN_NET_TYPE_ETHERNET) {
        ADD_ARG_LIT(VZCTL);
        ADD_ARG_LIT("--quiet");
        ADD_ARG_LIT("set");
        ADD_ARG_LIT(vpsid);
    }

456 457 458 459 460 461
    virFormatMacAddr(net->mac, macaddr);

    if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
        virBuffer buf = VIR_BUFFER_INITIALIZER;
        char *dev_name_ve;
        int veid = strtoI(vpsid);
D
Daniel Veillard 已提交
462 463 464

        //--netif_add ifname[,mac,host_ifname,host_mac]
        ADD_ARG_LIT("--netif_add") ;
465 466 467 468 469

        /* generate interface name in ve and copy it to options */
        dev_name_ve = openvzGenerateContainerVethName(veid);
        if (dev_name_ve == NULL) {
           openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
470
                       "%s", _("Could not generate eth name for container"));
471 472 473 474 475 476 477 478 479 480
           rc = -1;
           goto exit;
        }

        /* if user doesn't specified host interface name,
         * than we need to generate it */
        if (net->ifname == NULL) {
            net->ifname = openvzGenerateVethName(veid, dev_name_ve);
            if (net->ifname == NULL) {
               openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
481
                           "%s", _("Could not generate veth name"));
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
               rc = -1;
               VIR_FREE(dev_name_ve);
               goto exit;
            }
        }

        virBufferAdd(&buf, dev_name_ve, -1); /* Guest dev */
        virBufferVSprintf(&buf, ",%s", macaddr); /* Guest dev mac */
        virBufferVSprintf(&buf, ",%s", net->ifname); /* Host dev */
        virBufferVSprintf(&buf, ",%s", macaddr); /* Host dev mac */

        if (driver->version >= VZCTL_BRIDGE_MIN_VERSION) {
            virBufferVSprintf(&buf, ",%s", net->data.bridge.brname); /* Host bridge */
        } else {
            virBufferVSprintf(configBuf, "ifname=%s", dev_name_ve);
            virBufferVSprintf(configBuf, ",mac=%s", macaddr); /* Guest dev mac */
            virBufferVSprintf(configBuf, ",host_ifname=%s", net->ifname); /* Host dev */
            virBufferVSprintf(configBuf, ",host_mac=%s", macaddr); /* Host dev mac */
            virBufferVSprintf(configBuf, ",bridge=%s", net->data.bridge.brname); /* Host bridge */
D
Daniel Veillard 已提交
501
        }
502 503 504 505 506 507

        VIR_FREE(dev_name_ve);

        if (!(opt = virBufferContentAndReset(&buf)))
            goto no_memory;

D
Daniel Veillard 已提交
508
        ADD_ARG_LIT(opt) ;
509 510
        VIR_FREE(opt);
    } else if (net->type == VIR_DOMAIN_NET_TYPE_ETHERNET &&
D
Daniel Veillard 已提交
511 512 513 514 515 516 517 518 519 520
              net->data.ethernet.ipaddr != NULL) {
        //--ipadd ip
        ADD_ARG_LIT("--ipadd") ;
        ADD_ARG_LIT(net->data.ethernet.ipaddr) ;
    }

    //TODO: processing NAT and physical device

    if (prog[0] != NULL){
        ADD_ARG_LIT("--save");
521
        if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
522 523 524 525 526 527 528 529 530 531 532 533
           openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not exec %s"), VZCTL);
           rc = -1;
           goto exit;
        }
    }

 exit:
    cmdExecFree(prog);
    return rc;

 no_memory:
534
    VIR_FREE(opt);
D
Daniel Veillard 已提交
535 536 537 538 539 540 541 542
    openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                _("Could not put argument to %s"), VZCTL);
    cmdExecFree(prog);
    return -1;

#undef ADD_ARG_LIT
}

543 544 545 546 547 548 549 550 551

static int
openvzDomainSetNetworkConfig(virConnectPtr conn,
                             virDomainDefPtr def)
{
    unsigned int i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *param;
    int first = 1;
552
    struct openvz_driver *driver =  conn->privateData;
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

    for (i = 0 ; i < def->nnets ; i++) {
        if (driver->version < VZCTL_BRIDGE_MIN_VERSION &&
            def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            if (first)
                first = 0;
            else
                virBufferAddLit(&buf, ";");
        }

        if (openvzDomainSetNetwork(conn, def->name, def->nets[i], &buf) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                        "%s", _("Could not configure network"));
            goto exit;
        }
    }

    if (driver->version < VZCTL_BRIDGE_MIN_VERSION && def->nnets) {
        param = virBufferContentAndReset(&buf);
        if (param) {
            if (openvzWriteConfigParam(strtoI(def->name), "NETIF", param) < 0) {
                VIR_FREE(param);
                openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                            "%s", _("cannot replace NETIF config"));
                return -1;
            }
            VIR_FREE(param);
        }
    }

    return 0;

exit:
    param = virBufferContentAndReset(&buf);
    VIR_FREE(param);
    return -1;
}


592 593 594
static virDomainPtr
openvzDomainDefineXML(virConnectPtr conn, const char *xml)
{
595
    struct openvz_driver *driver =  conn->privateData;
596 597
    virDomainDefPtr vmdef = NULL;
    virDomainObjPtr vm = NULL;
598
    virDomainPtr dom = NULL;
599
    const char *prog[OPENVZ_MAX_ARG];
600
    prog[0] = NULL;
601

602
    if ((vmdef = virDomainDefParseString(conn, driver->caps, xml)) == NULL)
603
        goto cleanup;
604

605 606
    if (vmdef->os.init == NULL &&
        !(vmdef->os.init = strdup("/sbin/init"))) {
607
        goto cleanup;
608 609
    }

610
    vm = virDomainFindByName(&driver->domains, vmdef->name);
611
    if (vm) {
612 613
        openvzError(conn, VIR_ERR_OPERATION_FAILED,
                  _("Already an OPENVZ VM active with the id '%s'"),
614
                  vmdef->name);
615
        goto cleanup;
616
    }
617 618 619
    if (!(vm = virDomainAssignDef(conn, &driver->domains, vmdef)))
        goto cleanup;
    vmdef = NULL;
620

621
    if (openvzDomainDefineCmd(conn, prog, OPENVZ_MAX_ARG, vm->def) < 0) {
622
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
623
                "%s", _("Error creating command for container"));
624
        goto cleanup;
625 626
    }

D
Daniel Veillard 已提交
627 628
    //TODO: set quota

629
    if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
630
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
631
               _("Could not exec %s"), VZCTL);
632
        goto cleanup;
633
    }
634

635
    if (openvzSetDefinedUUID(strtoI(vm->def->name), vm->def->uuid) < 0) {
636
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
637
               "%s", _("Could not set UUID"));
638
        goto cleanup;
639 640
    }

641 642
    if (openvzDomainSetNetworkConfig(conn, vm->def) < 0)
        goto cleanup;
D
Daniel Veillard 已提交
643

644 645
    if (vm->def->vcpus > 0) {
        if (openvzDomainSetVcpus(dom, vm->def->vcpus) < 0) {
646
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
647
                     "%s", _("Could not set number of virtual cpu"));
648
             goto cleanup;
649 650 651
        }
    }

652 653 654 655 656 657
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = -1;

cleanup:
    virDomainDefFree(vmdef);
658
    cmdExecFree(prog);
659 660 661 662
    return dom;
}

static virDomainPtr
663
openvzDomainCreateXML(virConnectPtr conn, const char *xml,
664 665
                        unsigned int flags ATTRIBUTE_UNUSED)
{
666
    struct openvz_driver *driver =  conn->privateData;
667 668
    virDomainDefPtr vmdef = NULL;
    virDomainObjPtr vm = NULL;
669
    virDomainPtr dom = NULL;
670
    const char *progstart[] = {VZCTL, "--quiet", "start", PROGRAM_SENTINAL, NULL};
671
    const char *progcreate[OPENVZ_MAX_ARG];
672
    progcreate[0] = NULL;
673

674
    if ((vmdef = virDomainDefParseString(conn, driver->caps, xml)) == NULL)
675
        goto cleanup;
676 677

    if (vmdef->os.init == NULL &&
678 679
        !(vmdef->os.init = strdup("/sbin/init")))
        goto cleanup;
680

681
    vm = virDomainFindByName(&driver->domains, vmdef->name);
682
    if (vm) {
683 684 685
        openvzError(conn, VIR_ERR_OPERATION_FAILED,
                  _("Already an OPENVZ VM defined with the id '%s'"),
                  vmdef->name);
686
        goto cleanup;
687
    }
688 689 690
    if (!(vm = virDomainAssignDef(conn, &driver->domains, vmdef)))
        goto cleanup;
    vmdef = NULL;
691

692
    if (openvzDomainDefineCmd(conn, progcreate, OPENVZ_MAX_ARG, vm->def) < 0) {
693
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
694 695
                    "%s", _("Error creating command for container"));
        goto cleanup;
696 697
    }

698
    if (virRun(conn, progcreate, NULL) < 0) {
D
Daniel Veillard 已提交
699
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
700
               _("Could not exec %s"), VZCTL);
701
        goto cleanup;
702
    }
703

704
    if (openvzSetDefinedUUID(strtoI(vm->def->name), vm->def->uuid) < 0) {
705
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
706
               "%s", _("Could not set UUID"));
707
        goto cleanup;
708 709
    }

710 711
    if (openvzDomainSetNetworkConfig(conn, vm->def) < 0)
        goto cleanup;
D
Daniel Veillard 已提交
712

713
    openvzSetProgramSentinal(progstart, vm->def->name);
714

715
    if (virRun(conn, progstart, NULL) < 0) {
D
Daniel Veillard 已提交
716
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
717
               _("Could not exec %s"), VZCTL);
718
        goto cleanup;
719
    }
720

721
    vm->pid = strtoI(vm->def->name);
722 723
    vm->def->id = vm->pid;
    vm->state = VIR_DOMAIN_RUNNING;
724

725 726
    if (vm->def->vcpus > 0) {
        if (openvzDomainSetVcpus(dom, vm->def->vcpus) < 0) {
727
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
728
                        "%s", _("Could not set number of virtual cpu"));
729
            goto cleanup;
730 731 732
        }
    }

733 734 735 736 737 738
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (dom)
        dom->id = vm->def->id;

cleanup:
    virDomainDefFree(vmdef);
739
    cmdExecFree(progcreate);
740 741 742 743 744 745
    return dom;
}

static int
openvzDomainCreate(virDomainPtr dom)
{
746 747 748 749
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *prog[] = {VZCTL, "--quiet", "start", PROGRAM_SENTINAL, NULL };
    int ret = -1;
750

751
    vm = virDomainFindByName(&driver->domains, dom->name);
752
    if (!vm) {
D
Daniel Veillard 已提交
753
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
754 755
                    "%s", _("no domain with matching id"));
        goto cleanup;
756
    }
757

758
    if (vm->state != VIR_DOMAIN_SHUTOFF) {
D
Daniel Veillard 已提交
759
        openvzError(dom->conn, VIR_ERR_OPERATION_DENIED,
760 761
                    "%s", _("domain is not in shutoff state"));
        goto cleanup;
762 763
    }

764
    openvzSetProgramSentinal(prog, vm->def->name);
765
    if (virRun(dom->conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
766
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
767 768
                    _("Could not exec %s"), VZCTL);
        goto cleanup;
769
    }
770

771 772 773
    vm->pid = strtoI(vm->def->name);
    vm->def->id = vm->pid;
    vm->state = VIR_DOMAIN_RUNNING;
774
    ret = 0;
775

776 777
cleanup:
    return ret;
778 779 780 781 782
}

static int
openvzDomainUndefine(virDomainPtr dom)
{
783 784 785 786
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *prog[] = { VZCTL, "--quiet", "destroy", PROGRAM_SENTINAL, NULL };
    int ret = -1;
787

788
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
789
    if (!vm) {
790 791
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN, "%s", _("no domain with matching uuid"));
        goto cleanup;
792
    }
793

794
    if (virDomainIsActive(vm)) {
795 796
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR, "%s", _("cannot delete active domain"));
        goto cleanup;
797
    }
798

799 800 801 802 803
    openvzSetProgramSentinal(prog, vm->def->name);
    if (virRun(dom->conn, prog, NULL) < 0) {
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not exec %s"), VZCTL);
        goto cleanup;
804
    }
805

806
    virDomainRemoveInactive(&driver->domains, vm);
807
    ret = 0;
808

809 810
cleanup:
    return ret;
811 812
}

813 814 815
static int
openvzDomainSetAutostart(virDomainPtr dom, int autostart)
{
816 817 818
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    const char *prog[] = { VZCTL, "--quiet", "set", PROGRAM_SENTINAL,
D
Daniel Veillard 已提交
819
                           "--onboot", autostart ? "yes" : "no",
820
                           "--save", NULL };
821
    int ret = -1;
822

823
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
824
    if (!vm) {
825 826
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN, "%s", _("no domain with matching uuid"));
        goto cleanup;
827 828
    }

829 830 831 832
    openvzSetProgramSentinal(prog, vm->def->name);
    if (virRun(dom->conn, prog, NULL) < 0) {
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR, _("Could not exec %s"), VZCTL);
        goto cleanup;
833
    }
834
    ret = 0;
835

836 837
cleanup:
    return ret;
838 839 840 841 842
}

static int
openvzDomainGetAutostart(virDomainPtr dom, int *autostart)
{
843 844
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
845
    char value[1024];
846
    int ret = -1;
847

848
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
849
    if (!vm) {
850 851 852
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                    "%s", _("no domain with matching uuid"));
        goto cleanup;
853 854
    }

855
    if (openvzReadConfigParam(strtoI(vm->def->name), "ONBOOT", value, sizeof(value)) < 0) {
856 857 858
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
                    "%s", _("Could not read container config"));
        goto cleanup;
859 860 861 862
    }

    *autostart = 0;
    if (STREQ(value,"yes"))
D
Daniel Veillard 已提交
863
        *autostart = 1;
864
    ret = 0;
865

866 867
cleanup:
    return ret;
868 869
}

870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
static int openvzGetMaxVCPUs(virConnectPtr conn, const char *type) {
    if (STRCASEEQ(type, "openvz"))
        return 1028; //OpenVZ has no limitation

    openvzError(conn, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
    return -1;
}


static int openvzDomainGetMaxVcpus(virDomainPtr dom) {
    return openvzGetMaxVCPUs(dom->conn, "openvz");
}

static int openvzDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
885 886
    struct openvz_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
887
    char   str_vcpus[32];
888
    const char *prog[] = { VZCTL, "--quiet", "set", PROGRAM_SENTINAL,
889
                           "--cpus", str_vcpus, "--save", NULL };
890
    unsigned int pcpus;
891
    int ret = -1;
892

893
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
894
    if (!vm) {
895
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
896
                    "%s", _("no domain with matching uuid"));
897
        goto cleanup;
898 899
    }

900
    if (nvcpus <= 0) {
901
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
902
                    "%s", _("VCPUs should be >= 1"));
903
        goto cleanup;
904 905
    }

906 907 908 909
    pcpus = openvzGetNodeCPUs();
    if (pcpus > 0 && pcpus < nvcpus)
        nvcpus = pcpus;

910 911 912
    snprintf(str_vcpus, 31, "%d", nvcpus);
    str_vcpus[31] = '\0';

913 914 915
    openvzSetProgramSentinal(prog, vm->def->name);
    if (virRun(dom->conn, prog, NULL) < 0) {
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
916
                    _("Could not exec %s"), VZCTL);
917
        goto cleanup;
918 919
    }

920
    vm->def->vcpus = nvcpus;
921 922 923 924
    ret = 0;

cleanup:
    return ret;
925 926
}

927
static int openvzProbe(void)
928
{
929 930 931 932 933
    if (geteuid() == 0 &&
        virFileExists("/proc/vz"))
        return 1;

    return 0;
934 935
}

936
static virDrvOpenStatus openvzOpen(virConnectPtr conn,
937 938
                                   virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                   int flags ATTRIBUTE_UNUSED)
939
{
940
    struct openvz_driver *driver;
941
    if (!openvzProbe())
942
        return VIR_DRV_OPEN_DECLINED;
943 944 945 946 947 948 949 950 951 952 953

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI("openvz:///system");
        if (conn->uri == NULL) {
            openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
            return VIR_DRV_OPEN_ERROR;
        }
    } else if (conn->uri->scheme == NULL ||
               conn->uri->path == NULL ||
               STRNEQ (conn->uri->scheme, "openvz") ||
               STRNEQ (conn->uri->path, "/system")) {
954 955 956 957 958 959 960 961 962 963
        return VIR_DRV_OPEN_DECLINED;
    }

    if (VIR_ALLOC(driver) < 0) {
        openvzError(conn, VIR_ERR_NO_MEMORY, NULL);
        return VIR_DRV_OPEN_ERROR;
    }

    if (!(driver->caps = openvzCapsInit()))
        goto cleanup;
964

965 966
    if (openvzLoadDomains(driver) < 0)
        goto cleanup;
967

968 969 970
    if (openvzExtractVersion(conn, driver) < 0)
        goto cleanup;

971
    conn->privateData = driver;
972

973
    return VIR_DRV_OPEN_SUCCESS;
974

975 976 977
cleanup:
    openvzFreeDriver(driver);
    return VIR_DRV_OPEN_ERROR;
978
};
979 980

static int openvzClose(virConnectPtr conn) {
981
    struct openvz_driver *driver = conn->privateData;
982

983
    openvzFreeDriver(driver);
984 985 986 987 988 989 990 991 992
    conn->privateData = NULL;

    return 0;
}

static const char *openvzGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
    return strdup("OpenVZ");
}

993 994 995 996 997
static int openvzGetNodeInfo(virConnectPtr conn,
                             virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
}

998
static char *openvzGetCapabilities(virConnectPtr conn) {
999 1000 1001 1002
    struct openvz_driver *driver = conn->privateData;
    char *ret;

    ret = virCapabilitiesFormatXML(driver->caps);
1003

1004
    return ret;
1005 1006
}

1007 1008
static int openvzListDomains(virConnectPtr conn, int *ids, int nids) {
    int got = 0;
1009 1010 1011
    int veid, pid;
    int outfd = -1;
    int errfd = -1;
1012 1013
    int ret;
    char buf[32];
1014
    char *endptr;
1015
    const char *cmd[] = {VZLIST, "-ovpsid", "-H" , NULL};
1016

1017 1018
    ret = virExec(conn, cmd, NULL, NULL,
                  &pid, -1, &outfd, &errfd, VIR_EXEC_NONE);
1019
    if(ret == -1) {
D
Daniel Veillard 已提交
1020
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
1021
               _("Could not exec %s"), VZLIST);
D
Daniel P. Berrange 已提交
1022
        return -1;
1023 1024
    }

1025 1026 1027
    while(got < nids){
        ret = openvz_readline(outfd, buf, 32);
        if(!ret) break;
1028 1029 1030 1031 1032
        if (virStrToLong_i(buf, &endptr, 10, &veid) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not parse VPS ID %s"), buf);
            continue;
        }
1033 1034 1035
        ids[got] = veid;
        got ++;
    }
1036
    waitpid(pid, NULL, 0);
1037 1038 1039 1040

    return got;
}

1041
static int openvzNumDomains(virConnectPtr conn) {
1042
    struct openvz_driver *driver = conn->privateData;
1043 1044 1045 1046
    int nactive = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (virDomainIsActive(driver->domains.objs[i]))
1047
            nactive++;
1048

1049
    return nactive;
1050 1051 1052
}

static int openvzListDefinedDomains(virConnectPtr conn,
1053
                                    char **const names, int nnames) {
1054
    int got = 0;
1055
    int veid, pid, outfd = -1, errfd = -1, ret;
1056
    char vpsname[32];
1057
    char buf[32];
1058
    char *endptr;
1059
    const char *cmd[] = {VZLIST, "-ovpsid", "-H", "-S", NULL};
1060 1061

    /* the -S options lists only stopped domains */
1062 1063
    ret = virExec(conn, cmd, NULL, NULL,
                  &pid, -1, &outfd, &errfd, VIR_EXEC_NONE);
1064
    if(ret == -1) {
D
Daniel Veillard 已提交
1065
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
1066
               _("Could not exec %s"), VZLIST);
D
Daniel P. Berrange 已提交
1067
        return -1;
1068 1069
    }

1070 1071 1072
    while(got < nnames){
        ret = openvz_readline(outfd, buf, 32);
        if(!ret) break;
1073 1074 1075 1076 1077
        if (virStrToLong_i(buf, &endptr, 10, &veid) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not parse VPS ID %s"), buf);
            continue;
        }
1078 1079 1080
        snprintf(vpsname, sizeof(vpsname), "%d", veid);
        if (!(names[got] = strdup(vpsname)))
            goto no_memory;
1081 1082
        got ++;
    }
1083
    waitpid(pid, NULL, 0);
1084
    return got;
1085 1086 1087 1088 1089 1090

no_memory:
    openvzError(conn, VIR_ERR_NO_MEMORY, NULL);
    for ( ; got >= 0 ; got--)
        VIR_FREE(names[got]);
    return -1;
1091 1092
}

D
Daniel Veillard 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 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
static int openvzGetProcessInfo(unsigned long long *cpuTime, int vpsid) {
    int fd;
    char line[1024] ;
    unsigned long long usertime, systime, nicetime;
    int readvps = 0, ret;

/* read statistic from /proc/vz/vestat.
sample:
Version: 2.2
      VEID     user      nice     system     uptime                 idle   other..
        33       78         0       1330   59454597      142650441835148   other..
        55      178         0       5340   59424597      542650441835148   other..
*/

    if ((fd = open("/proc/vz/vestat", O_RDONLY)) == -1)
        return -1;

    /*search line with VEID=vpsid*/
    while(1) {
        ret = openvz_readline(fd, line, sizeof(line));
        if(ret <= 0)
            break;

        if (sscanf(line, "%d %llu %llu %llu",
                          &readvps, &usertime, &nicetime, &systime) != 4)
            continue;

        if (readvps == vpsid)
            break; /*found vpsid*/
    }

    close(fd);
    if (ret < 0)
        return -1;

    if (readvps != vpsid) /*not found*/
        return -1;

    /* convert jiffies to nanoseconds */
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + nicetime  + systime)
                                     / (unsigned long long)sysconf(_SC_CLK_TCK);

    return 0;
}

1138
static int openvzNumDefinedDomains(virConnectPtr conn) {
1139
    struct openvz_driver *driver =  conn->privateData;
1140 1141 1142 1143
    int ninactive = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
1144
            ninactive++;
1145

1146
    return ninactive;
1147 1148 1149 1150 1151 1152 1153
}

static virDriver openvzDriver = {
    VIR_DRV_OPENVZ,
    "OPENVZ",
    openvzOpen, /* open */
    openvzClose, /* close */
1154
    NULL, /* supports_feature */
1155
    openvzGetType, /* type */
1156
    openvzGetVersion, /* version */
1157 1158
    NULL, /* hostname */
    NULL, /* uri */
1159
    openvzGetMaxVCPUs, /* getMaxVcpus */
1160
    openvzGetNodeInfo, /* nodeGetInfo */
1161
    openvzGetCapabilities, /* getCapabilities */
1162 1163
    openvzListDomains, /* listDomains */
    openvzNumDomains, /* numOfDomains */
1164
    openvzDomainCreateXML, /* domainCreateXML */
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    openvzDomainLookupByID, /* domainLookupByID */
    openvzDomainLookupByUUID, /* domainLookupByUUID */
    openvzDomainLookupByName, /* domainLookupByName */
    NULL, /* domainSuspend */
    NULL, /* domainResume */
    openvzDomainShutdown, /* domainShutdown */
    openvzDomainReboot, /* domainReboot */
    openvzDomainShutdown, /* domainDestroy */
    openvzGetOSType, /* domainGetOSType */
    NULL, /* domainGetMaxMemory */
    NULL, /* domainSetMaxMemory */
    NULL, /* domainSetMemory */
    openvzDomainGetInfo, /* domainGetInfo */
    NULL, /* domainSave */
    NULL, /* domainRestore */
    NULL, /* domainCoreDump */
1181
    openvzDomainSetVcpus, /* domainSetVcpus */
1182 1183
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
1184
    openvzDomainGetMaxVcpus, /* domainGetMaxVcpus */
1185
    openvzDomainDumpXML, /* domainDumpXML */
1186 1187 1188
    openvzListDefinedDomains, /* listDomains */
    openvzNumDefinedDomains, /* numOfDomains */
    openvzDomainCreate, /* domainCreate */
1189 1190
    openvzDomainDefineXML, /* domainDefineXML */
    openvzDomainUndefine, /* domainUndefine */
1191 1192
    NULL, /* domainAttachDevice */
    NULL, /* domainDetachDevice */
1193 1194
    openvzDomainGetAutostart, /* domainGetAutostart */
    openvzDomainSetAutostart, /* domainSetAutostart */
1195 1196 1197
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
1198 1199 1200 1201 1202
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
D
Daniel P. Berrange 已提交
1203 1204
    NULL, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
1205
    NULL, /* nodeGetCellsFreeMemory */
1206
    NULL, /* nodeGetFreeMemory */
1207 1208
    NULL, /* domainEventRegister */
    NULL, /* domainEventDeregister */
D
Daniel Veillard 已提交
1209 1210
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
1211 1212 1213 1214 1215 1216 1217
};

int openvzRegister(void) {
    virRegisterDriver(&openvzDriver);
    return 0;
}