Diff
Not logged in

Differences From Artifact [55b3a303d0]:

To Artifact [fff489ba36]:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python
""" vws - script to control QEMU/KVM virtual workstations """
# pylint: disable=bad-builtin
from ConfigParser import ConfigParser
from argparse import ArgumentParser, Namespace
import fcntl
import socket, select
import errno
import re
import os, sys, time, os.path
import pwd

VERSION = 0.4
def find_vm(name):
    """ Search and return VM directory """
    search_path = [os.path.join(pwd.getpwuid(os.getuid()).pw_dir, "VWs"),
                   config.get("directories", "SharedVMs"),
                   config.get("directories", "AutostartVMs")]
    for dirname in search_path:
        if not os.access(dirname, os.X_OK):












|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python
""" vws - script to control QEMU/KVM virtual workstations """
# pylint: disable=bad-builtin
from ConfigParser import ConfigParser
from argparse import ArgumentParser, Namespace
import fcntl
import socket, select
import errno
import re
import os, sys, time, os.path
import pwd

VERSION = 0.5
def find_vm(name):
    """ Search and return VM directory """
    search_path = [os.path.join(pwd.getpwuid(os.getuid()).pw_dir, "VWs"),
                   config.get("directories", "SharedVMs"),
                   config.get("directories", "AutostartVMs")]
    for dirname in search_path:
        if not os.access(dirname, os.X_OK):
177
178
179
180
181
182
183


