openvz_conf.c 29.3 KB
Newer Older
1 2 3
/*
 * openvz_conf.c: config functions for managing OpenVZ VEs
 *
4
 * Copyright (C) 2010-2012, 2014 Red Hat, Inc.
5 6
 * Copyright (C) 2006, 2007 Binary Karma
 * Copyright (C) 2006 Shuveb Hussain
7
 * Copyright (C) 2007 Anoop Joe Cyriac
8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22
 *
23
 * Authors:
24 25 26
 * Shuveb Hussain <shuveb@binarykarma.com>
 * Anoop Joe Cyriac <anoop@binarykarma.com>
 *
27 28
 */

29
#include <config.h>
J
Jim Meyering 已提交
30

31 32 33 34 35 36 37
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <time.h>
38 39 40
#include <sys/stat.h>
#include <limits.h>
#include <errno.h>
D
Daniel P. Berrange 已提交
41
#include <string.h>
42
#include <sys/wait.h>
43

44
#include "virerror.h"
45
#include "openvz_conf.h"
46
#include "openvz_util.h"
47
#include "viruuid.h"
48
#include "virbuffer.h"
49
#include "viralloc.h"
50
#include "nodeinfo.h"
E
Eric Blake 已提交
51
#include "virfile.h"
52
#include "vircommand.h"
53
#include "virstring.h"
54

55 56
#define VIR_FROM_THIS VIR_FROM_OPENVZ

57
static char *openvzLocateConfDir(void);
58
static int openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len);
59
static int openvzAssignUUIDs(void);
60 61 62
static int openvzLocateConfFileDefault(int vpsid, char **conffile, const char *ext);

openvzLocateConfFileFunc openvzLocateConfFile = openvzLocateConfFileDefault;
63

64
int
65
strtoI(const char *str)
66 67 68
{
    int val;

69
    if (virStrToLong_i(str, NULL, 10, &val) < 0)
E
Eric Blake 已提交
70
        return 0;
71

72 73 74
    return val;
}

75 76

static int
77
openvzExtractVersionInfo(const char *cmdstr, int *retversion)
78
{
79
    int ret = -1;
80
    unsigned long version;
81
    char *help = NULL;
82
    char *tmp;
83
    virCommandPtr cmd = virCommandNewArgList(cmdstr, "--help", NULL);
84 85 86 87

    if (retversion)
        *retversion = 0;

88 89
    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &help);
90

91 92
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
93

94 95 96 97
    tmp = help;

    /* expected format: vzctl version <major>.<minor>.<micro> */
    if ((tmp = STRSKIP(tmp, "vzctl version ")) == NULL)
98
        goto cleanup;
99

I
Ilja Livenson 已提交
100
    if (virParseVersionString(tmp, &version, true) < 0)
101
        goto cleanup;
102 103 104 105 106 107

    if (retversion)
        *retversion = version;

    ret = 0;

108 109
cleanup:
    virCommandFree(cmd);
110 111 112 113 114
    VIR_FREE(help);

    return ret;
}

115
int openvzExtractVersion(struct openvz_driver *driver)
116 117 118 119 120
{
    if (driver->version > 0)
        return 0;

    if (openvzExtractVersionInfo(VZCTL, &driver->version) < 0) {
121 122
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not extract vzctl version"));
123 124 125 126 127 128 129
        return -1;
    }

    return 0;
}


130 131 132 133 134 135 136 137
/* Parse config values of the form barrier:limit into barrier and limit */
static int
openvzParseBarrierLimit(const char* value,
                        unsigned long long *barrier,
                        unsigned long long *limit)
{
    char *token;
    char *saveptr = NULL;
138
    char *str;
P
Pavel Hrdina 已提交
139
    int ret = -1;
140

141
    if (VIR_STRDUP(str, value) < 0)
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        goto error;

    token = strtok_r(str, ":", &saveptr);
    if (token == NULL) {
        goto error;
    } else {
        if (barrier != NULL) {
            if (virStrToLong_ull(token, NULL, 10, barrier))
                goto error;
        }
    }
    token = strtok_r(NULL, ":", &saveptr);
    if (token == NULL) {
        goto error;
    } else {
        if (limit != NULL) {
            if (virStrToLong_ull(token, NULL, 10, limit))
                goto error;
        }
    }
P
Pavel Hrdina 已提交
162
    ret = 0;
163 164
error:
    VIR_FREE(str);
P
Pavel Hrdina 已提交
165
    return ret;
166 167 168
}


