openvz_driver.c 33.5 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 = (struct openvz_driver *)conn->privateData;
159
    virDomainObjPtr vm;
160 161
    virDomainPtr dom;

162
    vm = virDomainFindByID(&driver->domains, id);
163

164
    if (!vm) {
165
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
166 167 168
        return NULL;
    }

169 170
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (!dom)
171 172
        return NULL;

173
    dom->id = vm->def->id;
174 175 176
    return dom;
}

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

183
static char *openvzGetOSType(virDomainPtr dom)
184
{
185
    struct  openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
186
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
187 188 189 190 191 192 193 194 195 196 197
    char *ret;

    if (!vm) {
        openvzError(dom->conn, VIR_ERR_NO_DOMAIN, NULL);
        return NULL;
    }

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

    return ret;
198 199 200 201
}


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

    if (!vm) {
208
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
209 210 211
        return NULL;
    }

212 213
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (!dom)
214 215
        return NULL;

216
    dom->id = vm->def->id;
217 218 219 220 221 222
    return dom;
}

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

    if (!vm) {
227
        openvzError(conn, VIR_ERR_NO_DOMAIN, NULL);
228 229 230
        return NULL;
    }

231 232
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
    if (!dom)
233
        return NULL;
234

235
    dom->id = vm->def->id;
236 237 238 239
    return dom;
}

static int openvzDomainGetInfo(virDomainPtr dom,
240
                               virDomainInfoPtr info) {
241
    struct openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
242
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
243

244
    if (!vm) {
D
Daniel Veillard 已提交
245
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
246
                    "%s", _("no domain with matching uuid"));
247 248 249
        return -1;
    }

250
    info->state = vm->state;
251

252
    if (!virDomainIsActive(vm)) {
D
Daniel Veillard 已提交
253 254 255 256
        info->cpuTime = 0;
    } else {
        if (openvzGetProcessInfo(&(info->cpuTime), dom->id) < 0) {
            openvzError(dom->conn, VIR_ERR_OPERATION_FAILED,
257
                        _("cannot read cputime for domain %d"), dom->id);
D
Daniel Veillard 已提交
258 259 260 261
            return -1;
        }
    }

262 263 264
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
265 266 267 268
    return 0;
}


269 270
static char *openvzDomainDumpXML(virDomainPtr dom, int flags) {
    struct openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
271
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
272

273
    if (!vm) {
D
Daniel Veillard 已提交
274
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
275
                    "%s", _("no domain with matching uuid"));
276
        return NULL;
277
    }
278

279 280
    return virDomainDefFormat(dom->conn, vm->def, flags);
}
281

282 283 284 285


static int openvzDomainShutdown(virDomainPtr dom) {
    struct openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
286
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
287
    const char *prog[] = {VZCTL, "--quiet", "stop", vm ? vm->def->name : NULL, NULL};
288 289 290

    if (!vm) {
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
291
                    "%s", _("no domain with matching uuid"));
292 293
        return -1;
    }
294

295
    if (vm->state != VIR_DOMAIN_RUNNING) {
D
Daniel Veillard 已提交
296
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
297
                    "%s", _("domain is not in running state"));
298 299
        return -1;
    }
300

301 302
    if (virRun(dom->conn, prog, NULL) < 0)
        return -1;
303

304 305
    vm->def->id = -1;
    vm->state = VIR_DOMAIN_SHUTOFF;
306

307
    return 0;
308 309
}

310 311
static int openvzDomainReboot(virDomainPtr dom,
                              unsigned int flags ATTRIBUTE_UNUSED) {
312
    struct openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
313
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
314
    const char *prog[] = {VZCTL, "--quiet", "restart", vm ? vm->def->name : NULL, NULL};
315 316

    if (!vm) {
D
Daniel Veillard 已提交
317
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
318
                    "%s", _("no domain with matching uuid"));
319 320
        return -1;
    }
321

322 323
    if (vm->state != VIR_DOMAIN_RUNNING) {
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
324
                    "%s", _("domain is not in running state"));
325 326
        return -1;
    }
327

328
    if (virRun(dom->conn, prog, NULL) < 0)
