openvz_conf.c 26.0 KB
Newer Older
1 2 3
/*
 * openvz_conf.c: config functions for managing OpenVZ VEs
 *
4
 * Copyright (C) 2010-2011 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 20 21 22
 *
 * 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
 *
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 41
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
D
Daniel P. Berrange 已提交
42
#include <string.h>
43
#include <sys/utsname.h>
44
#include <sys/wait.h>
45

46
#include "virterror_internal.h"
47
#include "openvz_conf.h"
48 49
#include "uuid.h"
#include "buf.h"
50
#include "memory.h"
51
#include "util.h"
52
#include "nodeinfo.h"
53
#include "files.h"
E
Eric Blake 已提交
54
#include "command.h"
55
#include "ignore-value.h"
56

57 58
#define VIR_FROM_THIS VIR_FROM_OPENVZ

59
static char *openvzLocateConfDir(void);
60
static int openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len);
61
static int openvzLocateConfFile(int vpsid, char **conffile, const char *ext);
62
static int openvzAssignUUIDs(void);
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 77 78 79 80 81 82 83

static int
openvzExtractVersionInfo(const char *cmd, int *retversion)
{
    const char *const vzarg[] = { cmd, "--help", NULL };
    const char *const vzenv[] = { "LC_ALL=C", NULL };
    pid_t child;
    int newstdout = -1;
    int ret = -1, status;
84 85
    unsigned long version;
    char *tmp;
86 87 88 89

    if (retversion)
        *retversion = 0;

90
    if (virExec(vzarg, vzenv, NULL,
91 92 93 94
                &child, -1, &newstdout, NULL, VIR_EXEC_NONE) < 0)
        return -1;

    char *help = NULL;
95
    int len = virFileReadLimFD(newstdout, 4096, &help);
96 97 98
    if (len < 0)
        goto cleanup2;

99 100 101 102
    tmp = help;

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

105 106
    if (virParseVersionString(tmp, &version) < 0)
        goto cleanup2;
107 108 109 110 111 112 113 114

    if (retversion)
        *retversion = version;

    ret = 0;

cleanup2:
    VIR_FREE(help);
115
    if (VIR_CLOSE(newstdout) < 0)
116 117 118 119 120 121 122 123 124 125 126 127
        ret = -1;

rewait:
    if (waitpid(child, &status, 0) != child) {
        if (errno == EINTR)
            goto rewait;
        ret = -1;
    }

    return ret;
}

128
int openvzExtractVersion(struct openvz_driver *driver)
129 130 131 132 133
{
    if (driver->version > 0)
        return 0;

    if (openvzExtractVersionInfo(VZCTL, &driver->version) < 0) {
134 135
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Could not extract vzctl version"));
136 137 138 139 140 141 142
        return -1;
    }

    return 0;
}


143 144 145 146 147 148 149 150 151 152 153 154
virCapsPtr openvzCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

    if ((caps = virCapabilitiesNew(utsname.machine,
                                   0, 0)) == NULL)
        goto no_memory;

155
    if (nodeCapsInitNUMA(caps) < 0)
156 157
        goto no_memory;

158 159
    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x52, 0x54, 0x00 });

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    if ((guest = virCapabilitiesAddGuest(caps,
                                         "exe",
                                         utsname.machine,
                                         sizeof(int) == 4 ? 32 : 8,
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

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

no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}


185
static int
186
openvzReadNetworkConf(virDomainDefPtr def,
187
                      int veid) {
188
    int ret;
189
    virDomainNetDefPtr net = NULL;
190
    char *temp = NULL;
191 192 193 194 195 196 197
    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
     */
198
    ret = openvzReadVPSConfigParam(veid, "IP_ADDRESS", &temp);
199
    if (ret < 0) {
200 201 202
        openvzError(VIR_ERR_INTERNAL_ERROR,
                    _("Could not read 'IP_ADDRESS' from config for container %d"),
                    veid);
203 204 205 206
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, " ", &saveptr);
        while (token != NULL) {
207
            if (VIR_ALLOC(net) < 0)
208 209 210 211 212 213 214 215
                goto no_memory;

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.ipaddr = strdup(token);

            if (net->data.ethernet.ipaddr == NULL)
                goto no_memory;

216 217 218 219 220
            if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0)
                goto no_memory;
            def->nets[def->nnets++] = net;
            net = NULL;

221 222 223 224 225 226 227 228 229
            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 ';'
     */
230
    ret = openvzReadVPSConfigParam(veid, "NETIF", &temp);