169 170 171 172 173
virCapsPtr openvzCapsInit(void)
{
    virCapsPtr caps;
    virCapsGuestPtr guest;

174
    if ((caps = virCapabilitiesNew(virArchFromHost(),
175 176 177
                                   0, 0)) == NULL)
        goto no_memory;

178
    if (nodeCapsInitNUMA(caps) < 0)
179 180
        goto no_memory;

181 182
    if ((guest = virCapabilitiesAddGuest(caps,
                                         "exe",
183
                                         caps->host.arch,
184 185 186 187 188 189 190 191 192 193 194 195 196 197
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      "openvz",
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;

198
    return caps;
199

200
no_memory:
201
    virObjectUnref(caps);
202 203 204 205
    return NULL;
}


206
int
207
openvzReadNetworkConf(virDomainDefPtr def,
208
                      int veid) {
209
    int ret;
210
    virDomainNetDefPtr net = NULL;
211
    char *temp = NULL;
212 213 214 215 216 217 218
    char *token, *saveptr = NULL;

    /*parse routing network configuration*
     * Sample from config:
     *   IP_ADDRESS="1.1.1.1 1.1.1.2"
     *   splited IPs by space
     */
219
    ret = openvzReadVPSConfigParam(veid, "IP_ADDRESS", &temp);
220
    if (ret < 0) {
221 222 223
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'IP_ADDRESS' from config for container %d"),
                       veid);
224 225 226 227
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, " ", &saveptr);
        while (token != NULL) {
228
            if (VIR_ALLOC(net) < 0)
229
                goto error;
230 231

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
232 233
            if (VIR_STRDUP(net->data.ethernet.ipaddr, token) < 0)
                goto error;
234

235
            if (VIR_APPEND_ELEMENT_COPY(def->nets, def->nnets, net) < 0)
236
                goto error;
237

238 239 240 241 242 243 244 245 246
            token = strtok_r(NULL, " ", &saveptr);
        }
    }

    /*parse bridge devices*/
    /*Sample from config:
     *NETIF="ifname=eth10,mac=00:18:51:C1:05:EE,host_ifname=veth105.10,host_mac=00:18:51:8F:D9:F3"
     *devices splited by ';'
     */
247
    ret = openvzReadVPSConfigParam(veid, "NETIF", &temp);
248
    if (ret < 0) {
249 250 251
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'NETIF' from config for container %d"),
                       veid);
252 253 254 255 256
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, ";", &saveptr);
        while (token != NULL) {
            /*add new device to list*/
257
            if (VIR_ALLOC(net) < 0)
258
                goto error;
259 260 261

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

262
            char *p = token;
263 264 265 266 267
            char cpy_temp[32];
            int len;

            /*parse string*/
            do {
268
                char *next = strchrnul(p, ',');
269
                if (STRPREFIX(p, "ifname=")) {
270 271 272
                    /* skip in libvirt */
                } else if (STRPREFIX(p, "host_ifname=")) {
                    p += 12;
273 274
                    len = next - p;
                    if (len > 16) {
275 276
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Too long network device name"));
277 278 279
                        goto error;
                    }

280
                    if (VIR_ALLOC_N(net->ifname, len+1) < 0)
281
                        goto error;
282

C
Chris Lalancette 已提交
283
                    if (virStrncpy(net->ifname, p, len, len+1) == NULL) {
284 285
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Network ifname %s too long for destination"), p);
C
Chris Lalancette 已提交
286 287
                        goto error;
                    }
288 289 290 291
                } else if (STRPREFIX(p, "bridge=")) {
                    p += 7;
                    len = next - p;
                    if (len > 16) {
292 293
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Too long bridge device name"));
294 295 296
                        goto error;
                    }

297
                    if (VIR_ALLOC_N(net->data.bridge.brname, len+1) < 0)
298
                        goto error;
299

C
Chris Lalancette 已提交
300
                    if (virStrncpy(net->data.bridge.brname, p, len, len+1) == NULL) {
301 302
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Bridge name %s too long for destination"), p);
C
Chris Lalancette 已提交
303 304
                        goto error;
                    }
305 306 307
                } else if (STRPREFIX(p, "mac=")) {
                    p += 4;
                    len = next - p;
308
                    if (len != 17) { /* should be 17 */
309 310
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Wrong length MAC address"));
311 312
                        goto error;
                    }
C
Chris Lalancette 已提交
313
                    if (virStrncpy(cpy_temp, p, len, sizeof(cpy_temp)) == NULL) {
314 315
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("MAC address %s too long for destination"), p);
C
Chris Lalancette 已提交
316 317
                        goto error;
                    }
318
                    if (virMacAddrParse(cpy_temp, &net->mac) < 0) {
319 320
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("Wrong MAC address"));
321 322 323 324 325 326
                        goto error;
                    }
                }
                p = ++next;
            } while (p < token + strlen(token));

