Ejemplo n.º 1
0
def main():
    mongo_setup.global_init()
    print('Hello, welcome to the engineering shop sign in system alpha. \n')
    svc.print_day()
    # attempt to run the login code
    try:
        while True:
            case = find_user_intent()
            if case == 'admin':
                admin.run()

            elif case == 'log':
                login.run()

            else:
                print(
                    "-------------------- NOT IMPLEMENTED ----------------------"
                )
            rule = input("\n Exit? [y/n]\n")
            if rule == 'y':
                break

    # exit if user presses CrtL+C, or something goes wrong
    except (KeyboardInterrupt, SystemError, SystemExit):
        print("\n----------------Goodbye-----------------\n")
        return 0
Ejemplo n.º 2
0
 def clean(*args):
     try:
         run(['lxc-destroy', '-f', '-n', hostname])
     finally:
         if ephemeral_tinc_key and os.path.exists(ephemeral_tinc_key):
             os.unlink(ephemeral_tinc_key)
     sys.exit(0)
Ejemplo n.º 3
0
 def clean(*args):
     try:
         run(['lxc-destroy', '-f', '-n', hostname])
     finally:
         if ephemeral_tinc_key and os.path.exists(ephemeral_tinc_key):
             os.unlink(ephemeral_tinc_key)
     sys.exit(0)
Ejemplo n.º 4
0
 def on_enter(self):
     info = DepSelect.todo_deps[self.app.selected_dep]
     self.todo = info['todo']
     self.hidden = info['hidden']
     self.todo_num = info['num']
     self.queue = info['queue']
     self.re_product(self.get_product())
     try:
         import admin
         importlib.reload(admin)
         admin.run(self)
         print('admin_user')
     except ModuleNotFoundError:
         pass
