aboutsummaryrefslogtreecommitdiffstats
path: root/docs/getting_started_vagrant.md
diff options
context:
space:
mode:
Diffstat (limited to 'docs/getting_started_vagrant.md')
0 files changed, 0 insertions, 0 deletions
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
import os, re, socket, string, sys, tempfile, xenctl.ip

##### Module variables

"""Location of the Virtual Disk management database.
   defaults to /var/db/xen_vdisks.sqlite
"""
VD_DB_FILE = "/var/db/xen_vdisks.sqlite"

"""VBD expertise level - determines the strictness of the sanity checking.
  This mode determines the level of complaints when disk sharing occurs
  through the current VBD mappings.
   0 - only allow shared mappings if both domains have r/o access (always OK)
   1 - also allow sharing with one dom r/w and the other r/o
   2 - allow sharing with both doms r/w
"""
VBD_EXPERT_MODE = 0

##### Module initialisation

try:
    # try to import sqlite (not everyone will have it installed)
    import sqlite
except ImportError:
    # on failure, just catch the error, don't do anything
    pass


##### Networking-related functions

def get_current_ipaddr(dev='eth0'):
    return xenctl.ip.get_current_ipaddr(dev)
def get_current_ipmask(dev='eth0'):
    return xenctl.ip.get_current_ipmask(dev)
def get_current_ipgw(dev='eth0'):
    return xenctl.ip.get_current_ipgw(dev)
def setup_vfr_rules_for_vif(dom,vif,addr):
    return xenctl.ip.setup_vfr_rules_for_vif(dom,vif,addr)
def inet_aton(addr):
    return xenctl.ip.inet_aton(addr)
def inet_ntoa(n):
    return xenctl.ip.inet_ntoa(n)
def add_offset_to_ip(addr, offset):
    return xenctl.ip.add_offset_to_ip(addr, offset)
def check_subnet( ip, network, netmask ):
    return xenctl.ip.check_subnet( ip, network, netmask )

##### VBD-related Functions

def blkdev_name_to_number(name):
    """Take the given textual block-device name (e.g., '/dev/sda1',
    'hda') and return the device number used by the OS. """

    if not re.match( '/dev/', name ):
        name = '/dev/' + name
        
    return os.stat(name).st_rdev

# lookup_blkdev_partn_info( '/dev/sda3' )
def lookup_raw_partn(partition):
    """Take the given block-device name (e.g., '/dev/sda1', 'hda')
    and return a dictionary { device, start_sector,
    nr_sectors, type }
        device:       Device number of the given partition
        start_sector: Index of first sector of the partition
        nr_sectors:   Number of sectors comprising this partition
        type:         'Disk' or identifying name for partition type
    """

    if not re.match( '/dev/', partition ):
        partition = '/dev/' + partition

    drive = re.split( '[0-9]', partition )[0]

    if drive == partition:
        fd = os.popen( '/sbin/sfdisk -s ' + drive + ' 2>/dev/null' )
        line = fd.readline()
        if line:
            return [ { 'device' : blkdev_name_to_number(drive),
                       'start_sector' : long(0),
                       'nr_sectors' : long(line) * 2,
                       'type' : 'Disk' } ]
        return None

    # determine position on disk
    fd = os.popen( '/sbin/sfdisk -d ' + drive + ' 2>/dev/null' )

    #['/dev/sda3 : start= 16948575, size=16836120, Id=83, bootable\012']
    lines = fd.readlines()
    for line in lines:
        m = re.search( '^' + partition + '\s*: start=\s*([0-9]+), ' +
                       'size=\s*([0-9]+), Id=\s*(\S+).*$', line)
        if m:
            return [ { 'device' : blkdev_name_to_number(drive),
                       'start_sector' : long(m.group(1)),
                       'nr_sectors' : long(m.group(2)),
                       'type' : m.group(3) } ]
    
    return None

def lookup_disk_uname( uname ):
    """Lookup a list of segments for either a physical or a virtual device.
    uname [string]:  name of the device in the format \'vd:id\' for a virtual
                     disk, or \'phy:dev\' for a physical device
    returns [list of dicts]: list of extents that make up the named device
    """
    ( type, d_name ) = string.split( uname, ':' )

    if type == "phy":
        segments = lookup_raw_partn( d_name )
    elif type == "vd":
	segments = vd_lookup( d_name )

    return segments


##### Management of the Xen control daemon
##### (c) Keir Fraser, University of Cambridge

def xend_control_message( message ):
    """Takes a textual control message and sends it to the 'xend' Xen
    control daemon. Returns a dictionary containing the daemon's multi-part
    response."""
    tmpdir = tempfile.mkdtemp()
    try:
        ctl = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM, 0)
        ctl.bind(tmpdir+'/sock')
        ctl.sendto(message, '/var/run/xend/management_sock')
        data, addr = ctl.recvfrom(2048)
        ctl.close()
    finally:
        if os.path.exists(tmpdir+'/sock'):
            os.unlink(tmpdir+'/sock')
        if os.path.exists(tmpdir):
            os.rmdir(tmpdir)    
    return eval(data)


##### VD Management-related functions

##### By Mark Williamson, <mark.a.williamson@intel.com>
##### (C) Intel Research Cambridge

