openvz_conf.c 28.5 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
 cleanup:
109
    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
 error:
164
    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
                                   false, false)) == NULL)
176 177
        goto no_memory;

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

181
    if ((guest = virCapabilitiesAddGuest(caps,
182
                                         VIR_DOMAIN_OSTYPE_EXE,
183
                                         caps->host.arch,
184 185 186 187 188 189 190
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
191
                                      VIR_DOMAIN_VIRT_OPENVZ,
192 193 194 195 196 197
                                      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 209
                      int veid)
{
210
    int ret;
211
    virDomainNetDefPtr net = NULL;
212
    char *temp = NULL;
213 214 215 216 217
    char *token, *saveptr = NULL;

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

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
233
            if (virDomainNetAppendIpAddress(net, token, AF_UNSPEC, 0) < 0)
234
                goto error;
235

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

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

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

            net->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

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

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

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

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

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

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

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

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

335 336
    VIR_FREE(temp);

337
    return 0;
338

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


346
static int
347
openvzReadFSConf(virDomainDefPtr def,
348 349
                 int veid)
{
350 351
    int ret;
    virDomainFSDefPtr fs = NULL;
352 353
    char *veid_str = NULL;
    char *temp = NULL;
354 355
    const char *param;
    unsigned long long barrier, limit;
356

357
    ret = openvzReadVPSConfigParam(veid, "OSTEMPLATE", &temp);
358
    if (ret < 0) {
359 360 361
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read 'OSTEMPLATE' from config for container %d"),
                       veid);
362 363 364
        goto error;
    } else if (ret > 0) {
        if (VIR_ALLOC(fs) < 0)
365
            goto error;
366 367

        fs->type = VIR_DOMAIN_FS_TYPE_TEMPLATE;
368 369
        if (VIR_STRDUP(fs->src, temp) < 0)
            goto error;
370 371
    } else {
        /* OSTEMPLATE was not found, VE was booted from a private dir directly */
372
        ret = openvzReadVPSConfigParam(veid, "VE_PRIVATE", &temp);
373
        if (ret <= 0) {
374 375 376
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read 'VE_PRIVATE' from config for container %d"),
                           veid);
377 378
            goto error;
        }
379

380
        if (VIR_ALLOC(fs) < 0)
381
            goto error;
382

383
        if (virAsprintf(&veid_str, "%d", veid) < 0)
384
            goto error;
385 386

        fs->type = VIR_DOMAIN_FS_TYPE_MOUNT;
387 388
        if (!(fs->src = virStringReplace(temp, "$VEID", veid_str)))
            goto error;
389

390
        VIR_FREE(veid_str);
391 392
    }

393 394
    if (VIR_STRDUP(fs->dst, "/") < 0)
        goto error;
395

396 397 398 399
    param = "DISKSPACE";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret > 0) {
        if (openvzParseBarrierLimit(temp, &barrier, &limit)) {
400 401 402
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read '%s' from config for container %d"),
                           param, veid);
403 404 405
            goto error;
        } else {
            /* Ensure that we can multiply by 1024 without overflowing. */
406
            if (barrier > ULLONG_MAX / 1024 ||
407
                limit > ULLONG_MAX / 1024) {
J
Jiri Denemark 已提交
408 409
                virReportError(VIR_ERR_OVERFLOW, "%s",
                               _("Unable to parse quota"));
410 411 412 413 414 415 416
                goto error;
            }
            fs->space_soft_limit = barrier * 1024; /* unit is bytes */
            fs->space_hard_limit = limit * 1024;   /* unit is bytes */
        }
    }

417
    if (VIR_APPEND_ELEMENT(def->fss, def->nfss, fs) < 0)
418
        goto error;
419

420 421
    VIR_FREE(temp);

422
    return 0;
423
 error:
424
    VIR_FREE(temp);
425 426 427 428 429
    virDomainFSDefFree(fs);
    return -1;
}


430 431 432
static int
openvzReadMemConf(virDomainDefPtr def, int veid)
{
433
    int ret = -1;
434 435 436
    char *temp = NULL;
    unsigned long long barrier, limit;
    const char *param;
437
    long kb_per_pages;
438

439 440
    kb_per_pages = openvzKBPerPages();
    if (kb_per_pages < 0)
441 442 443 444 445 446
        goto error;

    /* Memory allocation guarantee */
    param = "VMGUARPAGES";
    ret = openvzReadVPSConfigParam(veid, param, &temp);
    if (ret < 0) {
447 448 449
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
450 451 452 453
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, NULL);
        if (ret < 0) {
454 455 456
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier of '%s' "
                             "from config for container %d"), param, veid);
