openvz_conf.c 26.2 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"
E
Eric Blake 已提交
53
#include "virfile.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 openvzAssignUUIDs(void);
62 63 64
static int openvzLocateConfFileDefault(int vpsid, char **conffile, const char *ext);

openvzLocateConfFileFunc openvzLocateConfFile = openvzLocateConfFileDefault;
65

66
int
67
strtoI(const char *str)
68 69 70
{
    int val;

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

74 75 76
    return val;
}

77 78

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

    if (retversion)
        *retversion = 0;

90 91
    virCommandAddEnvString(cmd, "LC_ALL=C");
    virCommandSetOutputBuffer(cmd, &help);
92

93 94
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
95

96 97 98 99
    tmp = help;

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

102
    if (virParseVersionString(tmp, &version, false) < 0)
103
        goto cleanup;
104 105 106 107 108 109

    if (retversion)
        *retversion = version;

    ret = 0;

110 111
cleanup:
    virCommandFree(cmd);
112 113 114 115 116
    VIR_FREE(help);

    return ret;
}

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

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

    return 0;
}


132 133 134 135 136
static int openvzDefaultConsoleType(const char *ostype ATTRIBUTE_UNUSED)
{
    return VIR_DOMAIN_CHR_CONSOLE_TARGET_TYPE_OPENVZ;
}

137 138 139 140 141 142 143 144 145 146 147 148
virCapsPtr openvzCapsInit(void)
{
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

149
    if (nodeCapsInitNUMA(caps) < 0)
150 151
        goto no_memory;

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

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
    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;

172
    caps->defaultInitPath = "/sbin/init";
173
    caps->defaultConsoleTargetType = openvzDefaultConsoleType;
174 175

    return caps;
176 177 178 179 180 181
no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}


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

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

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

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

242
            char *p = token;
243 244 245 246 247
            char cpy_temp[32];
            int len;

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

260 261 262
                    if (VIR_ALLOC_N(net->ifname, len+1) < 0)
                        goto no_memory;

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

277 278 279
                    if (VIR_ALLOC_N(net->data.bridge.brname, len+1) < 0)
                        goto no_memory;

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

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

312 313 314 315
            token = strtok_r(NULL, ";", &saveptr);
        }
    }

316 317
    VIR_FREE(temp);

318
    return 0;
319
no_memory:
320
    virReportOOMError();
321
error:
322
    VIR_FREE(temp);
323
    virDomainNetDefFree(net);
324
    return -1;
325 326 327
}


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

339
    if ((!from) || (!to))
340
        return NULL;
341 342
    from_len = strlen(from);
    to_len = strlen(to);
343

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

351
    virBufferAdd(&buf, str_start, -1);
352

353 354 355 356
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        return NULL;
    }
357 358 359 360 361

    return virBufferContentAndReset(&buf);
}


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

370
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
371
    if (ret < 0) {
372
        openvzError(VIR_ERR_INTERNAL_ERROR,
373
                    _("Could not read 'OSTEMPLATE' from config for container %d"),
374 375 376 377 378 379 380 381
                    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);
382 383
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
384
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
385
        if (ret <= 0) {
386
            openvzError(VIR_ERR_INTERNAL_ERROR,
387
                        _("Could not read 'VE_PRIVATE' from config for container %d"),
388 389 390
                        veid);
            goto error;
        }
391

392
        if (VIR_ALLOC(fs) < 0)
393 394
            goto no_memory;

395 396
        if (virAsprintf(&veid_str, "%d", veid) < 0)
            goto no_memory;
397 398 399

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

401
        VIR_FREE(veid_str);
402 403
    }

404 405 406 407 408 409 410 411 412 413
    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;

414 415
    VIR_FREE(temp);

416 417
    return 0;
no_memory:
418
    virReportOOMError();
419
error:
420
    VIR_FREE(temp);
421 422 423 424 425
    virDomainFSDefFree(fs);
    return -1;
}


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

433
    virDomainObjListDeinit(&driver->domains);
434
    virCapabilitiesFree(driver->caps);
435
    VIR_FREE(driver);
436
}
D
Daniel Veillard 已提交
437 438 439



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

450 451
    if (openvzAssignUUIDs() < 0)
        return -1;
452

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

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

469
        if (VIR_ALLOC(dom) < 0)
470
            goto no_memory;
471

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

479 480
        virDomainObjLock(dom);

481 482
        if (VIR_ALLOC(dom->def) < 0)
            goto no_memory;
483

484 485
        dom->def->virtType = VIR_DOMAIN_VIRT_OPENVZ;

J
Jiri Denemark 已提交
486 487 488 489 490 491 492
        if (STREQ(status, "stopped")) {
            virDomainObjSetState(dom, VIR_DOMAIN_SHUTOFF,
                                 VIR_DOMAIN_SHUTOFF_UNKNOWN);
        } else {
            virDomainObjSetState(dom, VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_UNKNOWN);
        }
493