327
            if (VIR_APPEND_ELEMENT_COPY(def->nets, def->nnets, net) < 0)
328
                goto error;
329

330 331 332 333
            token = strtok_r(NULL, ";", &saveptr);
        }
    }

334 335
    VIR_FREE(temp);

336
    return 0;
337

338
error:
339
    VIR_FREE(temp);
340
    virDomainNetDefFree(net);
341
    return -1;
342 343 344
}


345 346 347 348 349 350 351
/* utility function to replace 'from' by 'to' in 'str' */
static char*
openvz_replace(const char* str,
               const char* from,
               const char* to) {
    const char* offset = NULL;
    const char* str_start = str;
352 353
    int to_len;
    int from_len;
354 355
    virBuffer buf = VIR_BUFFER_INITIALIZER;

356
    if ((!from) || (!to))
357
        return NULL;
358 359
    from_len = strlen(from);
    to_len = strlen(to);
360

E
Eric Blake 已提交
361
    while ((offset = strstr(str_start, from)))
362 363 364 365 366 367
    {
        virBufferAdd(&buf, str_start, offset-str_start);
        virBufferAdd(&buf, to, to_len);
        str_start = offset + from_len;
    }

368
    virBufferAdd(&buf, str_start, -1);
369

370 371 372 373
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        return NULL;
    }
374 375 376 377 378

    return virBufferContentAndReset(&buf);
}


379
static int
380
openvzReadFSConf(virDomainDefPtr def,
381 382 383
                 int veid) {
    int ret;
    virDomainFSDefPtr fs = NULL;
384 385
    char *veid_str = NULL;
    char *temp = NULL;
386 387
    const char *param;
    unsigned long long barrier, limit;
388

389
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
390
    if (ret < 0) {
391 392 393
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'OSTEMPLATE' from config for container %d"),
                       veid);
394 395 396
        goto error;
    } else if (ret > 0) {
        if (VIR_ALLOC(fs) < 0)
397
            goto error;
398 399

        fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE;
400 401
        if (VIR_STRDUP(fs->src, temp) < 0)
            goto error;
402 403
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
404
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
405
        if (ret <= 0) {
406 407 408
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read 'VE_PRIVATE' from config for container %d"),
                           veid);
409 410
            goto error;
        }
411

412
        if (VIR_ALLOC(fs) < 0)
413
            goto error;
414

415
        if (virAsprintf(&veid_str, "%d", veid) < 0)
416
            goto error;
417 418

        fs->type = VIR_DOMAIN_FS_TYPE_MOUNT;
419 420
        if (!(fs->src = openvz_replace(temp, "$VEID", veid_str)))
            goto no_memory;
421

422
        VIR_FREE(veid_str);
423 424
    }