Ejemplo n.º 5
0
def run_kvm(ip_address, hostname, stop, vcpus, ram, vnc, disk, base, fstab):
    #################################
    # create the copy-on-write image
    #################################
    t = time.time()
    img_path = os.path.join(os.environ['HOME'], 'vm', 'images')
    base_img_path = os.path.join(img_path, 'base3')
    if not os.path.exists(base_img_path):
        os.makedirs(base_img_path)
    persistent_img_path = os.path.join(img_path, 'persistent')
    if not os.path.exists(persistent_img_path):
        os.makedirs(persistent_img_path)
    temporary_img_path = os.path.join(img_path, 'temporary')
    if not os.path.exists(temporary_img_path):
        os.makedirs(temporary_img_path)
    new_img = os.path.join(temporary_img_path, hostname + '.img')

    tincname = hostname.replace('-','_')

    if stop:
        log.info("stopping ephemeral vm '%s'"%hostname)
        try:
            log.info("virsh shutdown '%s'"%hostname)
            log.info(virsh('shutdown', hostname))
        except: pass
        time.sleep(30) # give it at least 30 seconds to actually shut down.
        try:
            log.info("virsh destroy '%s'"%hostname)
            a = virsh('destroy', hostname)
            log.info(a)
        except:
            pass
        try:
            i = a.index('Failed to terminate process')
            if i != -1:
                log.info("couldn't destroy -- trying to kill directly")
                pid = a[i+len('Failed to terminate process'):].strip().split()[0]
                run(['kill', '-9', pid])
        except: pass
        try:
            log.info("virsh undefine '%s'"%hostname)
            log.info(virsh('undefine', hostname))
        except: pass
        try:
            path = os.path.join(conf_path, 'tinc_hosts', tincname)
            log.info("remove tinc public key '%s'"%path)
            os.unlink(path)
        except: pass
        try:
            log.info("remove ephemeral image '%s'"%new_img)
            os.unlink(new_img)
        except: pass

    if os.path.exists(new_img):
        raise RuntimeError("the image '%s' already exists; maybe the virtual machine is already running?"%new_img)

    if not base.endswith('.img'): base += '.img'
    base_img = os.path.join(base_img_path, base)


    try:
        #################################
        # create disk images
        #################################
        tmp_path = tempfile.mkdtemp()  # put here so finally below will work.

        # Transient image based on our template
        sh['qemu-img', 'create', '-b', base_img, '-f', 'qcow2', new_img]
        log.info("created %s in %s seconds", new_img, time.time()-t); t = time.time()
        # Persistent image(s)
        persistent_images = []
        for name, size, fstype, format in disk:
            if name.startswith('/dev'):
                # NOTE: size="mount point" for raw disk images
                persistent_images.append((name, size, fstype, format))
            else:
                # TODO: this functionality will be removed as soon as I move *all* UW vm's to use zvol's.
                persistent_images.append((os.path.join(persistent_img_path, '%s-%s.img'%(hostname, name)),
                                          '/mnt/'+name, fstype, format))
                img = persistent_images[-1][0]
                if not os.path.exists(img):
                    os.chdir(persistent_img_path)
                    temp = None
                    try:
                        # Unfortunately, guestfish doesn't support xfs.
                        sh['qemu-img', 'create', '-f', format, img, '%sG'%size]
                        # See salvus/salvus/scripts/salvus_nbd_format.py
                        if fstype != 'none':
                            log.info("WARNING: formatting filesystem can take a long time...")
                            run(['sudo', '/usr/local/bin/salvus_nbd_format.py', fstype, img], maxtime=1800)
                        sh['chgrp', 'kvm', img]
                        sh['chmod', 'g+rw', img]
                    finally:
                        if temp is not None:
                            shutil.rmtree(temp)
                            if os.path.exists('test1.img'):
                                os.unlink('test1.img')
                else:
                    pass
                    # TODO: else -- if too small, enlarge image if possible

        #################################
        # configure the vm's image
        #################################
        # - mount the image in a temp directory
        vmhost_tincname = socket.gethostname().replace('-','_')
        try:
            run(['guestmount', '-i', '-a', new_img, '--rw', tmp_path], maxtime=600)

            #### hostname ####
            hostname_file = os.path.join(tmp_path,'etc/hostname')
            if not os.path.exists(hostname_file):
                raise RuntimeError("missing /etc/hostname in the VM image; probably the guestmount command is not working, and the fix is probably to type 'sudo chmod a+r /boot/vmlinuz-*; sudo chmod a+rw /dev/fuse'")

            os.unlink(hostname_file)
            open(hostname_file,'w').write(hostname)
            hosts_file = os.path.join(tmp_path, 'etc/hosts')
            hosts = open(hosts_file).read()
            os.unlink(hosts_file)
            open(hosts_file,'w').write("%s\n127.0.1.1  %s\n"%(hosts, hostname))

            #### tinc vpn ####
            tinc_path = os.path.join(tmp_path, 'home/salvus/salvus/salvus/data/local/etc/tinc/')
            open(os.path.join(tinc_path, 'tinc-up'),'w').write(
                "#!/bin/sh\nifconfig $INTERFACE %s netmask 255.192.0.0 txqueuelen 10000"%ip_address)
            open(os.path.join(tinc_path, 'tinc.conf'),'w').write(
                "Name = %s\nKeyExpire = 2592000\nConnectTo = %s"%(tincname, vmhost_tincname))
            rsa_key_priv = os.path.join(tinc_path, 'rsa_key.priv')
            rsa_key_pub = os.path.join(tinc_path, 'hosts', tincname)
            if os.path.exists(rsa_key_priv): os.unlink(rsa_key_priv)
            if os.path.exists(rsa_key_pub): os.unlink(rsa_key_pub)
            sh['tincd', '--config', tinc_path, '-K']
            host_file = os.path.join(tinc_path, 'hosts', tincname)
            public_key = open(rsa_key_pub).read().strip()
            open(host_file,'w').write("TCPonly=yes\nCompression=10\nCipher = aes-128-cbc\nSubnet = %s/32\n%s"%(ip_address, public_key))
            # put the tinc public key in our local db, so that the vm can connect to host.
            shutil.copyfile(host_file, os.path.join(conf_path, 'tinc_hosts', tincname))

            #### persisent disks ####
            fstab_file = os.path.join(tmp_path, 'etc/fstab')
            try:
                f = open(fstab_file,'a')
                for i,x in enumerate(persistent_images):
                    if x[1] and x[2] not in ['none','zfs']:   # using defaults instead of nobootwait, since nobootwait causes trouble with firstboot.py
                        f.write("\n/dev/vd%s1   %s   %s   defaults  0   2\n"%(chr(98+i),x[1],x[2]))
                        mnt_point = os.path.join(tmp_path, x[1].lstrip('/'))
                        os.makedirs(mnt_point)
                f.write('\n'+fstab+'\n')
                for x in fstab.splitlines():
                    v = x.split()
                    if not x.lstrip().startswith('#') and len(v) >= 2:
                        mnt_point = os.path.join(tmp_path, v[1].lstrip('/'))
                        os.makedirs(mnt_point)

            finally:
                f.close()

        finally:
            # - unmount image and remove tmp_path
            sh['fusermount', '-u', tmp_path]
    finally:
        shutil.rmtree(tmp_path)

    log.info("configured image in %s seconds", time.time()-t); t = time.time()

    #################################
    # create and start the vm itself
    #################################
    try:
        cmd = ['virt-install',
               '--connect', 'qemu:///%s'%qemu,
               #'--cpu', 'core2duo', # definitely fails
               #'--cpu', 'core2duo,+wdt,+skinit,+osvw,+3dnowprefetch,+misalignsse,+sse4a,+abm,+cr8legacy,+extapic,+svm,+cmp_legacy,+lahf_lm,+rdtscp,+pdpe1gb,+fxsr_opt,+mmxext,+aes,+popcnt,+sse4.2,+sse4.1,+cx16,+ht',  # definitely does NOT work
               '--cpu', 'host',  # definitely fails
               '--network', 'network:default,model=virtio',
               '--name', hostname,
               '--vcpus', vcpus,
               '--ram', 1024*ram,
               '--import',
               '--disk', (new_img + ',device=disk,bus=virtio,format=qcow2,cache=writeback'),
               '--noautoconsole']

        if vnc:
            cmd.extend(['--graphics', 'vnc,port=%s'%vnc])

        for x in persistent_images:
            cmd.extend(['--disk', '%s,bus=virtio,cache=writeback,format=%s'%(x[0],x[3])])

        os.system("ls -lh %s"%new_img)
        sh['chgrp', 'kvm', new_img]
        sh['chmod', 'g+rw', new_img]
        os.system("ls -lh %s"%new_img)

        log.info(run(cmd, maxtime=600))

        log.info("created new virtual machine in %s seconds -- now running", time.time()-t); t = time.time()

        ##########################################################################
        # - run until vm terminates or we receive term signal, undefined, destroy
        ##########################################################################
        while virsh('domstate', hostname) == 'running':
             # TODO: this is polling, which violates an axiom.  We absolutely
             # must rewrite this to be event driven!!!?
            time.sleep(1)
    except Exception, e:
        log.info("error creating virtual machine -- %s"%e)