231
    if (ret < 0) {
232 233 234
        openvzError(VIR_ERR_INTERNAL_ERROR,
                    _("Could not read 'NETIF' from config for container %d"),
                    veid);
235 236 237 238 239
        goto error;
    } else if (ret > 0) {
        token = strtok_r(temp, ";", &saveptr);
        while (token != NULL) {
            /*add new device to list*/
240
            if (VIR_ALLOC(net) < 0)
241 242 243 244
                goto no_memory;

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

245
            char *p = token;
246 247 248 249 250
            char cpy_temp[32];
            int len;

            /*parse string*/
            do {
251
                char *next = strchrnul (token, ',');
252
                if (STRPREFIX(p, "ifname=")) {
253 254 255
                    /* skip in libvirt */
                } else if (STRPREFIX(p, "host_ifname=")) {
                    p += 12;
256 257
                    len = next - p;
                    if (len > 16) {
258 259
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Too long network device name"));
260 261 262
                        goto error;
                    }

263 264 265
                    if (VIR_ALLOC_N(net->ifname, len+1) < 0)
                        goto no_memory;

C
Chris Lalancette 已提交
266
                    if (virStrncpy(net->ifname, p, len, len+1) == NULL) {
267
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
268 269 270
                                    _("Network ifname %s too long for destination"), p);
                        goto error;
                    }
271 272 273 274
                } else if (STRPREFIX(p, "bridge=")) {
                    p += 7;
                    len = next - p;
                    if (len > 16) {
275 276
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Too long bridge device name"));
277 278 279
                        goto error;
                    }

280 281 282
                    if (VIR_ALLOC_N(net->data.bridge.brname, len+1) < 0)
                        goto no_memory;

C
Chris Lalancette 已提交
283
                    if (virStrncpy(net->data.bridge.brname, p, len, len+1) == NULL) {
284
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
285 286 287
                                    _("Bridge name %s too long for destination"), p);
                        goto error;
                    }
288 289 290
                } else if (STRPREFIX(p, "mac=")) {
                    p += 4;
                    len = next - p;
291
                    if (len != 17) { /* should be 17 */
292 293
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Wrong length MAC address"));
294 295
                        goto error;
                    }
C
Chris Lalancette 已提交
296
                    if (virStrncpy(cpy_temp, p, len, sizeof(cpy_temp)) == NULL) {
297
                        openvzError(VIR_ERR_INTERNAL_ERROR,
C
Chris Lalancette 已提交
298 299 300
                                    _("MAC address %s too long for destination"), p);
                        goto error;
                    }
301
                    if (virParseMacAddr(cpy_temp, net->mac) < 0) {
302 303
                        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                                    _("Wrong MAC address"));
304 305 306 307 308 309
                        goto error;
                    }
                }
                p = ++next;
            } while (p < token + strlen(token));

310 311 312 313 314
            if (VIR_REALLOC_N(def->nets, def->nnets + 1) < 0)
                goto no_memory;
            def->nets[def->nnets++] = net;
            net = NULL;

315 316 317 318
            token = strtok_r(NULL, ";", &saveptr);
        }
    }

319 320
    VIR_FREE(temp);

321
    return 0;
322
no_memory:
323
    virReportOOMError();
324
error:
325
    VIR_FREE(temp);
326
    virDomainNetDefFree(net);
327
    return -1;
328 329 330
}