329
        return -1;
330

331
    return 0;
332 333
}

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
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 已提交
374 375
static int
openvzDomainSetNetwork(virConnectPtr conn, const char *vpsid,
376 377
                       virDomainNetDefPtr net,
                       virBufferPtr configBuf)
D
Daniel Veillard 已提交
378 379
{
    int rc = 0, narg;
380
    const char *prog[OPENVZ_MAX_ARG];
381 382 383
    char macaddr[VIR_MAC_STRING_BUFLEN];
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
    char *opt = NULL;
D
Daniel Veillard 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397

#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 已提交
398
                    "%s", _("Container ID is not specified"));
D
Daniel Veillard 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        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);
    }

415 416 417 418 419 420
    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 已提交
421 422 423

        //--netif_add ifname[,mac,host_ifname,host_mac]
        ADD_ARG_LIT("--netif_add") ;
424 425 426 427 428

        /* 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 已提交
429
                       "%s", _("Could not generate eth name for container"));
430 431 432 433 434 435 436 437 438 439
           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 已提交
440
                           "%s", _("Could not generate veth name"));
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
               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 已提交
460
        }
461 462 463 464 465 466

        VIR_FREE(dev_name_ve);

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

D
Daniel Veillard 已提交
467
        ADD_ARG_LIT(opt) ;
468 469
        VIR_FREE(opt);
    } else if (net->type == VIR_DOMAIN_NET_TYPE_ETHERNET &&
D
Daniel Veillard 已提交
470 471 472 473 474 475 476 477 478 479
              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");
480
        if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
481 482 483 484 485 486 487 488 489 490 491 492
           openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not exec %s"), VZCTL);
           rc = -1;
           goto exit;
        }
    }

 exit:
    cmdExecFree(prog);
    return rc;

 no_memory:
493
    VIR_FREE(opt);
D
Daniel Veillard 已提交
494 495 496 497 498 499 500 501
    openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                _("Could not put argument to %s"), VZCTL);
    cmdExecFree(prog);
    return -1;

#undef ADD_ARG_LIT
}

502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

static int
openvzDomainSetNetworkConfig(virConnectPtr conn,
                             virDomainDefPtr def)
{
    unsigned int i;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *param;
    int first = 1;
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;

    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;
}


551 552 553 554
static virDomainPtr
openvzDomainDefineXML(virConnectPtr conn, const char *xml)
{
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
555 556
    virDomainDefPtr vmdef = NULL;
    virDomainObjPtr vm = NULL;
557
    virDomainPtr dom = NULL;
558
    const char *prog[OPENVZ_MAX_ARG];
559
    prog[0] = NULL;
560

561
    if ((vmdef = virDomainDefParseString(conn, driver->caps, xml)) == NULL)
562
        return NULL;
563

564 565 566 567 568 569
    if (vmdef->os.init == NULL &&
        !(vmdef->os.init = strdup("/sbin/init"))) {
        virDomainDefFree(vmdef);
        return NULL;
    }

570
    vm = virDomainFindByName(&driver->domains, vmdef->name);
571
    if (vm) {
572 573
        openvzError(conn, VIR_ERR_OPERATION_FAILED,
                  _("Already an OPENVZ VM active with the id '%s'"),
574
                  vmdef->name);
575
        virDomainDefFree(vmdef);
576
        return NULL;
577
    }
578 579 580
    if (!(vm = virDomainAssignDef(conn, &driver->domains, vmdef))) {
        virDomainDefFree(vmdef);
        return NULL;
581 582
    }

583 584
    if (openvzDomainDefineCmd(conn, prog, OPENVZ_MAX_ARG, vmdef) < 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
585
                "%s", _("Error creating command for container"));
586
        goto exit;
587 588
    }

D
Daniel Veillard 已提交
589 590
    //TODO: set quota

591
    if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
592
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
593
               _("Could not exec %s"), VZCTL);
594
        goto exit;
595
    }
596

597 598
    if (openvzSetDefinedUUID(strtoI(vmdef->name), vmdef->uuid) < 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
599
               "%s", _("Could not set UUID"));
600 601 602
        goto exit;
    }

603 604 605
    if (openvzDomainSetNetworkConfig(conn, vmdef) < 0)
        goto exit;

606
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
607
    if (dom)
608
        dom->id = -1;
D
Daniel Veillard 已提交
609

610 611 612
    if (vmdef->vcpus > 0) {
        if (openvzDomainSetVcpus(dom, vmdef->vcpus) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
613
                     "%s", _("Could not set number of virtual cpu"));
614 615 616 617
             goto exit;
        }
    }

D
Daniel Veillard 已提交
618
    exit:
619
    cmdExecFree(prog);
620 621 622 623
    return dom;
}

static virDomainPtr
624
openvzDomainCreateXML(virConnectPtr conn, const char *xml,
625 626
                        unsigned int flags ATTRIBUTE_UNUSED)
{
627 628
    virDomainDefPtr vmdef = NULL;
    virDomainObjPtr vm = NULL;
629
    virDomainPtr dom = NULL;
630
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
631
    const char *progstart[] = {VZCTL, "--quiet", "start", NULL, NULL};
632
    const char *progcreate[OPENVZ_MAX_ARG];
633
    progcreate[0] = NULL;
634

635 636 637 638 639 640
    if ((vmdef = virDomainDefParseString(conn, driver->caps, xml)) == NULL)
        return NULL;

    if (vmdef->os.init == NULL &&
        !(vmdef->os.init = strdup("/sbin/init"))) {
        virDomainDefFree(vmdef);
641
        return NULL;
642
    }
643

644
    vm = virDomainFindByName(&driver->domains, vmdef->name);
645
    if (vm) {
646 647 648
        openvzError(conn, VIR_ERR_OPERATION_FAILED,
                  _("Already an OPENVZ VM defined with the id '%s'"),
                  vmdef->name);
649
        virDomainDefFree(vmdef);
650 651
        return NULL;
    }
652 653
    if (!(vm = virDomainAssignDef(conn, &driver->domains, vmdef))) {
        virDomainDefFree(vmdef);
654 655 656
        return NULL;
    }

657 658
    if (openvzDomainDefineCmd(conn, progcreate, OPENVZ_MAX_ARG, vmdef) < 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
659
                "%s", _("Error creating command for container"));
660
        goto exit;
661 662
    }

663
    if (virRun(conn, progcreate, NULL) < 0) {
D
Daniel Veillard 已提交
664
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
665
               _("Could not exec %s"), VZCTL);
666
        goto exit;
667
    }
668

669 670
    if (openvzSetDefinedUUID(strtoI(vmdef->name), vmdef->uuid) < 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
671
               "%s", _("Could not set UUID"));
672 673 674
        goto exit;
    }

675 676
    if (openvzDomainSetNetworkConfig(conn, vmdef) < 0)
        goto exit;
D
Daniel Veillard 已提交
677

678
    progstart[3] = vmdef->name;
679

680
    if (virRun(conn, progstart, NULL) < 0) {
D
Daniel Veillard 已提交
681
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
682
               _("Could not exec %s"), VZCTL);
683
        goto exit;
684
    }
685

686 687 688
    vm->pid = strtoI(vmdef->name);
    vm->def->id = vm->pid;
    vm->state = VIR_DOMAIN_RUNNING;
689

690
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
691
    if (dom)
692
        dom->id = vm->def->id;
693 694 695 696

    if (vmdef->vcpus > 0) {
        if (openvzDomainSetVcpus(dom, vmdef->vcpus) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
697
                        "%s", _("Could not set number of virtual cpu"));
698
            goto exit;
699 700 701
        }
    }

702 703
 exit:
    cmdExecFree(progcreate);
704 705 706 707 708 709
    return dom;
}

static int
openvzDomainCreate(virDomainPtr dom)
{
710
    struct openvz_driver *driver = (struct openvz_driver *)dom->conn->privateData;
711
    virDomainObjPtr vm = virDomainFindByName(&driver->domains, dom->name);
712
    const char *prog[] = {VZCTL, "--quiet", "start", vm ? vm->def->name : NULL, NULL };
713 714

    if (!vm) {
D
Daniel Veillard 已提交
715
        openvzError(dom->conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
716
              "%s", _("no domain with matching id"));
717 718
        return -1;
    }
719

720
    if (vm->state != VIR_DOMAIN_SHUTOFF) {
D
Daniel Veillard 已提交
721
        openvzError(dom->conn, VIR_ERR_OPERATION_DENIED,
J
Jim Meyering 已提交
722
              "%s", _("domain is not in shutoff state"));
723 724 725
        return -1;
    }

726
    if (virRun(dom->conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
727
        openvzError(dom->conn, VIR_ERR_INTERNAL_ERROR,
728
               _("Could not exec %s"), VZCTL);
729 730
        return -1;
    }
731

732 733 734
    vm->pid = strtoI(vm->def->name);
    vm->def->id = vm->pid;
    vm->state = VIR_DOMAIN_RUNNING;
735

736
    return 0;
737 738 739 740 741 742 743
}

static int
openvzDomainUndefine(virDomainPtr dom)
{
    virConnectPtr conn= dom->conn;
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
744
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
745
    const char *prog[] = { VZCTL, "--quiet", "destroy", vm ? vm->def->name : NULL, NULL };
746 747

    if (!vm) {
J
Jim Meyering 已提交
748
        openvzError(conn, VIR_ERR_INVALID_DOMAIN, "%s", _("no domain with matching uuid"));
749 750
        return -1;
    }
751

752
    if (virDomainIsActive(vm)) {
J
Jim Meyering 已提交
753
        openvzError(conn, VIR_ERR_INTERNAL_ERROR, "%s", _("cannot delete active domain"));
754 755
        return -1;
    }
756

757
    if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
758
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
759
               _("Could not exec %s"), VZCTL);
760 761
        return -1;
    }
762

763 764
    virDomainRemoveInactive(&driver->domains, vm);

765
    return 0;
766 767
}

768 769 770 771 772
static int
openvzDomainSetAutostart(virDomainPtr dom, int autostart)
{
    virConnectPtr conn= dom->conn;
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
773
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
774
    const char *prog[] = { VZCTL, "--quiet", "set", vm ? vm->def->name : NULL,
D
Daniel Veillard 已提交
775
                           "--onboot", autostart ? "yes" : "no",
776 777 778
                           "--save", NULL };

    if (!vm) {
J
Jim Meyering 已提交
779
        openvzError(conn, VIR_ERR_INVALID_DOMAIN, "%s", _("no domain with matching uuid"));
780 781 782
        return -1;
    }

783
    if (virRun(conn, prog, NULL) < 0) {
D
Daniel Veillard 已提交
784
        openvzError(conn, VIR_ERR_INTERNAL_ERROR, _("Could not exec %s"), VZCTL);
785 786 787 788 789 790 791 792 793 794 795
        return -1;
    }

    return 0;
}

static int
openvzDomainGetAutostart(virDomainPtr dom, int *autostart)
{
    virConnectPtr conn= dom->conn;
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
796
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
797 798 799
    char value[1024];

    if (!vm) {
J
Jim Meyering 已提交
800
        openvzError(conn, VIR_ERR_INVALID_DOMAIN, "%s", _("no domain with matching uuid"));
801 802 803
        return -1;
    }

804
    if (openvzReadConfigParam(strtoI(vm->def->name), "ONBOOT", value, sizeof(value)) < 0) {
J
Jim Meyering 已提交
805
        openvzError(conn, VIR_ERR_INTERNAL_ERROR, "%s", _("Could not read container config"));
806 807 808 809 810
        return -1;
    }

    *autostart = 0;
    if (STREQ(value,"yes"))
D
Daniel Veillard 已提交
811
        *autostart = 1;
812 813 814 815

    return 0;
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
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) {
    virConnectPtr conn= dom->conn;
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
833
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
834
    char   str_vcpus[32];
835
    const char *prog[] = { VZCTL, "--quiet", "set", vm ? vm->def->name : NULL,
836 837 838 839 840
                           "--cpus", str_vcpus, "--save", NULL };


    if (!vm) {
        openvzError(conn, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
841
                    "%s", _("no domain with matching uuid"));
842 843 844
        return -1;
    }

845 846
    if (nvcpus <= 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
847
                    "%s", _("VCPUs should be >= 1"));
848 849 850 851 852 853
        return -1;
    }

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

854 855
    if (virRun(conn, prog, NULL) < 0) {
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
856
                    _("Could not exec %s"), VZCTL);
857 858 859
        return -1;
    }

860
    vm->def->vcpus = nvcpus;
861 862 863
    return 0;
}

864 865 866
static const char *openvzProbe(void)
{
#ifdef __linux__
867
    if ((geteuid() == 0) && (virFileExists("/proc/vz")))
D
Daniel Veillard 已提交
868
        return("openvz:///system");
869 870 871 872
#endif
    return(NULL);
}

873
static virDrvOpenStatus openvzOpen(virConnectPtr conn,
874 875 876 877
                                 xmlURIPtr uri,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                 int flags ATTRIBUTE_UNUSED)
{
878
    struct openvz_driver *driver;
879
    /*Just check if the user is root. Nothing really to open for OpenVZ */