Ejemplo n.º 6
0
def virsh(command, name):
    return run(['virsh', '--connect', 'qemu:///%s'%qemu, command, name], verbose=False, maxtime=600).strip()
Ejemplo n.º 7
0
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################



import os, sys, time
sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],'..'))
from admin import run


# 1. Figure out what the newest lxc container is whose name starts with base
prev = [x for x in sorted(run(['lxc-ls']).split()) if x.startswith('base')][-1]
print "Last container:", prev

next = time.strftime("base-%Y-%m-%d-%H%M")

print "New container:", next
run(["lxc-clone", "-s", "-B", "overlayfs", "-o", prev, "-n", next])

print "Now running"
run(["lxc-start", "-d", "-n", next])
time.sleep(1)

while True:
    ip_address = run(["lxc-ls","-1","--fancy", next]).splitlines()[-1].split()[2]
    if ip_address != '-':
        print "IP address:",ip_address
Ejemplo n.º 8
0
def run_lxc(ip_address, hostname, base='base', project=None):
    if len(hostname.split()) != 1 or not hostname.strip():
        raise ValueError("hostname must not have whitespace")

    # If the container already exists, exit with an error
    if run(['lxc-ls', hostname]).strip():
        raise RuntimeError("there is already a container %s"%hostname)

    def clean(*args):
        return

    try:
        ephemeral_tinc_key = False

        # Create the ephemeral container

        run(["lxc-clone", "-s", "-B", "overlayfs", "-o", base, "-n", hostname])

        path = os.path.join("/var/lib/lxc/", hostname)
        root = os.path.join(path, "delta0")
        tinc_path = os.path.join(root, 'etc/tinc/smc')
        if not os.path.exists(path):
            raise RuntimeError("error creating lxc container -- missing files")

        ################################################################
        # Configure the tinc network:
        #   - create all the relevant files in delta0/etc/tinc
        tincname = hostname.replace('-','_')
        vmhost_tincname = socket.gethostname().replace('-','_')

        os.makedirs(os.path.join(tinc_path,'hosts'))
        shutil.copyfile(os.path.join("/etc/tinc/hosts/",vmhost_tincname), os.path.join(tinc_path,'hosts',vmhost_tincname))

        open(os.path.join(tinc_path, 'tinc-up'),'w').write(
            "#!/bin/sh\nifconfig $INTERFACE %s netmask 255.192.0.0"%ip_address)
        open(os.path.join(tinc_path, 'tinc.conf'),'w').write(
            "Name = %s\nConnectTo = %s"%(tincname, vmhost_tincname))

        rsa_key_priv = os.path.join(tinc_path, 'rsa_key.priv')
        rsa_key_pub = os.path.join(tinc_path, 'hosts', tincname)
        run(["tincd", "-K", "-c", tinc_path])

        host_file = os.path.join(tinc_path, 'hosts', tincname)
        public_key = open(rsa_key_pub).read().strip()
        open(host_file,'w').write("Subnet = %s/32\n%s"%(ip_address, public_key))
        # put the tinc public key in host config, so that the vm can connect to host.
        ephemeral_tinc_key = os.path.join("/etc/tinc/hosts/", tincname)
        shutil.copyfile(host_file, os.path.join("/etc/tinc/hosts/", tincname))

        os.makedirs(os.path.join(root, 'dev/net'))
        run(["mknod", os.path.join(root, 'dev/net/tun'), "c", "10", "200"])
        run(['chmod', 'a+x', os.path.join(tinc_path, 'tinc-up')])

        f = open(os.path.join(root, 'etc/tinc/nets.boot'),'w')
        f.write('smc')
        f.close()

        ################################################################
        # project user
        if project:
            log.info("bind mounting the project files to their home directory")
            fstab_line = "%s home/project none bind 0 0\n"%os.path.abspath(project)
            fstab = os.path.join(path, "fstab")
            v = open(fstab).readlines()
            v.append(fstab_line)
            log.info("remove salvus from fstab and disable salvus login")
            v = [x for x in v if 'home/salvus' not in x]
            open(fstab,'w').write(''.join(v))

        # Start the container
        s = ["lxc-start", "-d", "-n", hostname]
        run(s, maxtime=10)

        def clean(*args):
            try:
                run(['lxc-destroy', '-f', '-n', hostname])
            finally:
                if ephemeral_tinc_key and os.path.exists(ephemeral_tinc_key):
                    os.unlink(ephemeral_tinc_key)
            sys.exit(0)

        signal.signal(signal.SIGTERM, clean)

        # Wait for the container to stop
        run(['lxc-wait', '-n', hostname, '-s', 'STOPPED'], maxtime=0)
        log.info("container has stopped")
    finally:
        log.info("stop and remove the container.")
        clean()