184
185
186
187
188
189
190
        arg = ""
        if options.cdrom:
            arg = " -cdrom " + os.path.abspath(options.cdrom[0])
        if options.snapshot:
            arg = arg+" -snapshot"
        if options.args:
            arg = arg + " " + "".join(options.args)


        print arg
        cwd = os.getcwd()
        os.chdir(options.dir)
        # Check for snapshot
        nxt = 0
        snapshot_id = None
        with os.popen("qemu-img info \"%s\"" %







>
>







177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        arg = ""
        if options.cdrom:
            arg = " -cdrom " + os.path.abspath(options.cdrom[0])
        if options.snapshot:
            arg = arg+" -snapshot"
        if options.args:
            arg = arg + " " + "".join(options.args)
        if options.password:
            os.environ["SPICE_PASSWORD"]=options.password
        print arg
        cwd = os.getcwd()
        os.chdir(options.dir)
        # Check for snapshot
        nxt = 0
        snapshot_id = None
        with os.popen("qemu-img info \"%s\"" %
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
        os.system("./start%s" % arg)
        os.chdir(cwd)
        time.sleep(2)
        options.sock = connect_vm(options.dir)
        if snapshot_id:
            send_command(options.sock, "delvm " + snapshot_id)
    else:
        if options.snapshot or options.args:
            print >>sys.stderr, ("Cannot change qemu options. " +
                                 "VM is already running")
        if options.cdrom:
            options.file = options.cdrom[0]
            options.id = None
            cmd_cdrom(options)
    uri = spiceurl(options.sock)







|







205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        os.system("./start%s" % arg)
        os.chdir(cwd)
        time.sleep(2)
        options.sock = connect_vm(options.dir)
        if snapshot_id:
            send_command(options.sock, "delvm " + snapshot_id)
    else:
        if options.snapshot or options.args or options.password:
            print >>sys.stderr, ("Cannot change qemu options. " +
                                 "VM is already running")
        if options.cdrom:
            options.file = options.cdrom[0]
            options.id = None
            cmd_cdrom(options)
    uri = spiceurl(options.sock)
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
"""

def cmd_create(parsed_args):
    """ vws create - create new VM """
    BADSIZE = "Invalid size of %s specifed %s. Should have K, M or G suffix"
    global TEMPLATE
    if not parsed_args.image and not validate_size(parsed_args.size):
        print >>sys.stderr, BADSIZE % ("disk", parsed_args.size)
        sys.exit(1)
    if not validate_size(parsed_args.mem):
        print >>sys.stderr, BADSIZE % ("memory", parsed_args.size)
        sys.exit(1)
    drivename = "drive0.qcow2"
    options = {'qemubinary':'qemu-system-x86_64',
               "accel":"-enable-kvm",
               "memory":"1024M",
               "vga":'qxl',
               "drive":"-drive media=disk,index=0,if={interface},file={image}",
               "cdrom":"-drive media=cdrom,index=2,if=ide",
               "sound":"-soundhw hda",
               "group":config.get("permissions","vm_group"),
               "usb":"-usb",
               "rtc":""}
    macaddr = ":".join(["%02x" % ord(x) for x in  chr(0x52) + os.urandom(5)])
    if parsed_args.shared:
        machinedir = os.path.join(config.get("directories", "SharedVMs"),
                                  parsed_args.machine)
        dirmode = 0775
    else:
        machinedir = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, "VWs",
                                  parsed_args.machine)
        dirmode = 0775

    if parsed_args.net != 'user':
        bridges = list_bridges()
        if not parsed_args.net in bridges:
            print >>sys.stderr, ("No such bridge %s. Available ones %s" %
                                 (parsed_args.net, ", ".join(bridges)))
            sys.exit(1)
        options["net"] = ("-net nic,macaddr=%s -net bridge,br=%s" %
                          (macaddr, parsed_args.net))
    else:
        options["net"] = "-net nic,macaddr=%s -net user" % (macaddr,)
    options["qemubinary"] = 'qemu-system-' + parsed_args.arch
    options["vga"] = parsed_args.vga
    NOACCEL = "KVM acceleration disabled due to "







|
<

|
<




















|



|
|
<







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
"""

def cmd_create(parsed_args):
    """ vws create - create new VM """
    BADSIZE = "Invalid size of %s specifed %s. Should have K, M or G suffix"
    global TEMPLATE
    if not parsed_args.image and not validate_size(parsed_args.size):
        raise ValueError(BADSIZE % ("disk", parsed_args.size))

    if not validate_size(parsed_args.mem):
        raise ValueError(BADSIZE % ("memory", parsed_args.size))

    drivename = "drive0.qcow2"
    options = {'qemubinary':'qemu-system-x86_64',
               "accel":"-enable-kvm",
               "memory":"1024M",
               "vga":'qxl',
               "drive":"-drive media=disk,index=0,if={interface},file={image}",
               "cdrom":"-drive media=cdrom,index=2,if=ide",
               "sound":"-soundhw hda",
               "group":config.get("permissions","vm_group"),
               "usb":"-usb",
               "rtc":""}
    macaddr = ":".join(["%02x" % ord(x) for x in  chr(0x52) + os.urandom(5)])
    if parsed_args.shared:
        machinedir = os.path.join(config.get("directories", "SharedVMs"),
                                  parsed_args.machine)
        dirmode = 0775
    else:
        machinedir = os.path.join(pwd.getpwuid(os.getuid()).pw_dir, "VWs",
                                  parsed_args.machine)
        dirmode = 0775
   
    if parsed_args.net != 'user':
        bridges = list_bridges()
        if not parsed_args.net in bridges:
            raise ValueError("No such bridge %s. Available ones %s" %
                             (parsed_args.net, ", ".join(bridges)))

        options["net"] = ("-net nic,macaddr=%s -net bridge,br=%s" %
                          (macaddr, parsed_args.net))
    else:
        options["net"] = "-net nic,macaddr=%s -net user" % (macaddr,)
    options["qemubinary"] = 'qemu-system-' + parsed_args.arch
    options["vga"] = parsed_args.vga
    NOACCEL = "KVM acceleration disabled due to "
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759

760
761
762
763
764
765
766

    options["memory"] = parsed_args.mem
    if parsed_args.localtime:
        options["rtc"] = "-rtc base=localtime,clock=host \\\n"

    if os.path.exists(machinedir):
        if os.path.exists(os.path.join(machinedir, "start")):
            print >> sys.stderr, ("Virtual Worstation %s already exists" %
                                  parsed_args.machine)
        else:
            print >> sys.stderr, ("Cannot create VW directory, " +
                                  "something on the way")
        sys.exit(1)
    #  Creating directory for VM
    os.makedirs(machinedir, dirmode)

    if parsed_args.shared:
        import grp
        gid=grp.getgrnam(config.get("permissions","vm_group")).gr_gid
        uid=os.getuid() 
        os.chown(machinedir,uid,gid)
        if config.getboolean("permissions","setgid_vm"):  
            os.chmod(machinedir,02775)







|
|

|

<


>







744
745
746
747
748
749
750
751
752
753
754
755

756
757
758
759
760
761
762
763
764
765

    options["memory"] = parsed_args.mem
    if parsed_args.localtime:
        options["rtc"] = "-rtc base=localtime,clock=host \\\n"

    if os.path.exists(machinedir):
        if os.path.exists(os.path.join(machinedir, "start")):
            raise OSError("Virtual Worstation %s already exists" %
                           parsed_args.machine)
        else:
            raise OSError("Cannot create VW directory, " +
                                  "something on the way")

    #  Creating directory for VM
    os.makedirs(machinedir, dirmode)
    parsed_args.dir=machinedir
    if parsed_args.shared:
        import grp
        gid=grp.getgrnam(config.get("permissions","vm_group")).gr_gid
        uid=os.getuid() 
        os.chown(machinedir,uid,gid)
        if config.getboolean("permissions","setgid_vm"):  
            os.chmod(machinedir,02775)
871
872
873
874
875
876
877


878
879
880
881
882
883
884
               default=True, help='do not open console window')
p.add_argument('--cdrom', metavar='filename.iso', dest='cdrom', nargs=1,
               help='connect specified iso image to VMs cdrom on start')
p.add_argument('--args', metavar='string', dest='args', nargs=1, default="",
               help="Specify extra QEMU options")
p.add_argument("--snapshot", action='store_const', const=True, default=False,
               help="Run without modifying disk image")


p = new_command(cmds, 'stop', help='Shut down virtual machine',
                description="Terminate the VW, gracefully or ungracefully")
p.add_argument('--hard', help='Power off immediately', action='store_const',
               dest='hard', const=True, default=False)
new_command(cmds, 'save', help='Save VW state and stop emulation',
            description="Save VW state and stop emulation")
new_command(cmds, 'reset', help='Reboot a guest OS',







>
>







870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
               default=True, help='do not open console window')
p.add_argument('--cdrom', metavar='filename.iso', dest='cdrom', nargs=1,
               help='connect specified iso image to VMs cdrom on start')
p.add_argument('--args', metavar='string', dest='args', nargs=1, default="",
               help="Specify extra QEMU options")
p.add_argument("--snapshot", action='store_const', const=True, default=False,
               help="Run without modifying disk image")
p.add_argument("--password", metavar='string', dest='password',nargs=1,
                default=None, help="Set password for remote spice connection")
p = new_command(cmds, 'stop', help='Shut down virtual machine',
                description="Terminate the VW, gracefully or ungracefully")
p.add_argument('--hard', help='Power off immediately', action='store_const',
               dest='hard', const=True, default=False)
new_command(cmds, 'save', help='Save VW state and stop emulation',
            description="Save VW state and stop emulation")
new_command(cmds, 'reset', help='Reboot a guest OS',
960
961
962
963
964
965
966

967






968
969
970
971
972
973
974
p = new_command(cmds, 'spiceuri', help='Output spice URI of machine')

parsed_args = args.parse_args(sys.argv[1:])

os.umask(002)
# Create command is totally different, so it is handled separately
if parsed_args.command == 'create':

    cmd_create(parsed_args)






    sys.exit(0)

funcname = "cmd_" + parsed_args.command
if hasattr(parsed_args, "subcommand"):
    funcname += "_" + parsed_args.subcommand
try:
    func = globals()[funcname]







>
|
>
>
>
>
>
>







961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
p = new_command(cmds, 'spiceuri', help='Output spice URI of machine')

parsed_args = args.parse_args(sys.argv[1:])

os.umask(002)
# Create command is totally different, so it is handled separately
if parsed_args.command == 'create':
    try:
        cmd_create(parsed_args)
    except Exception as e:
        print >>sys.stderr,e.message
        if hasattr(parsed_args,"dir"):
            import shutil
            shutil.rmtree(parsed_args.dir)
            sys.exit(1)
    sys.exit(0)

funcname = "cmd_" + parsed_args.command
if hasattr(parsed_args, "subcommand"):
    funcname += "_" + parsed_args.subcommand
try:
    func = globals()[funcname]