457 458 459 460 461 462 463 464 465 466 467 468
            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) {
469 470 471
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not read '%s' from config for container %d"),
                       param, veid);
472 473 474 475
        goto error;
    } else if (ret > 0) {
        ret = openvzParseBarrierLimit(temp, &barrier, &limit);
        if (ret < 0) {
476 477 478
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not parse barrier and limit of '%s' "
                             "from config for container %d"), param, veid);
479 480 481
            goto error;
        }
        if (barrier == LONG_MAX)
482
            def->mem.soft_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
483 484 485 486
        else
            def->mem.soft_limit = barrier * kb_per_pages;

        if (limit == LONG_MAX)
487
            def->mem.hard_limit = VIR_DOMAIN_MEMORY_PARAM_UNLIMITED;
488 489 490 491 492
        else
            def->mem.hard_limit = limit * kb_per_pages;
    }

    ret = 0;
493
 error:
494 495 496 497 498
    VIR_FREE(temp);
    return ret;
}


499 500 501 502 503 504
/* Free all memory associated with a openvz_driver structure */
void
openvzFreeDriver(struct openvz_driver *driver)
{
    if (!driver)
        return;
505

506
    virObjectUnref(driver->xmlopt);
507
    virObjectUnref(driver->domains);
508
    virObjectUnref(driver->caps);
509
    VIR_FREE(driver);
510
}
D
Daniel Veillard 已提交
511 512 513



514 515
int openvzLoadDomains(struct openvz_driver *driver)
{
516
    int veid, ret;
517
    char *status;
518
    char uuidstr[VIR_UUID_STRING_BUFLEN];
519
    virDomainObjPtr dom = NULL;
520
    virDomainDefPtr def = NULL;
521
    char *temp = NULL;
E
Eric Blake 已提交
522 523 524
    char *outbuf = NULL;
    char *line;
    virCommandPtr cmd = NULL;
525
    unsigned int vcpus = 0;
526

527 528
    if (openvzAssignUUIDs() < 0)
        return -1;
529

E
Eric Blake 已提交
530 531 532 533
    cmd = virCommandNewArgList(VZLIST, "-a", "-ovpsid,status", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;
534

535 536
    line = outbuf;
    while (line[0] != '\0') {
537
        unsigned int flags = 0;
538 539 540
        if (virStrToLong_i(line, &status, 10, &veid) < 0 ||
            *status++ != ' ' ||
            (line = strchr(status, '\n')) == NULL) {
541 542
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Failed to parse vzlist output"));
543
            goto cleanup;
544
        }
545
        *line++ = '\0';
546

547
        if (!(def = virDomainDefNew()))
548
            goto cleanup;
549

550
        def->virtType = VIR_DOMAIN_VIRT_OPENVZ;
551

552 553
        if (STREQ(status, "stopped"))
            def->id = -1;
J
Jiri Denemark 已提交
554
        else
555 556
            def->id = veid;
        if (virAsprintf(&def->name, "%i", veid) < 0)
557
            goto cleanup;
558

559
        openvzGetVPSUUID(veid, uuidstr, sizeof(uuidstr));
560
        ret = virUUIDParse(uuidstr, def->uuid);
561

562
        if (ret == -1) {
563 564
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("UUID in config file malformed"));
565
            goto cleanup;
566
        }
567

568
        def->os.type = VIR_DOMAIN_OSTYPE_EXE;
569 570
        if (VIR_STRDUP(def->os.init, "/sbin/init") < 0)
            goto cleanup;
571

572
        ret = openvzReadVPSConfigParam(veid, "CPUS", &temp);
573
        if (ret < 0) {
574 575 576
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not read config for container %d"),
                           veid);
577
            goto cleanup;
578
        } else if (ret > 0) {
579
            vcpus = strtoI(temp);
580 581
        }

582 583 584
        if (ret == 0 || vcpus == 0)
            vcpus = openvzGetNodeCPUs();

585 586 587
        if (virDomainDefSetVcpusMax(def, vcpus) < 0)
            goto cleanup;

588 589
        if (virDomainDefSetVcpus(def, vcpus) < 0)
            goto cleanup;
590

591
        /* XXX load rest of VM config data .... */
592

593 594 595
        openvzReadNetworkConf(def, veid);
        openvzReadFSConf(def, veid);
        openvzReadMemConf(def, veid);
596

597
        virUUIDFormat(def->uuid, uuidstr);
598 599 600 601
        flags = VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE;
        if (STRNEQ(status, "stopped"))
            flags |= VIR_DOMAIN_OBJ_LIST_ADD_LIVE;

602 603
        if (!(dom = virDomainObjListAdd(driver->domains,
                                        def,
604
                                        driver->xmlopt,
605 606
                                        flags,
                                        NULL)))
607
            goto cleanup;
608 609 610 611 612 613 614 615 616

        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;
617
        }