425 426
    if (VIR_STRDUP(fs->dst, "/") < 0)
        goto error;
427

428 429 430 431
    param = "DISKSPACE";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret > 0) {
        if (openvzParseBarrierLimit(temp, &barrier, &limit)) {
432 433 434
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read '%s' from config for container %d"),
                           param, veid);
435 436 437
            goto error;
        } else {
            /* Ensure that we can multiply by 1024 without overflowing. */
438
            if (barrier > ULLONG_MAX / 1024 ||
439
                limit > ULLONG_MAX / 1024) {
440 441
                virReportSystemError(VIR_ERR_OVERFLOW, "%s",
                                     _("Unable to parse quota"));
442 443 444 445 446 447 448
                goto error;
            }
            fs->space_soft_limit = barrier * 1024; /* unit is bytes */
            fs->space_hard_limit = limit * 1024;   /* unit is bytes */
        }
    }

449
    if (VIR_APPEND_ELEMENT(def->fss, def->nfss, fs) < 0)
450
        goto error;
451

452 453
    VIR_FREE(temp);

454 455
    return 0;
no_memory:
456
    virReportOOMError();
457
error:
458
    VIR_FREE(temp);
459 460 461 462 463
    virDomainFSDefFree(fs);
    return -1;
}


464 465 466
static int
openvzReadMemConf(virDomainDefPtr def, int veid)
{
467
    int ret = -1;
468 469 470
    char *temp = NULL;
    unsigned long long barrier, limit;
    const char *param;
471
    long kb_per_pages;
472

473 474
    kb_per_pages = openvzKBPerPages();
    if (kb_per_pages < 0)
475 476 477 478 479 480
        goto error;

    /* Memory allocation guarantee */
    param = "VMGUARPAGES";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret < 0) {
481 482 483
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
484 485 486 487
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, NULL);
        if (ret < 0) {
488 489 490
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier of '%s' "
                             "from config for container %d"), param, veid);
491 492 493 494 495 496 497 498 499 500 501 502
            goto error;
        }
        if (barrier == LONG_MAX)
            def->mem.min_guarantee = 0ull;
        else
            def->mem.min_guarantee = barrier * kb_per_pages;
    }

    /* Memory hard and soft limits */
    param = "PRIVVMPAGES";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret < 0) {
503 504 505
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
506 507 508 509
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, &limit);
        if (ret < 0) {
510 511 512
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier and limit of '%s' "
                             "from config for container %d"), param, veid);
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
            goto error;
        }
        if (barrier == LONG_MAX)
            def->mem.soft_limit = 0ull;
        else
            def->mem.soft_limit = barrier * kb_per_pages;

        if (limit == LONG_MAX)
            def->mem.hard_limit = 0ull;
        else
            def->mem.hard_limit = limit * kb_per_pages;
    }

    ret = 0;
error:
    VIR_FREE(temp);
    return ret;
}


533 534 535 536 537 538
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
    if (!driver)
        return;
539

540
    virObjectUnref(driver->xmlopt);
541
    virObjectUnref(driver->domains);
542
    virObjectUnref(driver->caps);
543
    VIR_FREE(driver);
544
}
D
Daniel Veillard 已提交
545 546 547