331 332 333 334 335 336 337
/* 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;
338 339
    int to_len;
    int from_len;
340 341
    virBuffer buf = VIR_BUFFER_INITIALIZER;

342
    if ((!from) || (!to))
343
        return NULL;
344 345
    from_len = strlen(from);
    to_len = strlen(to);
346

E
Eric Blake 已提交
347
    while ((offset = strstr(str_start, from)))
348 349 350 351 352 353
    {
        virBufferAdd(&buf, str_start, offset-str_start);
        virBufferAdd(&buf, to, to_len);
        str_start = offset + from_len;
    }

354
    virBufferAdd(&buf, str_start, -1);
355

356 357 358 359
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        return NULL;
    }
360 361 362 363 364

    return virBufferContentAndReset(&buf);
}


365
static int
366
openvzReadFSConf(virDomainDefPtr def,
367 368 369
                 int veid) {
    int ret;
    virDomainFSDefPtr fs = NULL;
370 371
    char *veid_str = NULL;
    char *temp = NULL;
372

373
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
374
    if (ret < 0) {
375
        openvzError(VIR_ERR_INTERNAL_ERROR,
376
                    _("Could not read 'OSTEMPLATE' from config for container %d"),
377 378 379 380 381 382 383 384
                    veid);
        goto error;
    } else if (ret > 0) {
        if (VIR_ALLOC(fs) < 0)
            goto no_memory;

        fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE;
        fs->src = strdup(temp);
385 386
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
387
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
388
        if (ret <= 0) {
389
            openvzError(VIR_ERR_INTERNAL_ERROR,
390
                        _("Could not read 'VE_PRIVATE' from config for container %d"),
391 392 393
                        veid);
            goto error;
        }
394

395
        if (VIR_ALLOC(fs) < 0)
396 397
            goto no_memory;

398 399
        if (virAsprintf(&veid_str, "%d", veid) < 0)
            goto no_memory;
400 401 402

        fs->type = VIR_DOMAIN_FS_TYPE_MOUNT;
        fs->src = openvz_replace(temp, "$VEID", veid_str);
403

404
        VIR_FREE(veid_str);
405 406
    }

407 408 409 410 411 412 413 414 415 416
    fs->dst = strdup("/");

    if (fs->src == NULL || fs->dst == NULL)
        goto no_memory;

    if (VIR_REALLOC_N(def->fss, def->nfss + 1) < 0)
        goto no_memory;
    def->fss[def->nfss++] = fs;
    fs = NULL;

417 418
    VIR_FREE(temp);

419 420
    return 0;
no_memory:
421
    virReportOOMError();
422
error:
423
    VIR_FREE(temp);
424 425 426 427 428
    virDomainFSDefFree(fs);
    return -1;
}


429 430 431 432 433 434
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
    if (!driver)
        return;
435

436
    virDomainObjListDeinit(&driver->domains);
437
    virCapabilitiesFree(driver->caps);
438
    VIR_FREE(driver);
439
}
D
Daniel Veillard 已提交
440 441 442



443
int openvzLoadDomains(struct openvz_driver *driver) {
444
    int veid, ret;
445
    char *status;
446
    char uuidstr[VIR_UUID_STRING_BUFLEN];
447
    virDomainObjPtr dom = NULL;
448
    char *temp = NULL;
E
Eric Blake 已提交
449 450 451
    char *outbuf = NULL;
    char *line;
    virCommandPtr cmd = NULL;
452

453 454
    if (openvzAssignUUIDs() < 0)
        return -1;
455

E
Eric Blake 已提交
456 457 458 459
    cmd = virCommandNewArgList(VZLIST, "-a", "-ovpsid,status", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
460

461 462 463 464 465
    line = outbuf;
    while (line[0] != '\0') {
        if (virStrToLong_i(line, &status, 10, &veid) < 0 ||
            *status++ != ' ' ||
            (line = strchr(status, '\n')) == NULL) {
466 467
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("Failed to parse vzlist output"));
468
            goto cleanup;
469
        }
470
        *line++ = '\0';
471

472
        if (VIR_ALLOC(dom) < 0)
473
            goto no_memory;
474

475
        if (virMutexInit(&dom->lock) < 0) {
476 477
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot initialize mutex"));
478 479 480 481
            VIR_FREE(dom);
            goto cleanup;
        }

482 483
        virDomainObjLock(dom);

484 485
        if (VIR_ALLOC(dom->def) < 0)
            goto no_memory;
486

487 488 489 490
        if (STREQ(status, "stopped"))
            dom->state = VIR_DOMAIN_SHUTOFF;
        else
            dom->state = VIR_DOMAIN_RUNNING;
491

492
        dom->refs = 1;
493 494
        dom->pid = veid;
        dom->def->id = dom->state == VIR_DOMAIN_SHUTOFF ? -1 : veid;
495 496
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
497

498
        if (virAsprintf(&dom->def->name, "%i", veid) < 0)
499
            goto no_memory;
500

501
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
502
        ret = virUUIDParse(uuidstr, dom->def->uuid);
503

504
        if (ret == -1) {
505 506
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("UUID in config file malformed"));
507
            goto cleanup;
508
        }
509

510 511 512 513
        if (!(dom->def->os.type = strdup("exe")))
            goto no_memory;
        if (!(dom->def->os.init = strdup("/sbin/init")))
            goto no_memory;
514

515
        ret = openvzReadVPSConfigParam(veid, "CPUS", &temp);
516
        if (ret < 0) {
517
            openvzError(VIR_ERR_INTERNAL_ERROR,
518
                        _("Could not read config for container %d"),
519 520
                        veid);
            goto cleanup;
521
        } else if (ret > 0) {
E
Eric Blake 已提交
522
            dom->def->maxvcpus = strtoI(temp);
523 524
        }

E
Eric Blake 已提交
525 526 527
        if (ret == 0 || dom->def->maxvcpus == 0)
            dom->def->maxvcpus = openvzGetNodeCPUs();
        dom->def->vcpus = dom->def->maxvcpus;
528

529
        /* XXX load rest of VM config data .... */