618 619
        /* XXX OpenVZ doesn't appear to have concept of a transient domain */
        dom->persistent = 1;
620

621
        virObjectUnlock(dom);
622
        dom = NULL;
623
        def = NULL;
624
    }
625

E
Eric Blake 已提交
626
    virCommandFree(cmd);
627
    VIR_FREE(temp);
E
Eric Blake 已提交
628
    VIR_FREE(outbuf);
629

630
    return 0;
631

632
 cleanup:
E
Eric Blake 已提交
633
    virCommandFree(cmd);
634
    VIR_FREE(temp);
E
Eric Blake 已提交
635
    VIR_FREE(outbuf);
636
    virObjectUnref(dom);
637
    virDomainDefFree(def);
638
    return -1;
639 640
}

641 642 643 644 645
unsigned int
openvzGetNodeCPUs(void)
{
    virNodeInfo nodeinfo;

646
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
647 648 649 650
        return 0;

    return nodeinfo.cpus;
}
651

652 653
static int
openvzWriteConfigParam(const char * conf_file, const char *param, const char *value)
654
{
655
    char * temp_file = NULL;
656 657 658 659
    int temp_fd = -1;
    FILE *fp;
    char *line = NULL;
    size_t line_size = 0;
660

661
    if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0)
662 663
        return -1;

664 665
    fp = fopen(conf_file, "r");
    if (fp == NULL)
666
        goto error;
667
    temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
668
    if (temp_fd == -1)
669
        goto error;
670

E
Eric Blake 已提交
671
    while (1) {
672
        if (getline(&line, &line_size, fp) <= 0)
673 674
            break;

675
        if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) {
676 677 678 679 680 681 682 683 684 685 686 687
            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;

688
    if (VIR_FCLOSE(fp) < 0)
689
        goto error;
690
    if (VIR_CLOSE(temp_fd) < 0)
691 692 693 694 695
        goto error;

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

696 697
    VIR_FREE(line);

698 699
    return 0;

700
 error:
701 702
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
703
    VIR_FORCE_CLOSE(temp_fd);
E
Eric Blake 已提交
704
    if (temp_file)
705 706
        unlink(temp_file);
    VIR_FREE(temp_file);
707 708 709
    return -1;
}

710
int
711 712
openvzWriteVPSConfigParam(int vpsid, const char *param, const char *value)
{
713 714
    char *conf_file;
    int ret;
715

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

719 720 721
    ret = openvzWriteConfigParam(conf_file, param, value);
    VIR_FREE(conf_file);
    return ret;
722 723
}

724 725 726
/*
 * value will be freed before a new value is assigned to it, the caller is
 * responsible for freeing it afterwards.
727 728
 *
 * Returns <0 on error, 0 if not found, 1 if found.
729
 */
730
int
731
openvzReadConfigParam(const char *conf_file, const char *param, char **value)
732
{
733 734 735
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
736 737
    int err = 0;
    char *sf, *token, *saveptr = NULL;
738

739 740
    fp = fopen(conf_file, "r");
    if (fp == NULL)
741 742
        return -1;

743
    VIR_FREE(*value);
744 745 746 747 748 749
    while (1) {
        if (getline(&line, &line_size, fp) < 0) {
            err = !feof(fp);
            break;
        }

750 751 752 753 754 755
        if (! STREQLEN(line, param, strlen(param)))
            continue;

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

756
        saveptr = NULL;
757 758
        if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) {
            VIR_FREE(*value);
759
            if (VIR_STRDUP(*value, token) < 0) {
760 761
                err = 1;
                break;
762
            }
763 764
            /* keep going - last entry wins */
        }
765
    }
766 767
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
768

769
    return err ? -1 : *value ? 1 : 0;
770 771
}

772
/*
773 774 775 776 777 778 779 780 781 782
 * 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
 */
783
int
784
openvzReadVPSConfigParam(int vpsid, const char *param, char **value)
785
{
786 787
    char *conf_file;
    int ret;
788

789
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
790 791
        return -1;

792
    ret = openvzReadConfigParam(conf_file, param, value);
793 794
    VIR_FREE(conf_file);
    return ret;
795 796 797 798 799
}