548
int openvzLoadDomains(struct openvz_driver *driver) {
549
    int veid, ret;
550
    char *status;
551
    char uuidstr[VIR_UUID_STRING_BUFLEN];
552
    virDomainObjPtr dom = NULL;
553
    virDomainDefPtr def = NULL;
554
    char *temp = NULL;
E
Eric Blake 已提交
555 556 557
    char *outbuf = NULL;
    char *line;
    virCommandPtr cmd = NULL;
558

559 560
    if (openvzAssignUUIDs() < 0)
        return -1;
561

E
Eric Blake 已提交
562 563 564 565
    cmd = virCommandNewArgList(VZLIST, "-a", "-ovpsid,status", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
566

567 568
    line = outbuf;
    while (line[0] != '\0') {
569
        unsigned int flags = 0;
570 571 572
        if (virStrToLong_i(line, &status, 10, &veid) < 0 ||
            *status++ != ' ' ||
            (line = strchr(status, '\n')) == NULL) {
573 574
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Failed to parse vzlist output"));
575
            goto cleanup;
576
        }
577
        *line++ = '\0';
578

579
        if (VIR_ALLOC(def) < 0)
580
            goto cleanup;
581

582
        def->virtType = VIR_DOMAIN_VIRT_OPENVZ;
583

584 585
        if (STREQ(status, "stopped"))
            def->id = -1;
J
Jiri Denemark 已提交
586
        else
587 588
            def->id = veid;
        if (virAsprintf(&def->name, "%i", veid) < 0)
589
            goto cleanup;
590

591
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
592
        ret = virUUIDParse(uuidstr, def->uuid);
593

594
        if (ret == -1) {
595 596
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("UUID in config file malformed"));
597
            goto cleanup;
598
        }
599

600 601 602 603
        if (VIR_STRDUP(def->os.type, "exe") < 0)
            goto cleanup;
        if (VIR_STRDUP(def->os.init, "/sbin/init") < 0)
            goto cleanup;
604

605
        ret = openvzReadVPSConfigParam(veid, "CPUS", &temp);
606
        if (ret < 0) {
607 608 609
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read config for container %d"),
                           veid);
610
            goto cleanup;
611
        } else if (ret > 0) {
612
            def->maxvcpus = strtoI(temp);
613 614
        }

615 616 617
        if (ret == 0 || def->maxvcpus == 0)
            def->maxvcpus = openvzGetNodeCPUs();
        def->vcpus = def->maxvcpus;
618

619
        /* XXX load rest of VM config data .... */
620

621 622 623
        openvzReadNetworkConf(def, veid);
        openvzReadFSConf(def, veid);
        openvzReadMemConf(def, veid);
624

625
        virUUIDFormat(def->uuid, uuidstr);
626 627 628 629
        flags = VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE;
        if (STRNEQ(status, "stopped"))
            flags |= VIR_DOMAIN_OBJ_LIST_ADD_LIVE;

630 631
        if (!(dom = virDomainObjListAdd(driver->domains,
                                        def,
632
                                        driver->xmlopt,
633 634
                                        flags,
                                        NULL)))
635
            goto cleanup;
636 637 638 639 640 641 642 643 644

        if (STREQ(status, "stopped")) {
            virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
            dom->pid = -1;
        } else {
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNKNOWN);
            dom->pid = veid;
645
        }
646 647
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
648

649
        virObjectUnlock(dom);
650
        dom = NULL;
651
        def = NULL;
652
    }
653

E
Eric Blake 已提交
654
    virCommandFree(cmd);
655
    VIR_FREE(temp);
E
Eric Blake 已提交
656
    VIR_FREE(outbuf);
657

658
    return 0;
659

660
 cleanup:
E
Eric Blake 已提交
661
    virCommandFree(cmd);
662
    VIR_FREE(temp);
E
Eric Blake 已提交
663
    VIR_FREE(outbuf);
664
    virObjectUnref(dom);
665
    virDomainDefFree(def);
666
    return -1;
667 668
}

669 670 671 672 673
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

674
    if (nodeGetInfo(&nodeinfo) < 0)
675 676 677 678
        return 0;

    return nodeinfo.cpus;
}
679

680 681
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
682
{
683
    char * temp_file = NULL;
684 685 686 687
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
688

689
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0)
690 691
        return -1;

692 693
    fp = fopen(conf_file, "r");
    if (fp == NULL)
694
        goto error;
695 696
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (temp_fd == -1) {
697
        goto error;
698 699
    }

E
Eric Blake 已提交
700
    while (1) {
701
        if (getline(&line, &line_size, fp) <= 0)
702 703
            break;

704
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
705 706 707 708 709 710 711 712 713 714 715 716
            if (safewrite(temp_fd, line, strlen(line)) !=
                strlen(line))
                goto error;
        }
    }

    if (safewrite(temp_fd, param, strlen(param)) < 0 ||
        safewrite(temp_fd, "=\"", 2) < 0 ||
        safewrite(temp_fd, value, strlen(value)) < 0 ||
        safewrite(temp_fd, "\"\n", 2) < 0)
        goto error;