530

531 532
        openvzReadNetworkConf(dom->def, veid);
        openvzReadFSConf(dom->def, veid);
533

534 535
        virUUIDFormat(dom->def->uuid, uuidstr);
        if (virHashAddEntry(driver->domains.objs, uuidstr, dom) < 0)
536
            goto cleanup;
537

538
        virDomainObjUnlock(dom);
539
        dom = NULL;
540
    }
541

E
Eric Blake 已提交
542
    virCommandFree(cmd);
543
    VIR_FREE(temp);
E
Eric Blake 已提交
544
    VIR_FREE(outbuf);
545

546
    return 0;
547

548
 no_memory:
549
    virReportOOMError();
550

551
 cleanup:
E
Eric Blake 已提交
552
    virCommandFree(cmd);
553
    VIR_FREE(temp);
E
Eric Blake 已提交
554
    VIR_FREE(outbuf);
555
    /* dom hasn't been shared yet, so unref should return 0 */
556
    if (dom)
557
        ignore_value(virDomainObjUnref(dom));
558
    return -1;
559 560
}

561 562 563 564 565
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

566
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
567 568 569 570
        return 0;

    return nodeinfo.cpus;
}
571

572 573
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
574
{
575
    char * temp_file = NULL;
576 577 578 579
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
580

581
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0) {
582
        virReportOOMError();
583
        return -1;
584
    }
585

586 587
    fp = fopen(conf_file, "r");
    if (fp == NULL)
588
        goto error;
589 590
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (temp_fd == -1) {
591
        goto error;
592 593
    }

E
Eric Blake 已提交
594
    while (1) {
595
        if (getline(&line, &line_size, fp) <= 0)
596 597
            break;

598
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
599 600 601 602 603 604 605 606 607 608 609 610
            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;

611
    if (VIR_FCLOSE(fp) < 0)
612
        goto error;
613
    if (VIR_CLOSE(temp_fd) < 0)
614 615 616 617 618
        goto error;

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

619 620
    VIR_FREE(line);

621 622 623
    return 0;

error:
624 625
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
626
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
627
    if (temp_file)
628 629
        unlink(temp_file);
    VIR_FREE(temp_file);
630 631 632
    return -1;
}

633
int
634 635
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
636 637
    char *conf_file;
    int ret;
638

639
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
640 641
        return -1;

642 643 644
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
645 646
}

647 648 649 650
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
 */
651
static int
652
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
653
{
654 655 656 657 658 659
    char *line = NULL;
    size_t line_size = 0;
    ssize_t ret;
    FILE *fp;
    int found = 0;
    char *sf, *token;
660 661 662 663
    char *saveptr = NULL;

    value[0] = 0;

664 665
    fp = fopen(conf_file, "r");
    if (fp == NULL)
666 667
        return -1;

E
Eric Blake 已提交
668
    while (1) {
669
        ret = getline(&line, &line_size, fp);
E
Eric Blake 已提交
670
        if (ret <= 0)
671 672
            break;
        saveptr = NULL;
D
Daniel Veillard 已提交
673
        if (STREQLEN(line, param, strlen(param))) {
674 675
            sf = line;
            sf += strlen(param);
676
            if (sf[0] == '=' && sf[1] != '\0' ) {
E
Eric Blake 已提交
677
                sf++;
678
                if ((token = strtok_r(sf,"\"\t\n", &saveptr)) != NULL) {
679 680 681
                    VIR_FREE(*value);
                    *value = strdup(token);
                    if (value == NULL) {
C
Chris Lalancette 已提交
682 683 684
                        ret = -1;
                        break;
                    }
685 686
                    found = 1;
                }
687
            }
D
Daniel Veillard 已提交
688
       }
689
    }
690 691
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
692 693 694 695

    if (ret == 0 && found)
        ret = 1;

E
Eric Blake 已提交
696
    return ret;
697 698
}

699
/*
700 701 702 703 704 705 706 707 708 709
 * 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
 */