# TODO:
#
# Plenty of room for enhancement to this functionality (contributions
# welcome - and then you get to have your name in the source ;-)...
#
# vd_unformat() : want facilities to unallocate virtual disk
# partitions, possibly migrating virtual disks of them, with checks to see if
# it's safe and options to force it anyway
#
# vd_create() : should have an optional argument specifying a physical
# disk preference - useful to allocate for guest doms to do RAID
#
# vd_undelete() : add ability to "best effort" undelete as much of a
# vdisk as is left in the case that some of it has already been
# reallocated.  Some people might still be able to recover some of
# their data this way, even if some of the disk has disappeared.
#
# It'd be nice if we could wipe virtual disks for security purposes -
# should be easy to do this using dev if=/dev/{zero,random} on each
# extent in turn.  There could be another optional flag to vd_create
# in order to allow this.
#
# Error codes could be more expressive - i.e. actually tell why the
# error occurred rather than "it broke".  Currently the code avoids
# using exceptions to make control scripting simpler and more
# accessible to beginners - therefore probably should just use more
# return codes.
#
# Enhancements / additions to the example scripts are also welcome:
# some people will interact with this code mostly through those
# scripts.
#
# More documentation of how this stuff should be used is always nice -
# if you have a novel configuration that you feel isn't discussed
# enough in the HOWTO (which is currently a work in progress), feel
# free to contribute a walkthrough, or something more substantial.
#


def __vd_no_database():
    """Called when no database found - exits with an error
    """
    print >> sys.stderr, "ERROR: Could not locate the database file at " + VD_DB_FILE
    sys.exit(1)


def vd_format(partition, extent_size_mb):
    """Format a partition or drive for use a virtual disk storage.
    partition [string]: device file representing the partition
    extent_size_mb [string]: extent size in megabytes to use on this disk
    """

    if not os.path.isfile(VD_DB_FILE):
        vd_init_db(VD_DB_FILE)
    
    if not re.match( '/dev/', partition ):
        partition = '/dev/' + partition

    cx = sqlite.connect(VD_DB_FILE)
    cu = cx.cursor()

    cu.execute("select * from vdisk_part where partition = \'"
               + partition + "\'")
    row = cu.fetchone()

    extent_size = extent_size_mb * 2048 # convert megabytes to sectors
    
    if not row:
        part_info = lookup_raw_partn(partition)[0]
        
        cu.execute("INSERT INTO vdisk_part(partition, part_id, extent_size) " +
                   "VALUES ( \'" + partition + "\', "
                   + str(blkdev_name_to_number(partition))
                   + ", " + str(extent_size) + ")")


        cu.execute("SELECT max(vdisk_extent_no) FROM vdisk_extents "
                   + "WHERE vdisk_id = 0")
        
        max_id, = cu.fetchone()

        if max_id != None:
            new_id = max_id + 1
        else:
            new_id = 0

        num_extents = part_info['nr_sectors'] / extent_size

        for i in range(num_extents):
            sql ="""INSERT INTO vdisk_extents(vdisk_extent_no, vdisk_id,
                                              part_id, part_extent_no)
                    VALUES ("""+ str(new_id + i) + ", 0, "\
                               + str(blkdev_name_to_number(partition))\
                               + ", " + str(num_extents - (i + 1)) + ")"
            cu.execute(sql)

    cx.commit()
    cx.close()
    return 0


def vd_create(size_mb, expiry):
    """Create a new virtual disk.
    size_mb [int]: size in megabytes for the new virtual disk
    expiry [int]: expiry time in seconds from now
    """

    if not os.path.isfile(VD_DB_FILE):
        __vd_no_database()

    cx = sqlite.connect(VD_DB_FILE)
    cu = cx.cursor()

    size = size_mb * 2048

    cu.execute("SELECT max(vdisk_id) FROM vdisks")
    max_id, = cu.fetchone()
    new_id = int(max_id) + 1

    # fetch a list of extents from the expired disks, along with information
    # about their size
    cu.execute("""SELECT vdisks.vdisk_id, vdisk_extent_no, part_extent_no,
                         vdisk_extents.part_id, extent_size
                  FROM vdisks NATURAL JOIN vdisk_extents
                                                  NATURAL JOIN vdisk_part
                  WHERE expires AND expiry_time <= datetime('now')
                  ORDER BY expiry_time ASC, vdisk_extent_no DESC
               """)  # aims to reuse the last extents
                     # from the longest-expired disks first

    allocated = 0

    if expiry:
        expiry_ts = "datetime('now', '" + str(expiry) + " seconds')"
        expires = 1
    else:
        expiry_ts = "NULL"
        expires = 0

    # we'll use this to build the SQL statement we want
    building_sql = "INSERT INTO vdisks(vdisk_id, size, expires, expiry_time)" \
                   +" VALUES ("+str(new_id)+", "+str(size)+ ", "              \
                   + str(expires) + ", " + expiry_ts + "); "

    counter = 0

    while allocated < size:
        row = cu.fetchone()
        if not row:
            print "ran out of space, having allocated %d meg of %d" % (allocated, size)
            cx.close()
            return -1
        

        (vdisk_id, vdisk_extent_no, part_extent_no, part_id, extent_size) = row
        allocated += extent_size
        building_sql += "UPDATE vdisk_extents SET vdisk_id = " + str(new_id) \
                        + ", " + "vdisk_extent_no = " + str(counter)         \
                        + " WHERE vdisk_extent_no = " + str(vdisk_extent_no) \
                        + " AND vdisk_id = " + str(vdisk_id) + "; "

        counter += 1
        

    # this will execute the SQL query we build to store details of the new