static int
openvz_copyfile(char* from_path, char* to_path)
{
800 801 802 803
    char *line = NULL;
    size_t line_size = 0;
    FILE *fp;
    int copy_fd;
804 805
    int bytes_read;

806 807
    fp = fopen(from_path, "r");
    if (fp == NULL)
808 809 810
        return -1;
    copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (copy_fd == -1) {
811
        VIR_FORCE_FCLOSE(fp);
812 813 814
        return -1;
    }

E
Eric Blake 已提交
815
    while (1) {
816
        if (getline(&line, &line_size, fp) <= 0)
817 818 819 820 821 822 823
            break;

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

824
    if (VIR_FCLOSE(fp) < 0)
825
        goto error;
826
    if (VIR_CLOSE(copy_fd) < 0)
827 828
        goto error;

829 830
    VIR_FREE(line);

831 832
    return 0;

833
 error:
834 835
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
836
    VIR_FORCE_CLOSE(copy_fd);
837 838 839 840 841 842 843 844 845 846 847
    return -1;
}

/*
* Copy the default config to the VE conf file
* return: -1 - error
*          0 - OK
*/
int
openvzCopyDefaultConfig(int vpsid)
{
848 849 850
    char *confdir = NULL;
    char *default_conf_file = NULL;
    char *configfile_value = NULL;
851
    char *conf_file = NULL;
852 853
    int ret = -1;

854
    if (openvzReadConfigParam(VZ_CONF_FILE, "CONFIGFILE", &configfile_value) < 0)
855 856 857 858 859 860
        goto cleanup;

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

861
    if (virAsprintf(&default_conf_file, "%s/ve-%s.conf-sample", confdir,
862
                    configfile_value) < 0)
863 864
        goto cleanup;

865
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
866 867 868 869 870 871
        goto cleanup;

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

    ret = 0;
872
 cleanup:
873 874
    VIR_FREE(confdir);
    VIR_FREE(default_conf_file);
875
    VIR_FREE(configfile_value);
876
    VIR_FREE(conf_file);
877 878 879
    return ret;
}

880
/* Locate config file of container
881 882
 * return -1 - error
 *         0 - OK */
883
static int
884
openvzLocateConfFileDefault(int vpsid, char **conffile, const char *ext)
885
{
886
    char *confdir;
887 888 889 890 891 892
    int ret = 0;

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

893
    if (virAsprintf(conffile, "%s/%d.%s", confdir, vpsid,
894
                    ext ? ext : "conf") < 0)
895 896 897 898 899 900
        ret = -1;

    VIR_FREE(confdir);
    return ret;
}

901 902
static char *
openvzLocateConfDir(void)
903 904
{
    const char *conf_dir_list[] = {"/etc/vz/conf", "/usr/local/etc/conf", NULL};
905
    size_t i = 0;
906
    char *ret = NULL;
907

E
Eric Blake 已提交
908
    while (conf_dir_list[i]) {
909
        if (virFileExists(conf_dir_list[i])) {
910 911 912
            ignore_value(VIR_STRDUP(ret, conf_dir_list[i]));
            goto cleanup;
        }
E
Eric Blake 已提交
913
        i++;
914 915
    }

916
 cleanup:
917
    return ret;
918 919 920
}

/* Richard Steven's classic readline() function */
921
int
922
openvz_readline(int fd, char *ptr, int maxlen)
923 924 925 926
{
    int n, rc;
    char c;

E
Eric Blake 已提交
927
    for (n = 1; n < maxlen; n++) {
928
        if ((rc = read(fd, &c, 1)) == 1) {
929
            *ptr++ = c;
E
Eric Blake 已提交
930
            if (c == '\n')
931
                break;
E
Eric Blake 已提交
932 933
        } else if (rc == 0) {
            if (n == 1)
934 935 936 937 938 939 940 941 942 943 944
                return 0; /* EOF condition */
            else
                break;
        }
        else
            return -1; /* error */
    }
    *ptr = 0;
    return n;
}

945
static int
946
openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len)
947
{
948
    char *conf_file;
949 950
    char *line = NULL;
    size_t line_size = 0;
951
    char *saveptr = NULL;
952 953
    char *uuidbuf;
    char *iden;
954
    FILE *fp;
955
    int retval = -1;
956

957
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
958
        return -1;
959

960 961
    fp = fopen(conf_file, "r");
    if (fp == NULL)
962
        goto cleanup;
963

E
Eric Blake 已提交
964
    while (1) {
965 966 967 968 969 970 971
        if (getline(&line, &line_size, fp) < 0) {
            if (feof(fp)) { /* EOF, UUID was not found */
                uuidstr[0] = 0;
                break;
            } else {
                goto cleanup;
            }
972 973
        }

974 975 976 977
        iden = strtok_r(line, " ", &saveptr);
        uuidbuf = strtok_r(NULL, "\n", &saveptr);

        if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) {
978
            if (virStrcpy(uuidstr, uuidbuf, len) == NULL) {
979 980
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("invalid uuid %s"), uuidbuf);
981 982
                goto cleanup;
            }
983 984 985
            break;
        }
    }