717
    if (VIR_FCLOSE(fp) < 0)
718
        goto error;
719
    if (VIR_CLOSE(temp_fd) < 0)
720 721 722 723 724
        goto error;

    if (rename(temp_file, conf_file) < 0)
        goto error;

725 726
    VIR_FREE(line);

727 728 729
    return 0;

error:
730 731
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
732
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
733
    if (temp_file)
734 735
        unlink(temp_file);
    VIR_FREE(temp_file);
736 737 738
    return -1;
}

739
int
740 741
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
742 743
    char *conf_file;
    int ret;
744

745
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
746 747
        return -1;

748 749 750
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
751 752
}

753 754 755
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
756 757
 *
 * Returns <0 on error, 0 if not found, 1 if found.
758
 */
759
int
760
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
761
{
762 763 764
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
765 766
    int err = 0;
    char *sf, *token, *saveptr = NULL;
767

768 769
    fp = fopen(conf_file, "r");
    if (fp == NULL)
770 771
        return -1;

772
    VIR_FREE(*value);
773 774 775 776 777 778
    while (1) {
        if (getline(&line, &line_size, fp) < 0) {
            err = !feof(fp);
            break;
        }

779 780 781 782 783 784
        if (! STREQLEN(line, param, strlen(param)))
            continue;

        sf = line + strlen(param);
        if (*sf++ != '=') continue;

785
        saveptr = NULL;
786 787
        if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) {
            VIR_FREE(*value);
788
            if (VIR_STRDUP(*value, token) < 0) {
789 790
                err = 1;
                break;
791
            }
792 793
            /* keep going - last entry wins */
        }
794
    }
795 796
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
797

798
    return err ? -1 : *value ? 1 : 0;
799 800
}

801
/*
802 803 804 805 806 807 808 809 810 811
 * Read parameter from container config
 *
 * value will be freed before a new value is assined to it, the caller is
 * responsible for freeing it afterwards.
 *
 * sample: 133, "OSTEMPLATE", &value
 * return: -1 - error
 *          0 - don't found
 *          1 - OK
 */
812
int
813
openvzReadVPSConfigParam(int vpsid, const char *param, char **value)
814
{
815 816
    char *conf_file;
    int ret;
817

818
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
819 820
        return -1;

821
    ret = openvzReadConfigParam(conf_file, param, value);
822 823
    VIR_FREE(conf_file);
    return ret;
824 825 826 827 828
}

static int
openvz_copyfile(char* from_path, char* to_path)
{
829 830 831 832
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
    int copy_fd;
833 834
    int bytes_read;

835 836
    fp = fopen(from_path, "r");
    if (fp == NULL)
837 838 839
        return -1;
    copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (copy_fd == -1) {
840
        VIR_FORCE_FCLOSE(fp);
841 842 843
        return -1;
    }

E
Eric Blake 已提交
844
    while (1) {
845
        if (getline(&line, &line_size, fp) <= 0)
846 847 848 849 850 851 852
            break;

        bytes_read = strlen(line);
        if (safewrite(copy_fd, line, bytes_read) != bytes_read)
            goto error;
    }

853
    if (VIR_FCLOSE(fp) < 0)
854
        goto error;
855
    if (VIR_CLOSE(copy_fd) < 0)
856 857
        goto error;

858 859
    VIR_FREE(line);

860 861 862
    return 0;

error:
863 864
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
865
    VIR_FORCE_CLOSE(copy_fd);
866 867 868 869 870 871 872 873 874 875 876
    return -1;
}