710
int
711
openvzReadVPSConfigParam(int vpsid, const char *param, char **value)
712
{
713 714
    char *conf_file;
    int ret;
715

716
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
717 718
        return -1;

719
    ret = openvzReadConfigParam(conf_file, param, value);
720 721
    VIR_FREE(conf_file);
    return ret;
722 723 724 725 726
}

static int
openvz_copyfile(char* from_path, char* to_path)
{
727 728 729 730
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
    int copy_fd;
731 732
    int bytes_read;

733 734
    fp = fopen(from_path, "r");
    if (fp == NULL)
735 736 737
        return -1;
    copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (copy_fd == -1) {
738
        VIR_FORCE_FCLOSE(fp);
739 740 741
        return -1;
    }

E
Eric Blake 已提交
742
    while (1) {
743
        if (getline(&line, &line_size, fp) <= 0)
744 745 746 747 748 749 750
            break;

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

751
    if (VIR_FCLOSE(fp) < 0)
752
        goto error;
753
    if (VIR_CLOSE(copy_fd) < 0)
754 755
        goto error;

756 757
    VIR_FREE(line);

758 759 760
    return 0;

error:
761 762
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
763
    VIR_FORCE_CLOSE(copy_fd);
764 765 766 767 768 769 770 771 772 773 774
    return -1;
}

/*
* Copy the default config to the VE conf file
* return: -1 - error
*          0 - OK
*/
int
openvzCopyDefaultConfig(int vpsid)
{
775 776 777
    char *confdir = NULL;
    char *default_conf_file = NULL;
    char *configfile_value = NULL;
778
    char *conf_file = NULL;
779 780
    int ret = -1;

781
    if (openvzReadConfigParam(VZ_CONF_FILE, "CONFIGFILE", &configfile_value) < 0)
782 783 784 785 786 787
        goto cleanup;

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

788 789
    if (virAsprintf(&default_conf_file, "%s/ve-%s.conf-sample", confdir,
                    configfile_value) < 0) {
790
        virReportOOMError();
791
        goto cleanup;
792
    }
793

794
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
795 796 797 798 799 800 801 802 803
        goto cleanup;

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

    ret = 0;
cleanup:
    VIR_FREE(confdir);
    VIR_FREE(default_conf_file);
804
    VIR_FREE(configfile_value);
805
    VIR_FREE(conf_file);
806 807 808
    return ret;
}

809 810 811 812 813
/* Locate config file of container
* return -1 - error
*         0 - OK
*/
static int
814
openvzLocateConfFile(int vpsid, char **conffile, const char *ext)
815 816 817 818 819 820 821 822
{
    char * confdir;
    int ret = 0;

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

823 824 825
    if (virAsprintf(conffile, "%s/%d.%s", confdir, vpsid,
                    ext ? ext : "conf") < 0) {
        virReportOOMError();
826
        ret = -1;
827
    }
828 829 830 831 832

    VIR_FREE(confdir);
    return ret;
}

833
static char
834
*openvzLocateConfDir(void)
835 836 837 838
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
    int i=0;

E
Eric Blake 已提交
839 840
    while (conf_dir_list[i]) {
        if (!access(conf_dir_list[i], F_OK))
841
            return strdup(conf_dir_list[i]);
E
Eric Blake 已提交
842
        i++;
843 844 845 846 847 848
    }

    return NULL;
}