880 881 882 883 884 885 886 887 888 889
    if (geteuid()) { // OpenVZ tools can only be used by r00t
        return VIR_DRV_OPEN_DECLINED;
    } else {
        if (uri == NULL ||
            uri->scheme == NULL ||
            uri->path == NULL ||
            STRNEQ (uri->scheme, "openvz") ||
            STRNEQ (uri->path, "/system"))
            return VIR_DRV_OPEN_DECLINED;
    }
890
    /* See if we are running an OpenVZ enabled kernel */
891 892 893 894 895 896 897 898 899 900 901 902
    if(access("/proc/vz/veinfo", F_OK) == -1 ||
       access("/proc/user_beancounters", F_OK) == -1) {
        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;
903

904 905
    if (openvzLoadDomains(driver) < 0)
        goto cleanup;
906

907 908 909
    if (openvzExtractVersion(conn, driver) < 0)
        goto cleanup;

910
    conn->privateData = driver;
911

912
    return VIR_DRV_OPEN_SUCCESS;
913

914 915 916
cleanup:
    openvzFreeDriver(driver);
    return VIR_DRV_OPEN_ERROR;
917
};
918 919 920

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

922
    openvzFreeDriver(driver);
923 924 925 926 927 928 929 930 931
    conn->privateData = NULL;

    return 0;
}

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