/*
* Copy the default config to the VE conf file
* return: -1 - error
*          0 - OK
*/
int
openvzCopyDefaultConfig(int vpsid)
{
877 878 879
    char *confdir = NULL;
    char *default_conf_file = NULL;
    char *configfile_value = NULL;
880
    char *conf_file = NULL;
881 882
    int ret = -1;

883
    if (openvzReadConfigParam(VZ_CONF_FILE, "CONFIGFILE", &configfile_value) < 0)
884 885 886 887 888 889
        goto cleanup;

    confdir = openvzLocateConfDir();
    if (confdir == NULL)
        goto cleanup;

890
    if (virAsprintf(&default_conf_file, "%s/ve-%s.conf-sample", confdir,
891
                    configfile_value) < 0)
892 893
        goto cleanup;

894
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
895 896 897 898 899 900 901 902 903
        goto cleanup;

    if (openvz_copyfile(default_conf_file, conf_file)<0)
        goto cleanup;

    ret = 0;
cleanup:
    VIR_FREE(confdir);
    VIR_FREE(default_conf_file);
904
    VIR_FREE(configfile_value);
905
    VIR_FREE(conf_file);
906 907 908
    return ret;
}

909
/* Locate config file of container
910 911
 * return -1 - error
 *         0 - OK */
912
static int
913
openvzLocateConfFileDefault(int vpsid, char **conffile, const char *ext)
914
{
915
    char *confdir;
916 917 918 919 920 921
    int ret = 0;

    confdir = openvzLocateConfDir();
    if (confdir == NULL)
        return -1;

922
    if (virAsprintf(conffile, "%s/%d.%s", confdir, vpsid,
923
                    ext ? ext : "conf") < 0)
924 925 926 927 928 929
        ret = -1;

    VIR_FREE(confdir);
    return ret;
}

930 931
static char *
openvzLocateConfDir(void)
932 933
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
934
    size_t i = 0;
935
    char *ret = NULL;
936

E
Eric Blake 已提交
937
    while (conf_dir_list[i]) {
938
        if (virFileExists(conf_dir_list[i])) {
939 940 941
            ignore_value(VIR_STRDUP(ret, conf_dir_list[i]));
            goto cleanup;
        }
E
Eric Blake 已提交
942
        i++;
943 944
    }

945 946
cleanup:
    return ret;
947 948 949
}

/* Richard Steven's classic readline() function */
950
int
951
openvz_readline(int fd, char *ptr, int maxlen)
952 953 954 955
{
    int n, rc;
    char c;

E
Eric Blake 已提交
956
    for (n = 1; n < maxlen; n++) {
957
        if ((rc = read(fd, &c, 1)) == 1) {
958
            *ptr++ = c;
E
Eric Blake 已提交
959
            if (c == '\n')
960
                break;
E
Eric Blake 已提交
961 962
        } else if (rc == 0) {
            if (n == 1)
963 964 965 966 967 968 969 970 971 972 973
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

974
static int
975
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
976
{
977
    char *conf_file;
978 979
    char *line = NULL;
    size_t line_size = 0;
980
    char *saveptr = NULL;
981 982
    char *uuidbuf;
    char *iden;
983
    FILE *fp;
984
    int retval = -1;
985

986
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
987
        return -1;
988

989 990
    fp = fopen(conf_file, "r");
    if (fp == NULL)
991
        goto cleanup;
992

E
Eric Blake 已提交
993
    while (1) {
994 995 996 997 998 999 1000
        if (getline(&line, &line_size, fp) < 0) {
            if (feof(fp)) { /* EOF, UUID was not found */
                uuidstr[0] = 0;
                break;
            } else {
                goto cleanup;
            }
1001 1002
        }

1003 1004 1005 1006
        iden = strtok_r(line, " ", &saveptr);
        uuidbuf = strtok_r(NULL, "\n", &saveptr);

        if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) {
1007
            if (virStrcpy(uuidstr, uuidbuf, len) == NULL) {
1008 1009
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("invalid uuid %s"), uuidbuf);
1010 1011
                goto cleanup;
            }
1012 1013 1014
            break;
        }
    }
1015 1016
    retval = 0;
cleanup:
1017 1018
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
1019
    VIR_FREE(conf_file);
1020

C
Chris Lalancette 已提交
1021
    return retval;
1022 1023 1024 1025 1026
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
1027 1028
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
1029
{
1030
    char *conf_file;
1031
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1032
    FILE *fp = NULL;
1033
    int ret = -1;
1034 1035 1036

    if (uuid == NULL)
        return -1;
1037

1038
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
1039
        return -1;
1040

1041
    if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr)))