494
        dom->refs = 1;
495
        dom->pid = veid;
J
Jiri Denemark 已提交
496 497 498 499
        if (virDomainObjGetState(dom, NULL) == VIR_DOMAIN_SHUTOFF)
            dom->def->id = -1;
        else
            dom->def->id = veid;
500 501
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
502

503
        if (virAsprintf(&dom->def->name, "%i", veid) < 0)
504
            goto no_memory;
505

506
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
507
        ret = virUUIDParse(uuidstr, dom->def->uuid);
508

509
        if (ret == -1) {
510 511
            openvzError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("UUID in config file malformed"));
512
            goto cleanup;
513
        }
514

515 516 517 518
        if (!(dom->def->os.type = strdup("exe")))
            goto no_memory;
        if (!(dom->def->os.init = strdup("/sbin/init")))
            goto no_memory;
519

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

E
Eric Blake 已提交
530 531 532
        if (ret == 0 || dom->def->maxvcpus == 0)
            dom->def->maxvcpus = openvzGetNodeCPUs();
        dom->def->vcpus = dom->def->maxvcpus;
533

534
        /* XXX load rest of VM config data .... */
535

536 537
        openvzReadNetworkConf(dom->def, veid);
        openvzReadFSConf(dom->def, veid);
538

539 540
        virUUIDFormat(dom->def->uuid, uuidstr);
        if (virHashAddEntry(driver->domains.objs, uuidstr, dom) < 0)
541
            goto cleanup;
542

543
        virDomainObjUnlock(dom);
544
        dom = NULL;
545
    }
546

E
Eric Blake 已提交
547
    virCommandFree(cmd);
548
    VIR_FREE(temp);
E
Eric Blake 已提交
549
    VIR_FREE(outbuf);
550

551
    return 0;
552

553
 no_memory:
554
    virReportOOMError();
555

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

566 567 568 569 570
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

571
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
572 573 574 575
        return 0;

    return nodeinfo.cpus;
}
576

577 578
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
579
{
580
    char * temp_file = NULL;
581 582 583 584
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
585

586
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0) {
587
        virReportOOMError();
588
        return -1;
589
    }
590

591 592
    fp = fopen(conf_file, "r");
    if (fp == NULL)
593
        goto error;
594 595
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (temp_fd == -1) {
596
        goto error;
597 598
    }

E
Eric Blake 已提交
599
    while (1) {
600
        if (getline(&line, &line_size, fp) <= 0)
601 602
            break;

603
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
604 605 606 607 608 609 610 611 612 613 614 615
            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;

616
    if (VIR_FCLOSE(fp) < 0)
617
        goto error;
618
    if (VIR_CLOSE(temp_fd) < 0)
619 620 621 622 623
        goto error;

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

624 625
    VIR_FREE(line);

626 627 628
    return 0;

error:
629 630
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
631
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
632
    if (temp_file)
633 634
        unlink(temp_file);
    VIR_FREE(temp_file);
635 636 637
    return -1;
}

638
int
639 640
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
641 642
    char *conf_file;
    int ret;
643

644
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
645 646
        return -1;

647 648 649
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
650 651
}

652 653 654
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
655 656
 *
 * Returns <0 on error, 0 if not found, 1 if found.
657
 */
658
int
659
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
660
{
661 662 663
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
664 665
    int err = 0;
    char *sf, *token, *saveptr = NULL;
666

667 668
    fp = fopen(conf_file, "r");
    if (fp == NULL)
669 670
        return -1;

671
    VIR_FREE(*value);
672 673 674 675 676 677
    while (1) {
        if (getline(&line, &line_size, fp) < 0) {
            err = !feof(fp);
            break;
        }

678 679 680 681 682 683
        if (! STREQLEN(line, param, strlen(param)))
            continue;

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

684
        saveptr = NULL;
685 686 687 688 689 690
        if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) {
            VIR_FREE(*value);
            *value = strdup(token);
            if (*value == NULL) {
                err = 1;
                break;
691
            }
692 693
            /* keep going - last entry wins */
        }
694
    }
695 696
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
697

698
    return err ? -1 : *value ? 1 : 0;
699 700
}

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

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

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

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

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

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

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

753
    if (VIR_FCLOSE(fp) < 0)
754
        goto error;
755
    if (VIR_CLOSE(copy_fd) < 0)
756 757
        goto error;

758 759
    VIR_FREE(line);

760 761 762
    return 0;

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

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

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

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

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

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

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

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

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

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

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

    VIR_FREE(confdir);
    return ret;
}

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

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

    return NULL;
}

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

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

874
static int
875
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
876
{
877
    char *conf_file;
878 879
    char *line = NULL;
    size_t line_size = 0;
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 895 896 897 898 899 900
        if (getline(&line, &line_size, fp) < 0) {
            if (feof(fp)) { /* EOF, UUID was not found */
                uuidstr[0] = 0;
                break;
            } else {
                goto cleanup;
            }
901 902
        }

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