932 933 934 935 936
static int openvzGetNodeInfo(virConnectPtr conn,
                             virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
}

937 938 939 940 941 942
static char *openvzGetCapabilities(virConnectPtr conn) {
    struct openvz_driver *driver = (struct openvz_driver *)conn->privateData;

    return virCapabilitiesFormatXML(driver->caps);
}

943 944
static int openvzListDomains(virConnectPtr conn, int *ids, int nids) {
    int got = 0;
945 946 947
    int veid, pid;
    int outfd = -1;
    int errfd = -1;
948 949
    int ret;
    char buf[32];
950
    char *endptr;
951
    const char *cmd[] = {VZLIST, "-ovpsid", "-H" , NULL};
952

953 954
    ret = virExec(conn, cmd, NULL, NULL,
                  &pid, -1, &outfd, &errfd, VIR_EXEC_NONE);
955
    if(ret == -1) {
D
Daniel Veillard 已提交
956
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
957
               _("Could not exec %s"), VZLIST);
D
Daniel P. Berrange 已提交
958
        return -1;
959 960
    }

961 962 963
    while(got < nids){
        ret = openvz_readline(outfd, buf, 32);
        if(!ret) break;
964 965 966 967 968
        if (virStrToLong_i(buf, &endptr, 10, &veid) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not parse VPS ID %s"), buf);
            continue;
        }
969 970 971
        ids[got] = veid;
        got ++;
    }