Ejemplo n.º 9
0
    parser.add_argument('--base', dest='base', type=str, default="",
                        help="template container on which to base this container (default: the most recent base container)")

    args = parser.parse_args()

    if not args.hostname and args.project:
        args.hostname = 'project-' + os.path.split(args.project)[-1]

    if args.ip_address.count('.') != 3 or not args.ip_address.startswith('10.'):
        sys.stderr.write("%s: invalid ip address %s"%(sys.argv[0], args.ip_address))
        sys.exit(1)

    args.hostname = args.hostname if args.hostname else args.ip_address.replace('.','dot')

    if not args.base:
        args.base = [x for x in sorted(run(['lxc-ls']).split()) if x.startswith('base')][-1]

    if args.daemon:
        if not args.logfile:
            args.logfile = args.hostname + '.log'
        if not args.pidfile:
            args.pidfile = args.hostname + '.pid'

    if args.logfile:
        args.logfile = os.path.abspath(args.logfile)
    if args.pidfile:
        args.pidfile = os.path.abspath(args.pidfile)

    def main():
        global log
Ejemplo n.º 10
0
Archivo: vm.py Proyecto: wetlife/cloud
def run_kvm(ip_address, hostname, stop, vcpus, ram, vnc, disk, base, fstab):
    #################################
    # create the copy-on-write image
    #################################
    t = time.time()
    img_path = os.path.join(os.environ['HOME'], 'vm', 'images')
    base_img_path = os.path.join(img_path, 'base3')
    if not os.path.exists(base_img_path):
        os.makedirs(base_img_path)
    persistent_img_path = os.path.join(img_path, 'persistent')
    if not os.path.exists(persistent_img_path):
        os.makedirs(persistent_img_path)
    temporary_img_path = os.path.join(img_path, 'temporary')
    if not os.path.exists(temporary_img_path):
        os.makedirs(temporary_img_path)
    new_img = os.path.join(temporary_img_path, hostname + '.img')

    tincname = hostname.replace('-', '_')

    if stop:
        log.info("stopping ephemeral vm '%s'" % hostname)
        try:
            log.info("virsh shutdown '%s'" % hostname)
            log.info(virsh('shutdown', hostname))
        except:
            pass
        try:
            log.info("virsh destroy '%s'" % hostname)
            log.info(virsh('destroy', hostname))
        except:
            pass
        try:
            log.info("virsh undefine '%s'" % hostname)
            log.info(virsh('undefine', hostname))
        except:
            pass
        try:
            path = os.path.join(conf_path, 'tinc_hosts', tincname)
            log.info("remove tinc public key '%s'" % path)
            os.unlink(path)
        except:
            pass
        try:
            log.info("remove ephemeral image '%s'" % new_img)
            os.unlink(new_img)
        except:
            pass
        return

    if os.path.exists(new_img):
        raise RuntimeError(
            "the image '%s' already exists; maybe the virtual machine is already running?"
            % new_img)

    if not base.endswith('.img'): base += '.img'
    base_img = os.path.join(base_img_path, base)

    try:
        #################################
        # create disk images
        #################################
        tmp_path = tempfile.mkdtemp()  # put here so finally below will work.

        # Transient image based on our template
        sh['qemu-img', 'create', '-b', base_img, '-f', 'qcow2', new_img]
        log.info("created %s in %s seconds", new_img,
                 time.time() - t)
        t = time.time()
        # Persistent image(s)
        persistent_images = []
        for name, size, fstype, format in disk:
            if name.startswith('/dev'):
                # NOTE: size="mount point" for raw disk images
                persistent_images.append((name, size, fstype, format))
            else:
                # TODO: this functionality will be removed as soon as I move *all* UW vm's to use zvol's.
                persistent_images.append(
                    (os.path.join(persistent_img_path,
                                  '%s-%s.img' % (hostname, name)),
                     '/mnt/' + name, fstype, format))
                img = persistent_images[-1][0]
                if not os.path.exists(img):
                    os.chdir(persistent_img_path)
                    temp = None
                    try:
                        # Unfortunately, guestfish doesn't support xfs.
                        sh['qemu-img', 'create', '-f', format, img,
                           '%sG' % size]
                        # See salvus/salvus/scripts/salvus_nbd_format.py
                        if fstype != 'none':
                            log.info(
                                "WARNING: formatting filesystem can take a long time..."
                            )
                            run([
                                'sudo', '/usr/local/bin/salvus_nbd_format.py',
                                fstype, img
                            ],
                                maxtime=1800)
                        sh['chgrp', 'kvm', img]
                        sh['chmod', 'g+rw', img]
                    finally:
                        if temp is not None:
                            shutil.rmtree(temp)
                            if os.path.exists('test1.img'):
                                os.unlink('test1.img')
                else:
                    pass
                    # TODO: else -- if too small, enlarge image if possible

        #################################
        # configure the vm's image
        #################################
        # - mount the image in a temp directory
        vmhost_tincname = socket.gethostname().replace('-', '_')
        try:
            run(['guestmount', '-i', '-a', new_img, '--rw', tmp_path],
                maxtime=600)

            #### hostname ####
            hostname_file = os.path.join(tmp_path, 'etc/hostname')
            if not os.path.exists(hostname_file):
                raise RuntimeError(
                    "missing /etc/hostname in the VM image; probably the guestmount command is not working, and the fix is probably to type 'sudo chmod a+r /boot/vmlinuz-*; sudo chmod a+rw /dev/fuse'"
                )

            os.unlink(hostname_file)
            open(hostname_file, 'w').write(hostname)
            hosts_file = os.path.join(tmp_path, 'etc/hosts')
            hosts = open(hosts_file).read()
            os.unlink(hosts_file)
            open(hosts_file,
                 'w').write("%s\n127.0.1.1  %s\n" % (hosts, hostname))

            #### tinc vpn ####
            tinc_path = os.path.join(
                tmp_path, 'home/salvus/salvus/salvus/data/local/etc/tinc/')
            open(os.path.join(tinc_path, 'tinc-up'), 'w').write(
                "#!/bin/sh\nifconfig $INTERFACE %s netmask 255.192.0.0 txqueuelen 10000"
                % ip_address)
            open(os.path.join(tinc_path, 'tinc.conf'),
                 'w').write("Name = %s\nKeyExpire = 2592000\nConnectTo = %s" %
                            (tincname, vmhost_tincname))
            rsa_key_priv = os.path.join(tinc_path, 'rsa_key.priv')
            rsa_key_pub = os.path.join(tinc_path, 'hosts', tincname)
            if os.path.exists(rsa_key_priv): os.unlink(rsa_key_priv)
            if os.path.exists(rsa_key_pub): os.unlink(rsa_key_pub)
            sh['tincd', '--config', tinc_path, '-K']
            host_file = os.path.join(tinc_path, 'hosts', tincname)
            public_key = open(rsa_key_pub).read().strip()
            open(host_file, 'w').write(
                "TCPonly=yes\nCompression=10\nCipher = aes-128-cbc\nSubnet = %s/32\n%s"
                % (ip_address, public_key))
            # put the tinc public key in our local db, so that the vm can connect to host.
            shutil.copyfile(host_file,
                            os.path.join(conf_path, 'tinc_hosts', tincname))

            #### persisent disks ####
            fstab_file = os.path.join(tmp_path, 'etc/fstab')
            try:
                f = open(fstab_file, 'a')
                for i, x in enumerate(persistent_images):
                    if x[1] and x[2] not in [
                            'none', 'zfs'
                    ]:  # using defaults instead of nobootwait, since nobootwait causes trouble with firstboot.py
                        f.write("\n/dev/vd%s1   %s   %s   defaults  0   2\n" %
                                (chr(98 + i), x[1], x[2]))
                        mnt_point = os.path.join(tmp_path, x[1].lstrip('/'))
                        os.makedirs(mnt_point)
                f.write('\n' + fstab + '\n')
                for x in fstab.splitlines():
                    v = x.split()
                    if not x.lstrip().startswith('#') and len(v) >= 2:
                        mnt_point = os.path.join(tmp_path, v[1].lstrip('/'))
                        os.makedirs(mnt_point)

            finally:
                f.close()

        finally:
            # - unmount image and remove tmp_path
            sh['fusermount', '-u', tmp_path]
    finally:
        shutil.rmtree(tmp_path)

    log.info("configured image in %s seconds",
             time.time() - t)
    t = time.time()

    #################################
    # create and start the vm itself
    #################################
    try:
        cmd = [
            'virt-install',
            '--connect',
            'qemu:///%s' % qemu,
            #'--cpu', 'core2duo', # definitely fails
            #'--cpu', 'core2duo,+wdt,+skinit,+osvw,+3dnowprefetch,+misalignsse,+sse4a,+abm,+cr8legacy,+extapic,+svm,+cmp_legacy,+lahf_lm,+rdtscp,+pdpe1gb,+fxsr_opt,+mmxext,+aes,+popcnt,+sse4.2,+sse4.1,+cx16,+ht',  # definitely does NOT work
            '--cpu',
            'host',  # definitely fails
            '--network',
            'network:default,model=virtio',
            '--name',
            hostname,
            '--vcpus',
            vcpus,
            '--ram',
            1024 * ram,
            '--import',
            '--disk',
            (new_img + ',device=disk,bus=virtio,format=qcow2,cache=writeback'),
            '--noautoconsole'
        ]

        if vnc:
            cmd.extend(['--graphics', 'vnc,port=%s' % vnc])

        for x in persistent_images:
            cmd.extend([
                '--disk',
                '%s,bus=virtio,cache=writeback,format=%s' % (x[0], x[3])
            ])

        os.system("ls -lh %s" % new_img)
        sh['chgrp', 'kvm', new_img]
        sh['chmod', 'g+rw', new_img]
        os.system("ls -lh %s" % new_img)

        log.info(run(cmd, maxtime=600))

        log.info("created new virtual machine in %s seconds -- now running",
                 time.time() - t)
        t = time.time()

        ##########################################################################
        # - run until vm terminates or we receive term signal, undefined, destroy
        ##########################################################################
        while virsh('domstate', hostname) == 'running':
            # TODO: this is polling, which violates an axiom.  We absolutely
            # must rewrite this to be event driven!!!?
            time.sleep(1)
    except Exception, e:
        log.info("error creating virtual machine -- %s" % e)