1042
        goto cleanup;
1043

J
Jim Meyering 已提交
1044
    if (uuidstr[0] == 0) {
1045
        fp = fopen(conf_file, "a"); /* append */
1046
        if (fp == NULL)
1047
            goto cleanup;
1048

1049 1050
        virUUIDFormat(uuid, uuidstr);

1051
        /* Record failure if fprintf or VIR_FCLOSE fails,
1052
           and be careful always to close the stream.  */
1053 1054
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) ||
            (VIR_FCLOSE(fp) == EOF))
1055
            goto cleanup;
1056 1057
    }

1058 1059
    ret = 0;
cleanup:
1060
    VIR_FORCE_FCLOSE(fp);
1061 1062
    VIR_FREE(conf_file);
    return ret;
1063 1064
}

1065 1066 1067 1068
static int
openvzSetUUID(int vpsid){
    unsigned char uuid[VIR_UUID_BUFLEN];

1069
    if (virUUIDGenerate(uuid)) {
1070 1071
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to generate UUID"));
1072 1073
        return -1;
    }
1074 1075 1076 1077

    return openvzSetDefinedUUID(vpsid, uuid);
}

1078 1079 1080 1081 1082 1083 1084
/*
 * Scan VPS config files and see if they have a UUID.
 * If not, assign one. Just append one to the config
 * file as comment so that the OpenVZ tools ignore it.
 *
 */

1085
static int openvzAssignUUIDs(void)
1086 1087 1088 1089
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
1090 1091 1092
    int vpsid;
    char *ext;
    int ret = 0;
1093 1094

    conf_dir = openvzLocateConfDir();
1095 1096
    if (conf_dir == NULL)
        return -1;
1097 1098

    dp = opendir(conf_dir);
E
Eric Blake 已提交
1099
    if (dp == NULL) {
1100
        VIR_FREE(conf_dir);
1101 1102 1103
        return 0;
    }

1104
    errno = 0;
E
Eric Blake 已提交
1105
    while ((dent = readdir(dp))) {
1106 1107 1108
        if (virStrToLong_i(dent->d_name, &ext, 10, &vpsid) < 0 ||
            *ext++ != '.' ||
            STRNEQ(ext, "conf"))
1109
            continue;
E
Eric Blake 已提交
1110
        if (vpsid > 0) /* '0.conf' belongs to the host, ignore it */
1111
            openvzSetUUID(vpsid);
1112 1113 1114
        errno = 0;
    }
    if (errno) {
1115 1116
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to scan configuration directory"));
1117
        ret = -1;
1118
    }
1119

1120
    closedir(dp);
1121
    VIR_FREE(conf_dir);
1122
    return ret;
1123
}
1124 1125 1126 1127 1128 1129 1130 1131


/*
 * Return CTID from name
 *
 */

int openvzGetVEID(const char *name) {
E
Eric Blake 已提交
1132 1133
    virCommandPtr cmd;
    char *outbuf;
1134
    char *temp;
1135
    int veid;
1136
    bool ok;
1137

E
Eric Blake 已提交
1138 1139 1140 1141 1142
    cmd = virCommandNewArgList(VZLIST, name, "-ovpsid", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0) {
        virCommandFree(cmd);
        VIR_FREE(outbuf);
1143 1144 1145
        return -1;
    }

E
Eric Blake 已提交
1146
    virCommandFree(cmd);
1147
    ok = virStrToLong_i(outbuf, &temp, 10, &veid) == 0 && *temp == '\n';
E
Eric Blake 已提交
1148
    VIR_FREE(outbuf);
1149

1150 1151 1152
    if (ok && veid >= 0)
        return veid;

1153 1154
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Failed to parse vzlist output"));
1155 1156
    return -1;
}