986
    retval = 0;
987
 cleanup:
988 989
    VIR_FREE(line);
    VIR_FORCE_FCLOSE(fp);
990
    VIR_FREE(conf_file);
991

C
Chris Lalancette 已提交
992
    return retval;
993 994 995 996 997
}

/* Do actual checking for UUID presence in conf file,
 * assign if not present.
 */
998 999
int
openvzSetDefinedUUID(int vpsid, unsigned char *uuid)
1000
{
1001
    char *conf_file;
1002
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1003
    FILE *fp = NULL;
1004
    int ret = -1;
1005 1006 1007

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

1009
    if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0)
E
Eric Blake 已提交
1010
        return -1;
1011

1012
    if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr)))
1013
        goto cleanup;
1014

J
Jim Meyering 已提交
1015
    if (uuidstr[0] == 0) {
1016
        fp = fopen(conf_file, "a"); /* append */
1017
        if (fp == NULL)
1018
            goto cleanup;
1019

1020 1021
        virUUIDFormat(uuid, uuidstr);

1022
        /* Record failure if fprintf or VIR_FCLOSE fails,
1023
           and be careful always to close the stream.  */
1024 1025
        if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) ||
            (VIR_FCLOSE(fp) == EOF))
1026
            goto cleanup;
1027 1028
    }

1029
    ret = 0;
1030
 cleanup:
1031
    VIR_FORCE_FCLOSE(fp);
1032 1033
    VIR_FREE(conf_file);
    return ret;
1034 1035
}

1036
static int
1037 1038
openvzSetUUID(int vpsid)
{
1039 1040
    unsigned char uuid[VIR_UUID_BUFLEN];

1041
    if (virUUIDGenerate(uuid)) {
1042 1043
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to generate UUID"));
1044 1045
        return -1;
    }
1046 1047 1048 1049

    return openvzSetDefinedUUID(vpsid, uuid);
}

1050 1051 1052 1053 1054 1055 1056
/*
 * 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.
 *
 */

1057
static int openvzAssignUUIDs(void)
1058 1059 1060 1061
{
    DIR *dp;
    struct dirent *dent;
    char *conf_dir;
1062 1063 1064
    int vpsid;
    char *ext;
    int ret = 0;
1065 1066

    conf_dir = openvzLocateConfDir();
1067 1068
    if (conf_dir == NULL)
        return -1;
1069 1070

    dp = opendir(conf_dir);
E
Eric Blake 已提交
1071
    if (dp == NULL) {
1072
        VIR_FREE(conf_dir);
1073 1074 1075
        return 0;
    }

E
Eric Blake 已提交
1076
    while ((ret = virDirRead(dp, &dent, conf_dir)) > 0) {
1077 1078 1079
        if (virStrToLong_i(dent->d_name, &ext, 10, &vpsid) < 0 ||
            *ext++ != '.' ||
            STRNEQ(ext, "conf"))
1080
            continue;
E
Eric Blake 已提交
1081
        if (vpsid > 0) /* '0.conf' belongs to the host, ignore it */
1082 1083
            openvzSetUUID(vpsid);
    }
1084

1085
    closedir(dp);
1086
    VIR_FREE(conf_dir);
1087
    return ret;
1088
}
1089 1090 1091 1092 1093 1094 1095


/*
 * Return CTID from name
 *
 */

1096 1097
int openvzGetVEID(const char *name)
{
E
Eric Blake 已提交
1098 1099
    virCommandPtr cmd;
    char *outbuf;
1100
    char *temp;
1101
    int veid;
1102
    bool ok;
1103

E
Eric Blake 已提交
1104 1105 1106 1107 1108
    cmd = virCommandNewArgList(VZLIST, name, "-ovpsid", "-H", NULL);
    virCommandSetOutputBuffer(cmd, &outbuf);
    if (virCommandRun(cmd, NULL) < 0) {
        virCommandFree(cmd);
        VIR_FREE(outbuf);
1109 1110 1111
        return -1;
    }

E
Eric Blake 已提交
1112
    virCommandFree(cmd);
1113
    ok = virStrToLong_i(outbuf, &temp, 10, &veid) == 0 && *temp == '\n';
E
Eric Blake 已提交
1114
    VIR_FREE(outbuf);
1115

1116 1117 1118
    if (ok && veid >= 0)
        return veid;

1119 1120
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Failed to parse vzlist output"));
1121 1122
    return -1;
}