972
    waitpid(pid, NULL, 0);
973 974 975 976

    return got;
}

977
static int openvzNumDomains(virConnectPtr conn) {
978
    struct openvz_driver *driver = conn->privateData;
979 980 981 982
    int nactive = 0, i;

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

985
    return nactive;
986 987 988
}

static int openvzListDefinedDomains(virConnectPtr conn,
989
                                    char **const names, int nnames) {
990
    int got = 0;
991
    int veid, pid, outfd = -1, errfd = -1, ret;
992
    char vpsname[32];
993
    char buf[32];
994
    char *endptr;
995
    const char *cmd[] = {VZLIST, "-ovpsid", "-H", "-S", NULL};
996 997

    /* the -S options lists only stopped domains */
998 999
    ret = virExec(conn, cmd, NULL, NULL,
                  &pid, -1, &outfd, &errfd, VIR_EXEC_NONE);
1000
    if(ret == -1) {
D
Daniel Veillard 已提交
1001
        openvzError(conn, VIR_ERR_INTERNAL_ERROR,
1002
               _("Could not exec %s"), VZLIST);
D
Daniel P. Berrange 已提交
1003
        return -1;
1004 1005
    }

1006 1007 1008
    while(got < nnames){
        ret = openvz_readline(outfd, buf, 32);
        if(!ret) break;
1009 1010 1011 1012 1013
        if (virStrToLong_i(buf, &endptr, 10, &veid) < 0) {
            openvzError(conn, VIR_ERR_INTERNAL_ERROR,
                    _("Could not parse VPS ID %s"), buf);
            continue;
        }
1014 1015 1016
        snprintf(vpsname, sizeof(vpsname), "%d", veid);
        if (!(names[got] = strdup(vpsname)))
            goto no_memory;
1017 1018
        got ++;
    }
1019
    waitpid(pid, NULL, 0);
1020
    return got;
1021 1022 1023 1024 1025 1026

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

D
Daniel Veillard 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 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
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;
}