/* Richard Steven's classic readline() function */
849
int
850
openvz_readline(int fd, char *ptr, int maxlen)
851 852 853 854
{
    int n, rc;
    char c;

E
Eric Blake 已提交
855 856
    for (n = 1; n < maxlen; n++) {
        if ( (rc = read(fd, &c, 1)) == 1) {
857
            *ptr++ = c;
E
Eric Blake 已提交
858
            if (c == '\n')
859
                break;
E
Eric Blake 已提交
860 861
        } else if (rc == 0) {
            if (n == 1)
862 863 864 865 866 867 868 869 870 871 872
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

873
static int
874
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
875
{
876
    char *conf_file;
877 878 879
    char *line = NULL;
    size_t line_size = 0;
    ssize_t ret;
880
    char *saveptr = NULL;
881 882
    char *uuidbuf;
    char *iden;
883
    FILE *fp;
884
    int retval = -1;
885

886
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
887
        return -1;
888

889 890
    fp = fopen(conf_file, "r");
    if (fp == NULL)
891
        goto cleanup;
892

E
Eric Blake 已提交
893
    while (1) {
894
        ret = getline(&line, &line_size, fp);
895 896
        if (ret == -1)
            goto cleanup;
897

E
Eric Blake 已提交
898
        if (ret == 0) { /* EoF, UUID was not found */
899
            uuidstr[0] = 0;
900 901 902
            break;
        }

903 904 905 906
        iden = strtok_r(line, " ", &saveptr);
        uuidbuf = strtok_r(NULL, "\n", &saveptr);

        if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) {
907 908 909 910 911
            if (virStrcpy(uuidstr, uuidbuf, len) == NULL) {
                openvzError(VIR_ERR_INTERNAL_ERROR,
                            _("invalid uuid %s"), uuidbuf);
                goto cleanup;
            }
912 913 914
            break;
        }
    }
915 916
    retval = 0;
cleanup:
917 918
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
919
    VIR_FREE(conf_file);
920

C
Chris Lalancette 已提交
921
    return retval;
922 923 924 925 926
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
927 928
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
929
{
930
    char *conf_file;
931
    char uuidstr[VIR_UUID_STRING_BUFLEN];
932
    FILE *fp = NULL;
933
    int ret = -1;
934 935 936

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

938
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
939
        return -1;
940

941
    if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr)))
942
        goto cleanup;
943

J
Jim Meyering 已提交
944
    if (uuidstr[0] == 0) {
945
        fp = fopen(conf_file, "a"); /* append */
946
        if (fp == NULL)
947
            goto cleanup;
948

949 950
        virUUIDFormat(uuid, uuidstr);

951
        /* Record failure if fprintf or VIR_FCLOSE fails,
952
           and be careful always to close the stream.  */
953 954
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) ||
            (VIR_FCLOSE(fp) == EOF))
955
            goto cleanup;
956 957
    }

958 959
    ret = 0;
cleanup:
960
    VIR_FORCE_FCLOSE(fp);
961 962
    VIR_FREE(conf_file);
    return ret;
963 964
}

965 966 967 968
static int
openvzSetUUID(int vpsid){
    unsigned char uuid[VIR_UUID_BUFLEN];

969
    if (virUUIDGenerate(uuid)) {
970 971
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to generate UUID"));
972 973
        return -1;
    }
974 975 976 977

    return openvzSetDefinedUUID(vpsid, uuid);
}

978 979 980 981 982 983 984
/*
 * 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.
 *
 */

985
static int openvzAssignUUIDs(void)
986 987 988 989
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
990 991 992
    int vpsid;
    char *ext;
    int ret = 0;
993 994

    conf_dir = openvzLocateConfDir();
995 996
    if (conf_dir == NULL)
        return -1;
997 998

    dp = opendir(conf_dir);
E
Eric Blake 已提交
999
    if (dp == NULL) {
1000
        VIR_FREE(conf_dir);
1001 1002 1003
        return 0;
    }

1004
    errno = 0;
E
Eric Blake 已提交
1005
    while ((dent = readdir(dp))) {
1006 1007 1008
        if (virStrToLong_i(dent->d_name, &ext, 10, &vpsid) < 0 ||
            *ext++ != '.' ||
            STRNEQ(ext, "conf"))
1009
            continue;
E
Eric Blake 已提交
1010
        if (vpsid > 0) /* '0.conf' belongs to the host, ignore it */
1011
            openvzSetUUID(vpsid);
1012 1013 1014 1015 1016 1017
        errno = 0;
    }
    if (errno) {
        openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("Failed to scan configuration directory"));
        ret = -1;
1018
    }
1019

1020
    closedir(dp);
1021
    VIR_FREE(conf_dir);
1022
    return ret;
1023
}
1024 1025 1026 1027 1028 1029 1030 1031


/*
 * Return CTID from name
 *
 */

int openvzGetVEID(const char *name) {
E
Eric Blake 已提交
1032 1033
    virCommandPtr cmd;
    char *outbuf;
1034
    char *temp;
1035
    int veid;
1036
    bool ok;
1037

E
Eric Blake 已提交
1038 1039 1040 1041 1042
    cmd = virCommandNewArgList(VZLIST, name, "-ovpsid", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0) {
        virCommandFree(cmd);
        VIR_FREE(outbuf);
1043 1044 1045
        return -1;
    }

E
Eric Blake 已提交
1046
    virCommandFree(cmd);
1047
    ok = virStrToLong_i(outbuf, &temp, 10, &veid) == 0 && *temp == '\n';
E
Eric Blake 已提交
1048
    VIR_FREE(outbuf);
1049

1050 1051 1052
    if (ok && veid >= 0)
        return veid;

1053 1054
    openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                _("Failed to parse vzlist output"));
1055 1056
    return -1;
}