Ejemplo n.º 11
0
Archivo: vm.py Proyecto: wetlife/cloud
def virsh(command, name):
    return run(['virsh', '--connect',
                'qemu:///%s' % qemu, command, name],
               verbose=False,
               maxtime=600).strip()
Ejemplo n.º 12
0
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################



import os, sys, time
sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],'..'))
from admin import run


# 1. Figure out what the newest lxc container is whose name starts with base
prev = [x for x in sorted(run(['lxc-ls']).split()) if x.startswith('base')][-1]
print "Last container:", prev

next = time.strftime("base-%Y-%m-%d-%H%M")

print "New container:", next
run(["lxc-clone", "-s", "-B", "overlayfs", "-o", prev, "-n", next])

print "Now running"
run(["lxc-start", "-d", "-n", next])
time.sleep(1)

while True:
    ip_address = run(["lxc-ls","-1","--fancy", next]).splitlines()[-1].split()[2]
    if ip_address != '-':
        print "IP address:",ip_address
Ejemplo n.º 13
0
def main():
    while True:
        choice=input("请选择\n1:管理员\n2:学生\n3.退出\n>>>>>")
        if choice=='1':admin.run()
        elif choice=='2':stu.run()
        elif choice=='3':exit()
Ejemplo n.º 14
0
def run_lxc(ip_address, hostname, base='base', project=None):
    if len(hostname.split()) != 1 or not hostname.strip():
        raise ValueError("hostname must not have whitespace")

    # If the container already exists, exit with an error
    if run(['lxc-ls', hostname]).strip():
        raise RuntimeError("there is already a container %s" % hostname)

    def clean(*args):
        return

    try:
        ephemeral_tinc_key = False

        # Create the ephemeral container

        run(["lxc-clone", "-s", "-B", "overlayfs", "-o", base, "-n", hostname])

        path = os.path.join("/var/lib/lxc/", hostname)
        root = os.path.join(path, "delta0")
        tinc_path = os.path.join(root, 'etc/tinc/smc')
        if not os.path.exists(path):
            raise RuntimeError("error creating lxc container -- missing files")

        ################################################################
        # Configure the tinc network:
        #   - create all the relevant files in delta0/etc/tinc
        tincname = hostname.replace('-', '_')
        vmhost_tincname = socket.gethostname().replace('-', '_')

        os.makedirs(os.path.join(tinc_path, 'hosts'))
        shutil.copyfile(os.path.join("/etc/tinc/hosts/", vmhost_tincname),
                        os.path.join(tinc_path, 'hosts', vmhost_tincname))

        open(os.path.join(tinc_path, 'tinc-up'), 'w').write(
            "#!/bin/sh\nifconfig $INTERFACE %s netmask 255.192.0.0" %
            ip_address)
        open(os.path.join(tinc_path, 'tinc.conf'), 'w').write(
            "Name = %s\nConnectTo = %s" % (tincname, vmhost_tincname))

        rsa_key_priv = os.path.join(tinc_path, 'rsa_key.priv')
        rsa_key_pub = os.path.join(tinc_path, 'hosts', tincname)
        run(["tincd", "-K", "-c", tinc_path])

        host_file = os.path.join(tinc_path, 'hosts', tincname)
        public_key = open(rsa_key_pub).read().strip()
        open(host_file,
             'w').write("Subnet = %s/32\n%s" % (ip_address, public_key))
        # put the tinc public key in host config, so that the vm can connect to host.
        ephemeral_tinc_key = os.path.join("/etc/tinc/hosts/", tincname)
        shutil.copyfile(host_file, os.path.join("/etc/tinc/hosts/", tincname))

        os.makedirs(os.path.join(root, 'dev/net'))
        run(["mknod", os.path.join(root, 'dev/net/tun'), "c", "10", "200"])
        run(['chmod', 'a+x', os.path.join(tinc_path, 'tinc-up')])

        f = open(os.path.join(root, 'etc/tinc/nets.boot'), 'w')
        f.write('smc')
        f.close()

        ################################################################
        # project user
        if project:
            log.info("bind mounting the project files to their home directory")
            fstab_line = "%s home/project none bind 0 0\n" % os.path.abspath(
                project)
            fstab = os.path.join(path, "fstab")
            v = open(fstab).readlines()
            v.append(fstab_line)
            log.info("remove salvus from fstab and disable salvus login")
            v = [x for x in v if 'home/salvus' not in x]
            open(fstab, 'w').write(''.join(v))

        # Start the container
        s = ["lxc-start", "-d", "-n", hostname]
        run(s, maxtime=10)

        def clean(*args):
            try:
                run(['lxc-destroy', '-f', '-n', hostname])
            finally:
                if ephemeral_tinc_key and os.path.exists(ephemeral_tinc_key):
                    os.unlink(ephemeral_tinc_key)
            sys.exit(0)

        signal.signal(signal.SIGTERM, clean)

        # Wait for the container to stop
        run(['lxc-wait', '-n', hostname, '-s', 'STOPPED'], maxtime=0)
        log.info("container has stopped")
    finally:
        log.info("stop and remove the container.")
        clean()
Ejemplo n.º 15
0
    if not args.hostname and args.project:
        args.hostname = 'project-' + os.path.split(args.project)[-1]

    if args.ip_address.count('.') != 3 or not args.ip_address.startswith(
            '10.'):
        sys.stderr.write("%s: invalid ip address %s" %
                         (sys.argv[0], args.ip_address))
        sys.exit(1)

    args.hostname = args.hostname if args.hostname else args.ip_address.replace(
        '.', 'dot')

    if not args.base:
        args.base = [
            x for x in sorted(run(['lxc-ls']).split()) if x.startswith('base')
        ][-1]

    if args.daemon:
        if not args.logfile:
            args.logfile = args.hostname + '.log'
        if not args.pidfile:
            args.pidfile = args.hostname + '.pid'

    if args.logfile:
        args.logfile = os.path.abspath(args.logfile)
    if args.pidfile:
        args.pidfile = os.path.abspath(args.pidfile)

    def main():
        global log