1074 1075
static int openvzNumDefinedDomains(virConnectPtr conn) {
    struct openvz_driver *driver = (struct openvz_driver *) conn->privateData;
1076 1077 1078 1079
    int ninactive = 0, i;

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

1082
    return ninactive;
1083 1084 1085 1086 1087 1088
}

static virDriver openvzDriver = {
    VIR_DRV_OPENVZ,
    "OPENVZ",
    LIBVIR_VERSION_NUMBER,
1089
    openvzProbe, /* probe */
1090 1091
    openvzOpen, /* open */
    openvzClose, /* close */
1092
    NULL, /* supports_feature */
1093
    openvzGetType, /* type */
1094
    openvzGetVersion, /* version */
1095 1096
    NULL, /* hostname */
    NULL, /* uri */
1097
    openvzGetMaxVCPUs, /* getMaxVcpus */
1098
    openvzGetNodeInfo, /* nodeGetInfo */
1099
    openvzGetCapabilities, /* getCapabilities */
1100 1101
    openvzListDomains, /* listDomains */
    openvzNumDomains, /* numOfDomains */
1102
    openvzDomainCreateXML, /* domainCreateXML */
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    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 */
1119
    openvzDomainSetVcpus, /* domainSetVcpus */
1120 1121
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
1122
    openvzDomainGetMaxVcpus, /* domainGetMaxVcpus */
1123
    openvzDomainDumpXML, /* domainDumpXML */
1124 1125 1126
    openvzListDefinedDomains, /* listDomains */
    openvzNumDefinedDomains, /* numOfDomains */
    openvzDomainCreate, /* domainCreate */
1127 1128
    openvzDomainDefineXML, /* domainDefineXML */
    openvzDomainUndefine, /* domainUndefine */
1129 1130
    NULL, /* domainAttachDevice */
    NULL, /* domainDetachDevice */
1131 1132
    openvzDomainGetAutostart, /* domainGetAutostart */
    openvzDomainSetAutostart, /* domainSetAutostart */
1133 1134 1135
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
1136 1137 1138 1139 1140
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
D
Daniel P. Berrange 已提交
1141 1142
    NULL, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
1143
    NULL, /* nodeGetCellsFreeMemory */
1144
    NULL, /* nodeGetFreeMemory */
1145 1146
    NULL, /* domainEventRegister */
    NULL, /* domainEventDeregister */
D
Daniel Veillard 已提交
1147 1148
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
1149 1150 1151 1152 1153 1154 1155
};

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