Пример #1
0
def exec_duplicate(src, dest, hostname):
    s = system.getSystem()
    with gui.progressbar.SyncedProgressBar(gui.res.string_cloning) as pb:
        try:
            with s.openCancellableProcessForInput(["xfs_copy", src, dest]) as xfs_copy:
                nbr = s.getNonblockingReader(xfs_copy.stdout)
                output = ""
                percentage_pattern = re.compile('[0-9]{1,3}%')
                str = nbr.read()
                while str != "":
                    pb.yieldFrame()
                    if str != None: 
                        output += str
                        progress = float(percentage_pattern.findall(output)[-1][0:-1]) / 100.0
                        pb.setProgress(progress)
                    str = nbr.read()
        except system.ProcessKilled:
            pass # killed is proper result

        with s.temporaryMount(dest, None, "inode32") as tmpdir:
            # growfsする
            subprocess.Popen("xfs_growfs %s" % tmpdir, shell=True, close_fds=True).wait()
            # ホスト名をつける
            cli_import.set_hostname(tmpdir, hostname)
            # VAのメタデータを得る
            metadata = system.get_va_metadata(dest, tmpdir)
Пример #2
0
def getVirtualApplianceByCode():
    code = dialogbox.inputbox.TextInputBox(gui.res.string_virtual_appliance_code, "", 5, 32, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").execute()
    if code == None: return None
    json_url = "http://goo.gl/" + code # e.g. DoIX3

    try:
        with dialogbox.messagebox.open(gui.res.string_code_check):
            rst = http_client.nonblockHttpGet(json_url)
            va = json.loads(rst)
            for key in ["id", "title"]: 
                if not key in va: raise ValueError("Invalid data")
    except ValueError:
        dialogbox.messagebox.execute(gui.res.string_code_not_correct, None, gui.res.caution_sign)
        return None
    except http_client.Cancelled:
        dialogbox.messagebox.execute(string_cancelled)
        return None
    except http_client.CurlException as e:
        dialogbox.messagebox.execute(gui.res.string_comm_error % (e.getError(), e.getURL()), None, gui.res.caution_sign)
        return None

    # architecture check
    required_arch = va["arch"] if "arch" in va else "i686"
    supported_arch = {"i686":["i686"], "x86_64":["i686", "x86_64"]}
    s = system.getSystem()
    arch = s.getArchitectureString()
    if arch not in supported_arch:
        dialogbox.messagebox.execute(gui.res.string_domain_sys_error % arch, None, gui.res.caution_sign)
        return None
    if required_arch not in supported_arch[arch]:
        dialogbox.messagebox.execute(gui.res.string_domain_support_error % (required_arch, arch), None, gui.res.caution_sign)
        return None

    return va
Пример #3
0
def exec_duplicate(src, dest, hostname):
    s = system.getSystem()
    with gui.progressbar.SyncedProgressBar(gui.res.string_cloning) as pb:
        try:
            with s.openCancellableProcessForInput(["xfs_copy", src,
                                                   dest]) as xfs_copy:
                nbr = s.getNonblockingReader(xfs_copy.stdout)
                output = ""
                percentage_pattern = re.compile('[0-9]{1,3}%')
                str = nbr.read()
                while str != "":
                    pb.yieldFrame()
                    if str != None:
                        output += str
                        progress = float(
                            percentage_pattern.findall(output)[-1]
                            [0:-1]) / 100.0
                        pb.setProgress(progress)
                    str = nbr.read()
        except system.ProcessKilled:
            pass  # killed is proper result

        with s.temporaryMount(dest, None, "inode32") as tmpdir:
            # growfsする
            subprocess.Popen("xfs_growfs %s" % tmpdir,
                             shell=True,
                             close_fds=True).wait()
            # ホスト名をつける
            cli_import.set_hostname(tmpdir, hostname)
            # VAのメタデータを得る
            metadata = system.get_va_metadata(dest, tmpdir)
Пример #4
0
def expand(domain):
    s = system.getSystem()
    device = domain["device"]
    orig_disk = domain.get("size") or s.determineLogicalVolumeSizeInGB(device)
    min_disk = int(orig_disk) + 1
    disk = gui.inputbox.TextInputBox(gui.res.string_new_size, min_disk, None, 1, 5, "0123456789").execute(gui.getDesktop())
    if disk == None: return False
    disk = int(disk)
    if disk < min_disk:
        gui.messagebox.execute(gui.res.string_size_desc, ["ok"], gui.res.color_dialog_negative)
        return False
    if min_disk < 2048 and disk >= 2048:
        gui.messagebox.execute(string_cant_across_2tb, ["ok"], gui.res.color_dialog_negative)
        return False

    if subprocess.Popen("lvextend -L %dG %s" % (disk, device), shell=True, close_fds=True).wait() != 0:
        gui.messagebox.execute(gui.res.string_free_space_desc, ["ok"], gui.res.color_dialog_negative)
        return False

    with s.temporaryMount(device, None, "inode32") as tmpdir:
        if subprocess.Popen("xfs_growfs %s" % tmpdir, shell=True, close_fds=True).wait() != 0:
            gui.messagebox.execute(gui.res.string_assign_desc, ["ok"], gui.res.color_dialog_negative)
            return False
    
    gui.messagebox.execute(gui.res.string_enhanced, ["ok"])
    return True
Пример #5
0
def nonblockingHttpHead(url):
    cmdline = ["curl", "--cacert", CA_CERT_FILE, "-sLfI", url]
    curl = subprocess.Popen(cmdline, shell=False, close_fds=True, stdout=subprocess.PIPE)
    s = system.getSystem()
    headers = {}
    nbr = s.getNonblockingReader(curl.stdout)
    r = nbr.readline()
    started = False
    while r != "":
        if r != None:
            if started:
                splitted = r.split(":", 1)
                if len(splitted) > 1:
                    name = splitted[0].strip().lower()
                    value = splitted[1].strip()
                    if name == "content-length":
                        value = int(value)
                    headers[name] = value
            else:
                line = r.strip()
                if line.startswith("HTTP/") and line.endswith(" 200 OK"):
                    started = True
        if gui.yieldFrame():  # キャンセルキーでTrueが返る
            curl.terminate()
            raise Cancelled()
        r = nbr.readline()
    curl.stdout.close()
    rst = curl.wait()
    if rst != 0:
        raise CurlException(rst, url)
    return headers
Пример #6
0
def nonblockingHttpHead(url):
    cmdline = ["curl", "--cacert", CA_CERT_FILE, "-sLfI", url]
    curl = subprocess.Popen(cmdline,
                            shell=False,
                            close_fds=True,
                            stdout=subprocess.PIPE)
    s = system.getSystem()
    headers = {}
    nbr = s.getNonblockingReader(curl.stdout)
    r = nbr.readline()
    started = False
    while r != "":
        if r != None:
            if started:
                splitted = r.split(':', 1)
                if len(splitted) > 1:
                    name = splitted[0].strip().lower()
                    value = splitted[1].strip()
                    if name == "content-length": value = int(value)
                    headers[name] = value
            else:
                line = r.strip()
                if line.startswith("HTTP/") and line.endswith(" 200 OK"):
                    started = True
        if gui.yieldFrame():  # キャンセルキーでTrueが返る
            curl.terminate()
            raise Cancelled()
        r = nbr.readline()
    curl.stdout.close()
    rst = curl.wait()
    if rst != 0: raise CurlException(rst, url)
    return headers
Пример #7
0
def init():
    s = system.getSystem()
    uname = os.uname()

    global kernel_version, kernel_arch, kernel_date, ipaddress, cpus, cpu_clock, support_hvm, canvas, vpn_ipaddress
    kernel_version = uname[2]
    kernel_arch = s.getArchitectureString()
    kernel_date_str = uname[3].replace('Darwin Kernel ', '').split()
    kernel_date = gui.res.string_kernel_date % (kernel_date_str[7 if len(kernel_date_str) > 7 else 6],{"Jan":1,"Feb":2,"Mar":3,"Apr":4,"May":5,"Jun":6,"Jul":7,"Aug":8,"Sep":9,"Oct":10,"Nov":11,"Dec":12}[kernel_date_str[3]],kernel_date_str[4])

    try:
        ipaddress = system.get_ip_address_which_reaches_default_gateway()
    except:
        pass # keep it None
    
    # CPU情報を得る
    xl_info = cli_info.run()
    cpus = xl_info.get("nr_cpus") or 0
    cpu_clock = xl_info.get("cpu_mhz") or 0
    xen_caps = xl_info.get("xen_caps")
    support_hvm = xen_caps is not None and "hvm-" in xen_caps

    canvas = pygame.Surface((400, 400), pygame.SRCALPHA, 32)
    vpn_ipaddress = None

    gui.res.register("status_panel", resource_loader.loadImage("status_panel.png"))
    gui.res.register("font_status_text", gui.res.font_system.getFont(18))

    global window
    window = Window()
Пример #8
0
def run(options, args):
    if len(args) < 1: raise cli.Error("Device name must be specified.")

    deviceName = args[0]
    snapshotSize = options.snapshot_size

    s = system.getSystem()
    with s.openProcessForInput("lsblk -nr -o MAJ:MIN,FSTYPE %s" % deviceName) as lsblk:
        line = lsblk.readline()
        if not line: raise cli.Error("Device '%s' doesn't exist or may not be a block device." % deviceName)
        splitted = line.split(" ")
        devNum = splitted[0]
        fstype = splitted[1].strip() if len(splitted) > 1 else None
        if fstype == "": fstype = None
    
    backupFunc = backupRaw if fstype is None else backupTar
    print >> sys.stderr, "Backup type:%s" % ("raw" if backupFunc == backupRaw else "tar")

    useSnapshot = (deviceName in (x.strip() for x in subprocess.check_output("lvs --noheadings -o lv_path --unquoted", shell=True, close_fds=True).split('\n') if x != "") and snapshotSize > 0)

    if useSnapshot:
        with s.openSnapshot(deviceName, snapshotSize) as snapshot:
            print >> sys.stderr, "Using snapshot:%s" % snapshot
            backupFunc(snapshot)
    else:
        backupFunc(deviceName)

    print >>sys.stderr, "Done."
Пример #9
0
def vpn(domain):
    device = domain["device"]
    s = system.getSystem()
    try:
        with s.temporaryMount(device, None, "ro") as tmpdir:
            openvpn_binary = os.path.join(tmpdir, "/usr/sbin/openvpn")
            if os.path.isfile(openvpn_binary):
                subprocess.check_output(["/bin/egrep", "ENABLE_PASSWORD_SAVE|enable_password_save=yes", openvpn_binary]) 
    except:
        #traceback.print_exc(file=sys.stderr)
        dialogbox.messagebox.execute(gui.res.string_connection_desc, None, gui.res.caution_sign)
        return False

    fields = [{"id":"hostname", "label":gui.res.string_destination_host, "value":""},{"id":"id", "label":gui.res.string_con_id, "value":""}, {"id":"password", "label":gui.res.string_con_password, "value":"", "password":True}]
    while True:
        values = gui.propertybox.execute(gui.res.string_vpn_setting, fields)
        if values == None: return False
        if dialogbox.messagebox.execute(gui.res.string_setting_desc % (values["hostname"], values["id"]), dialogbox.DialogBox.OKCANCEL()) == "ok": break

    autostart_done = False
    try:
        with s.temporaryMount(device, None, "inode32") as tmpdir:
            with open("%s/etc/openvpn/openvpn.conf" % tmpdir, "w") as f:
                f.write("client\n")
                f.write("dev tun\n")
                f.write("remote %s\n" % values["hostname"])
                cert_filename = "/etc/ssl/certs/ca-bundle.crt"
                if not os.path.exists("%s%s" % (tmpdir, cert_filename)):
                    cert_filename = "/etc/ssl/certs/ca-certificates.crt"
                f.write("ca %s\n" % cert_filename)
                f.write("fragment 1300\n")
                f.write("mssfix\n")
                f.write("nobind\n")
                f.write("float\n")
                f.write("ping 60\n")
                f.write("auth-user-pass auth.txt\n")
            with open("%s/etc/openvpn/auth.txt" % tmpdir, "w") as f:
                f.write("%s\n%s\n" % (values["id"], values["password"]))
	    os.chmod("%s/etc/openvpn/auth.txt" % tmpdir, stat.S_IRUSR|stat.S_IWUSR)
            if os.path.isdir("%s/etc/runlevels/default" % tmpdir):
                if not os.path.lexists("%s/etc/runlevels/default/openvpn" % tmpdir):
                    os.symlink("/etc/init.d/openvpn", "%s/etc/runlevels/default/openvpn" % tmpdir)
                autostart_done = True
	    elif os.path.isdir("%s/etc/rc3.d" % tmpdir):
	    	if not os.path.lexists("%s/etc/rc3.d/S24openvpn" % tmpdir):
		    os.symlink("../init.d/openvpn", "%s/etc/rc3.d/S24openvpn" % tmpdir)
		autostart_done = True
            elif os.path.isdir("%s/etc/systemd/system/multi-user.target.wants" % tmpdir):
                if not os.path.lexists("%s/etc/systemd/system/multi-user.target.wants/openvpn.service" % tmpdir):
                    os.symlink("/usr/lib/systemd/system/[email protected]", "%s/etc/systemd/system/multi-user.target.wants/[email protected]" % tmpdir)
                autostart_done = True

    except Exception as e:
        dialogbox.messagebox.execute(gui.res.string_setting_fail % e.message, None, gui.res.caution_sign)
        return False

    autostart_msg = "" if autostart_done else gui.res.string_manually_start
    dialogbox.messagebox.execute(gui.res.string_vpn_vm_setting % (domain["name"], autostart_msg))
    return True
Пример #10
0
Файл: browse.py Проект: logan/iq
 def maybeExportPage(name, spec, require_full_page):
   if not spec:
     return
   if spec.offset < 0:
     return
   if require_full_page and len(quote_list) < page_spec.size:
     return
   if spec.reversed and not spec.start_value:
     return
   logging.info('latest quote: %s', system.getSystem().latest_quote)
   if (spec.reversed
       and spec.start_value
       and system.getSystem().latest_quote
       and spec.start_value >= system.getSystem().latest_quote):
     return
   logging.info('template should include link to page spec: %s', spec)
   setattr(self.template, name, spec)
Пример #11
0
def backupTar(deviceName):
    s = system.getSystem()
    with s.temporaryMount(deviceName, None, "ro") as tmpdir:
        cmd = "tar cvpf - -C %s ." % tmpdir 
        with s.openProcessForInput(cmd) as tar:
            buf = tar.read(1024)
            while buf != "":
                sys.stdout.write(buf)
                buf = tar.read(1024)
Пример #12
0
def show_progress(progress_bar, subprocess):
    s = system.getSystem()
    nbr = s.getNonblockingReader(subprocess.stdout)
    line = nbr.readline()
    while line != "":
        if line != None and re.match(r'^\d+/\d+$', line):
            (n, m) = map(lambda a: float(a), line.split('/'))
            progress_bar.setProgress(n / m if m > 0 else 0)
        gui.yieldFrame()
        line = nbr.readline()
Пример #13
0
def kexec_load_kernel(kernel, kernel_args = None, initrd = None):
    s = system.getSystem()
    cmdline = kexec_cmdline(kernel, kernel_args, initrd)
    with dialogbox.messagebox.open(gui.res.string_inst_start_) as pb:
        with s.openCancellableProcessForInput(cmdline) as kexec:
            nbr = s.getNonblockingReader(kexec.stdout)
            line = nbr.readline()
            while line != "":
                gui.yieldFrame()
                line = nbr.readline()
Пример #14
0
def show_progress(progress_bar, subprocess):
    s = system.getSystem()
    nbr = s.getNonblockingReader(subprocess.stdout)
    line = nbr.readline()
    while line != "":
        if line != None and re.match(r'^\d+/\d+$', line):
            (n, m) = map(lambda a: float(a), line.split('/'))
            progress_bar.setProgress(n / m if m > 0 else 0)
        gui.yieldFrame()
        line = nbr.readline()
Пример #15
0
def kexec_load_kernel(kernel, kernel_args=None, initrd=None):
    s = system.getSystem()
    cmdline = kexec_cmdline(kernel, kernel_args, initrd)
    with dialogbox.messagebox.open(gui.res.string_inst_start_) as pb:
        with s.openCancellableProcessForInput(cmdline) as kexec:
            nbr = s.getNonblockingReader(kexec.stdout)
            line = nbr.readline()
            while line != "":
                gui.yieldFrame()
                line = nbr.readline()
Пример #16
0
 def pre_hook():
   self.facebook = facebook.FacebookSupport(self)
   self.template.stability_level = str(system.getSystem().stability_level)
   self.template.current_version_id = os.environ.get('CURRENT_VERSION_ID')
   self.template.cache_stats = memcache.Client().get_stats()
   if self.account.trusted:
     self.template.delete_return_url = self.request.url
     self.template.draft_page = browse.PageSpecifier(mode='draft')
     self.template.my_page = browse.PageSpecifier(mode='recent',
                                                  account=self.account)
Пример #17
0
def src_block(src, dest, options):
    s = system.getSystem()
    block_size = s.getPhysicalSectorSize(src)
    cmdline = ["dd", "if=%s" % src, "bs=%d" % block_size]
    if dest: cmdline.append("of=%s" % dest)
    rsync = subprocess.Popen(cmdline)
    while True:
        try:
            return rsync.wait() == 0
        except KeyboardInterrupt:
            pass  # just to make sure subprocess is finished
Пример #18
0
def src_block(src, dest, options):
    s = system.getSystem()
    block_size = s.getPhysicalSectorSize(src)
    cmdline = ["dd", "if=%s" % src, "bs=%d" % block_size]
    if dest: cmdline.append("of=%s" % dest)
    rsync = subprocess.Popen(cmdline)
    while True:
        try:
            return rsync.wait() == 0
        except KeyboardInterrupt:
            pass # just to make sure subprocess is finished
Пример #19
0
def run_app(app):
    driver = pygame.display.get_driver()
    pygame.quit()

    s = system.getSystem()
    with s.temporaryMount(app["device"]) as tmpdir:
        with s.temporaryMount("/dev", "%s/dev" % (tmpdir), "bind"):
            with s.temporaryMount("/proc", "%s/proc" % (tmpdir), "bind"):
                cmdline = ("wb", "sandbox", "-r", tmpdir) if driver == "x11" else ("openvt", "-sw", "--", "wb", "sandbox", "-r", tmpdir)
                subprocess.Popen(cmdline, shell=False, close_fds=True).wait()

    wbui.restart()
Пример #20
0
def run(options, args):
    if len(args) < 1: raise cli.Error("Insufficient parameters.")

    vgname = args[0]
    s = system.getSystem()
    device = s.createLogicalVolume(vgname, "_WBDISKBENCH_", 1)
    try:
        print "Testing sequential write..."
        sequential_write(device)
        print "Testing sequential read..."
        sequential_read(device)
    finally:
        s.removeLogicalVolume(device)
Пример #21
0
 def isAdmin(self):
   if self.admin:
     return True
   if not self.trusted:
     return False
   sys = system.getSystem()
   if sys.owner:
     return False
   logging.info('Making %s owner and admin', self.name)
   sys.owner = self.name
   sys.put()
   self.admin = True
   self.put()
   return True
Пример #22
0
def run(options, args):
    if len(args) < 2: raise cli.Error("Insufficient parameters.")

    source = args[0]
    target = args[1]
    bufsize = options.bufsize * 1024
    exclude_from = options.exclude_from

    s = system.getSystem()

    if not s.isStreamSourceAvailable(source):
        raise cli.Error("Source file '%s' is not available." % source)
    if not os.path.isdir(target): raise cli.Error("Invalid target dir")

    extractor = generateExtractorBySuffix(source, target)
    if exclude_from != None:
        extractor.append("-X")
        extractor.append(exclude_from)

    i = 0
    tar = subprocess.Popen(extractor,
                           shell=False,
                           stdin=subprocess.PIPE,
                           close_fds=True)

    itstime = time.time()
    try:
        with s.openInputStream(source) as (src, size):
            buf = src.read(bufsize)
            i += len(buf)
            while buf != "":
                newtime = time.time()
                if newtime >= itstime + 0.01:
                    print "%d/%d" % (i, size)
                    sys.stdout.flush()
                    itstime = newtime
                tar.stdin.write(buf)
                buf = src.read(bufsize)
                i += len(buf)
            print "%d/%d" % (size, size)
            sys.stdout.flush()
    except KeyboardInterrupt:
        tar.terminate()
        tar.stdin.close()
        tar.wait()
        exit(130)

    tar.stdin.close()
    tar.wait()
Пример #23
0
def run(options, args):
    if len(args) < 1: raise cli.Error("Insufficient parameters.")

    src = args[0]
    dest = None if len(args) < 2 else args[1]

    s = system.getSystem()

    if not s.isBlockSpecial(src):
        raise cli.Error("Source must be a block device")

    if s.isLogicalVolume(src):
        return src_lv(src, dest, options)
    #else
    return src_block(src, dest, options)
Пример #24
0
def list_available_disks():
    useable_disks = []
    s = system.getSystem()
    with dialogbox.messagebox.open(string_searching_useable_disks):
        with s.openWbForInput("list_useable_disks") as list_useable_disks:
            nbr = s.getNonblockingReader(list_useable_disks.stdout)
            line = nbr.readline()
            while line != "":
                if line != None: 
                    cols = line.split('\t')
	            useable_disks.append({"logicalname":cols[0],"size":cols[1],"product":cols[2],"sectorSize":int(cols[3])})
                gui.yieldFrame()
                line = nbr.readline()

    return useable_disks
Пример #25
0
def run(options, args):
    if len(args) < 1: raise cli.Error("Insufficient parameters.")

    src = args[0]
    dest = None if len(args) < 2 else args[1]

    s = system.getSystem()

    if not s.isBlockSpecial(src):
        raise cli.Error("Source must be a block device")

    if s.isLogicalVolume(src):
        return src_lv(src, dest, options)
    #else
    return src_block(src, dest, options)
Пример #26
0
def rescue(source_device, arch):
    if gui.messagebox.execute(gui.res.string_installer_tools_rescue_mode % (arch), ["ok", "cancel"]) != "ok": return False

    try:
        s= system.getSystem()
        with s.temporaryMount(source_device, None, "ro") as sourceDir:
            kernel = "%s/boot/vmlinuz.%d" % (sourceDir, arch)
            kernel_args = "video=uvesafb:mtrr:3,ywrap,1024x768-32 logo.nologo"
            initrd = "%s/boot/rescue.img" % (sourceDir)
            kexec_load_kernel(kernel, kernel_args, initrd)
        pygame.quit()
        os.execv("/usr/sbin/kexec", ("/usr/sbin/kexec", "-e"))
    except Exception, e:
        traceback.print_exc(file=sys.stderr)
        gui.messagebox.execute(gui.res.string_installer_tools_failed % (e), ["ok"], gui.res.color_dialog_negative)
        return False
Пример #27
0
def duplicate(domain):
    name = domain["name"]
    src_device = domain["device"]
    use_snapshot = domain.get("open") != False
    if use_snapshot:
        if dialogbox.messagebox.execute(
                gui.res.string_operation_desc,
                dialogbox.DialogBox.OKCANCEL()) != "ok":
            return

    s = system.getSystem()
    lvsize = domain.get("size") or s.determineLogicalVolumeSizeInGB(src_device)
    new_domain = edit_duplicate_domain(name)
    if new_domain == None: return

    hostname = new_domain["hostname"]
    vgname = new_domain["vgname"]

    lvname = hostname
    device_name = system.create_logical_volume_in_GB(vgname, lvname, lvsize,
                                                     True, "@wbvm")
    if device_name == None:
        wbui.play_sound("fail")
        gui.messagebox.execute(gui.res.string_duplicate_fail, ["ok"],
                               gui.res.color_dialog_negative)
        return

    metadata = None  # /etc/wb-va.xml

    # マーキーに作成中の仮想マシンに関する情報を表示
    footer.window.setText(gui.res.string_duplication_description %
                          (name, vgname, hostname))

    try:
        if use_snapshot:
            with s.openSnapshot(src_device, 1) as snapshot:
                exec_duplicate(snapshot, device_name, hostname)
        else:
            exec_duplicate(src_device, device_name, hostname)
    except Exception, e:
        s.removeLogicalVolume(device_name)
        wbui.play_sound("fail")
        traceback.print_exc(file=sys.stderr)
        gui.messagebox.execute(gui.res.string_replicate_fails % (e), ["ok"],
                               gui.res.color_dialog_negative)
        return False
Пример #28
0
def run(options, args):
    if len(args) < 2: raise cli.Error("Insufficient parameters.")

    src = args[0]
    dest = args[1]

    s = system.getSystem()

    if s.isBlockSpecial(src):
        if s.isLogicalVolume(src):
            return src_lv(src, dest, options)
        #else
        return src_block(src, dest, options)
    elif os.path.isdir(src):
        return src_dir(src, dest, options)
    #else
    raise cli.Error("Invalid source specified(must be a directory or a mountable block device)")
Пример #29
0
def run(source_device, esp, device, arch):
    s = system.getSystem()
    try:
        mount_option = "loop" if os.path.isfile(source_device) else None
        with s.temporaryMount(source_device, mount_option, "ro") as sourceDir:
            with s.temporaryMount(device) as targetDir:
                delfiles = []
                with s.temporaryFile() as tmpFileName: # excludeFile
                    with open(tmpFileName, "w") as tmpFile:
                        with dialogbox.messagebox.open(gui.res.string_installer_upgrade_check) as pb:
                            tarball = "%s/wb-%s.tar.xz" % (sourceDir, arch)
                            with s.openWbForInput("compare_files", [tarball, targetDir]) as compare_files:
                                nbr = s.getNonblockingReader(compare_files.stdout)
                                line = nbr.readline()
                                while line != "":
                                    if line != None:
                                        #print line
                                        if line.startswith("X "): tmpFile.write(".%s" % line[2:])
                                        elif line.startswith("D "): delfiles.append(line[2:].rstrip())
                                    else:
                                        gui.yieldFrame()
                                    line = nbr.readline()

                    with dialogbox.progressbar.open(gui.res.string_installer_upgrade_upgrade) as progress_bar:
                        with s.openWbForInput("extract_archive", ("-x", tmpFileName, tarball, targetDir)) as extract_archive:
                            show_progress(progress_bar, extract_archive)

                # delete removed files
                delete(targetDir, delfiles)
                # install wbui
                installer.copyWBUI(sourceDir, targetDir)

            with dialogbox.progressbar.open(string_copying_boot_files) as progress_bar: 
                with s.temporaryMount(esp) as boot_dir:
                    with s.openWbForInput("copy_boot_files", ("%s/EFI/Walbrix" % sourceDir, "%s/EFI/Walbrix" % boot_dir)) as copy_boot_files:
                        show_progress(progress_bar, copy_boot_files)
                    s.installGrubEFI(boot_dir)
                    disk = s.getDiskFromPartition(esp) # get the disk which ESP belongs to
                    if s.isBiosCompatibleDisk(disk):
                        s.installGrub(disk, boot_dir)

    except Exception, e:
        traceback.print_exc(file=sys.stderr)
        dialogbox.messagebox.execute(gui.res.string_installer_upgrade_failed % (e), None, gui.res.caution_sign)
        return False
Пример #30
0
def init():
    global canvas, cursor, back
    canvas = pygame.Surface(gui.res.contents_panel.get_size(), pygame.SRCALPHA, 32)
    cursor = pygame.Surface((canvas.get_width(), wbui.smallfont.get_height()))
    cursor.fill((255,255,128))

    #self.back = main.smallfont.render(u"何もせずにタイトルへ戻る", True, (255,255,255))
    s = system.getSystem()
    back = wbui.smallfont.render(gui.res.string_back_title_screen if s.isRunningAsGetty() else gui.res.string_wbui_exit, True, (255,255,255))
    #self.check_update = main.smallfont.render(u"アップデートをチェックしてから戻る", True, (255, 255, 255))
    #self.show_demo = main.smallfont.render(u"おまけのデモを見てから戻る", True, (255,255,255))

    global alpha, dalpha, selected, active, blink_count
    alpha = 50
    dalpha = 2
    selected = 0
    active = False
    blink_count = 0
Пример #31
0
def run(options, args):
    if len(args) < 2: raise cli.Error("Insufficient parameters.")

    src = args[0]
    dest = args[1]

    s = system.getSystem()

    if s.isBlockSpecial(src):
        if s.isLogicalVolume(src):
            return src_lv(src, dest, options)
        #else
        return src_block(src, dest, options)
    elif os.path.isdir(src):
        return src_dir(src, dest, options)
    #else
    raise cli.Error(
        "Invalid source specified(must be a directory or a mountable block device)"
    )
Пример #32
0
def create_vg():
    # ディスク選択
    selected_disk = select_disk()
    if selected_disk == None: return
    logicalname = selected_disk[0]
    product = selected_disk[1]
    size = selected_disk[2]

    # VGの名前をユーザーに決めてもらう
    vgname = input_vg_name(logicalname)
    if vgname == None: return

    if dialogbox.messagebox.execute(
            gui.res.string_erase_msg % (size, product, logicalname, vgname),
            dialogbox.DialogBox.OKCANCEL(), gui.res.caution_sign) != "ok":
        return

    try:
        with gui.progressbar.SyncedProgressBar(
                gui.res.string_disk_partition) as progressBar:
            s = system.getSystem()
            with s.openWbForInput("initialize_disk",
                                  [logicalname, vgname]) as initialize_disk:
                nbr = s.getNonblockingReader(initialize_disk.stdout)
                line = nbr.readline()
                while line != "":
                    if line != None:
                        (x, y) = (float(x) for x in line.rstrip().split('/'))
                        progressBar.setProgress(x / y)
                    progressBar.yieldFrame()
                    line = nbr.readline()

    except Exception as e:
        traceback.print_exc(file=sys.stderr)
        wbui.play_sound("fail")
        dialogbox.messagebox.execute(gui.res.string_volume_fail % e.message,
                                     None, gui.res.caution_sign)
        return None

    refresh()
    wbui.play_sound("success")
    gui.messagebox.execute(gui.res.string_volume_success % (vgname))
    return vgname
Пример #33
0
def parse(xml_stream):
    arch = system.getSystem().getArchitectureString()
    doc = ElementTree.parse(xml_stream)
    items = []
    for item in doc.findall(".//item"):
        i = {}
        i["id"] = item.get("id")
        i["minimum_ram"] = item.get("minimum_ram")
        i["minimum_hd"] = item.get("minimum_hd")
        i["title"] = item.findtext("title")
        i["description"] = item.findtext("description")
        i["image"] = item.find("image")
        if i["image"] != None: i["image"] = i["image"].get("uri")
        i["tarball"] = item.get("tarball")
        i["arch"] = item.get("arch")
        if i["arch"] == None: i["arch"] = "i686"
        if arch == i["arch"] or (arch == "x86_64" and i["arch"] == "i686"):
            items.append(i)
    return items
Пример #34
0
def getVirtualApplianceByCode():
    code = dialogbox.inputbox.TextInputBox(
        gui.res.string_virtual_appliance_code, "", 5, 32,
        "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    ).execute()
    if code == None: return None
    json_url = "http://goo.gl/" + code  # e.g. DoIX3

    try:
        with dialogbox.messagebox.open(gui.res.string_code_check):
            rst = http_client.nonblockHttpGet(json_url)
            va = json.loads(rst)
            for key in ["id", "title"]:
                if not key in va: raise ValueError("Invalid data")
    except ValueError:
        dialogbox.messagebox.execute(gui.res.string_code_not_correct, None,
                                     gui.res.caution_sign)
        return None
    except http_client.Cancelled:
        dialogbox.messagebox.execute(string_cancelled)
        return None
    except http_client.CurlException as e:
        dialogbox.messagebox.execute(
            gui.res.string_comm_error % (e.getError(), e.getURL()), None,
            gui.res.caution_sign)
        return None

    # architecture check
    required_arch = va["arch"] if "arch" in va else "i686"
    supported_arch = {"i686": ["i686"], "x86_64": ["i686", "x86_64"]}
    s = system.getSystem()
    arch = s.getArchitectureString()
    if arch not in supported_arch:
        dialogbox.messagebox.execute(gui.res.string_domain_sys_error % arch,
                                     None, gui.res.caution_sign)
        return None
    if required_arch not in supported_arch[arch]:
        dialogbox.messagebox.execute(
            gui.res.string_domain_support_error % (required_arch, arch), None,
            gui.res.caution_sign)
        return None

    return va
Пример #35
0
def nonblockHttpGet(url):
    cmdline = ["curl", "--cacert", CA_CERT_FILE, "-sLf", url]
    curl = subprocess.Popen(cmdline, shell=False, close_fds=True, stdout=subprocess.PIPE)
    s = system.getSystem()
    nbr = s.getNonblockingReader(curl.stdout)
    buf = ""
    r = nbr.read()
    while r != "":
        if r != None:
            buf += r
        if gui.yieldFrame():  # キャンセルキーでTrueが返る
            curl.terminate()
            raise Cancelled()
        r = nbr.read()
    curl.stdout.close()
    rst = curl.wait()
    if rst != 0:
        raise CurlException(rst, url)
    return buf
Пример #36
0
def nonblockHttpGet(url):
    cmdline = ["curl", "--cacert", CA_CERT_FILE, "-sLf", url]
    curl = subprocess.Popen(cmdline,
                            shell=False,
                            close_fds=True,
                            stdout=subprocess.PIPE)
    s = system.getSystem()
    nbr = s.getNonblockingReader(curl.stdout)
    buf = ""
    r = nbr.read()
    while r != "":
        if r != None: buf += r
        if gui.yieldFrame():  # キャンセルキーでTrueが返る
            curl.terminate()
            raise Cancelled()
        r = nbr.read()
    curl.stdout.close()
    rst = curl.wait()
    if rst != 0: raise CurlException(rst, url)
    return buf
Пример #37
0
def list_available_disks():
    useable_disks = []
    s = system.getSystem()
    with dialogbox.messagebox.open(string_searching_useable_disks):
        with s.openWbForInput("list_useable_disks") as list_useable_disks:
            nbr = s.getNonblockingReader(list_useable_disks.stdout)
            line = nbr.readline()
            while line != "":
                if line != None:
                    cols = line.split('\t')
                    useable_disks.append({
                        "logicalname": cols[0],
                        "size": cols[1],
                        "product": cols[2],
                        "sectorSize": int(cols[3])
                    })
                gui.yieldFrame()
                line = nbr.readline()

    return useable_disks
Пример #38
0
def rescue(source_device, arch):
    if gui.messagebox.execute(
            gui.res.string_installer_tools_rescue_mode %
        (arch), ["ok", "cancel"]) != "ok":
        return False

    try:
        s = system.getSystem()
        with s.temporaryMount(source_device, None, "ro") as sourceDir:
            kernel = "%s/boot/vmlinuz.%d" % (sourceDir, arch)
            kernel_args = "video=uvesafb:mtrr:3,ywrap,1024x768-32 logo.nologo"
            initrd = "%s/boot/rescue.img" % (sourceDir)
            kexec_load_kernel(kernel, kernel_args, initrd)
        pygame.quit()
        os.execv("/usr/sbin/kexec", ("/usr/sbin/kexec", "-e"))
    except Exception, e:
        traceback.print_exc(file=sys.stderr)
        gui.messagebox.execute(gui.res.string_installer_tools_failed % (e),
                               ["ok"], gui.res.color_dialog_negative)
        return False
Пример #39
0
def init():
    global canvas, cursor, back
    canvas = pygame.Surface(gui.res.contents_panel.get_size(), pygame.SRCALPHA,
                            32)
    cursor = pygame.Surface((canvas.get_width(), wbui.smallfont.get_height()))
    cursor.fill((255, 255, 128))

    #self.back = main.smallfont.render(u"何もせずにタイトルへ戻る", True, (255,255,255))
    s = system.getSystem()
    back = wbui.smallfont.render(
        gui.res.string_back_title_screen if s.isRunningAsGetty() else
        gui.res.string_wbui_exit, True, (255, 255, 255))
    #self.check_update = main.smallfont.render(u"アップデートをチェックしてから戻る", True, (255, 255, 255))
    #self.show_demo = main.smallfont.render(u"おまけのデモを見てから戻る", True, (255,255,255))

    global alpha, dalpha, selected, active, blink_count
    alpha = 50
    dalpha = 2
    selected = 0
    active = False
    blink_count = 0
Пример #40
0
def duplicate(domain):
    name = domain["name"]
    src_device = domain["device"]
    use_snapshot = domain.get("open") != False
    if use_snapshot:
        if dialogbox.messagebox.execute(gui.res.string_operation_desc, dialogbox.DialogBox.OKCANCEL()) != "ok": return

    s = system.getSystem()
    lvsize = domain.get("size") or s.determineLogicalVolumeSizeInGB(src_device)
    new_domain = edit_duplicate_domain(name)
    if new_domain == None: return

    hostname = new_domain["hostname"]
    vgname = new_domain["vgname"]

    lvname = hostname
    device_name = system.create_logical_volume_in_GB(vgname, lvname, lvsize, True, "@wbvm")
    if device_name == None:
        wbui.play_sound("fail")
        gui.messagebox.execute(gui.res.string_duplicate_fail, ["ok"], gui.res.color_dialog_negative)
        return

    metadata = None # /etc/wb-va.xml

    # マーキーに作成中の仮想マシンに関する情報を表示
    footer.window.setText(gui.res.string_duplication_description % (name,vgname,hostname) )

    try:
        if use_snapshot:
            with s.openSnapshot(src_device, 1) as snapshot:
                exec_duplicate(snapshot, device_name, hostname)
        else:
            exec_duplicate(src_device, device_name, hostname)
    except Exception, e:
        s.removeLogicalVolume(device_name)
        wbui.play_sound("fail")
        traceback.print_exc(file=sys.stderr)
        gui.messagebox.execute(gui.res.string_replicate_fails % (e), ["ok"], gui.res.color_dialog_negative)
        return False
Пример #41
0
def create_vg():
    # ディスク選択
    selected_disk = select_disk()
    if selected_disk == None: return
    logicalname = selected_disk[0]
    product = selected_disk[1]
    size = selected_disk[2]

    # VGの名前をユーザーに決めてもらう
    vgname = input_vg_name(logicalname)
    if vgname == None: return

    if dialogbox.messagebox.execute(gui.res.string_erase_msg % (size, product, logicalname,vgname), dialogbox.DialogBox.OKCANCEL(), gui.res.caution_sign) != "ok":
        return

    try:
        with gui.progressbar.SyncedProgressBar(gui.res.string_disk_partition) as progressBar:
            s = system.getSystem()
            with s.openWbForInput("initialize_disk", [logicalname, vgname]) as initialize_disk:
                nbr = s.getNonblockingReader(initialize_disk.stdout)
                line = nbr.readline()
                while line != "":
                    if line != None: 
                        (x, y) = (float(x) for x in line.rstrip().split('/'))
                        progressBar.setProgress(x / y)
                    progressBar.yieldFrame()
                    line = nbr.readline()

    except Exception as e:
        traceback.print_exc(file=sys.stderr)
        wbui.play_sound("fail")
        dialogbox.messagebox.execute(gui.res.string_volume_fail % e.message, None, gui.res.caution_sign)
        return None

    refresh()
    wbui.play_sound("success")
    gui.messagebox.execute(gui.res.string_volume_success % (vgname))
    return vgname
Пример #42
0
def expand(domain):
    s = system.getSystem()
    device = domain["device"]
    orig_disk = domain.get("size") or s.determineLogicalVolumeSizeInGB(device)
    min_disk = int(orig_disk) + 1
    disk = gui.inputbox.TextInputBox(gui.res.string_new_size, min_disk, None,
                                     1, 5,
                                     "0123456789").execute(gui.getDesktop())
    if disk == None: return False
    disk = int(disk)
    if disk < min_disk:
        gui.messagebox.execute(gui.res.string_size_desc, ["ok"],
                               gui.res.color_dialog_negative)
        return False
    if min_disk < 2048 and disk >= 2048:
        gui.messagebox.execute(string_cant_across_2tb, ["ok"],
                               gui.res.color_dialog_negative)
        return False

    if subprocess.Popen(
            "lvextend -L %dG %s" %
        (disk, device), shell=True, close_fds=True).wait() != 0:
        gui.messagebox.execute(gui.res.string_free_space_desc, ["ok"],
                               gui.res.color_dialog_negative)
        return False

    with s.temporaryMount(device, None, "inode32") as tmpdir:
        if subprocess.Popen("xfs_growfs %s" % tmpdir,
                            shell=True,
                            close_fds=True).wait() != 0:
            gui.messagebox.execute(gui.res.string_assign_desc, ["ok"],
                                   gui.res.color_dialog_negative)
            return False

    gui.messagebox.execute(gui.res.string_enhanced, ["ok"])
    return True
Пример #43
0
def init():
    s = system.getSystem()

    global hostname, version
    hostname = s.getHostname()
    version = system.version

    # 画像リソースのロード
    screen = gui.getScreen()
    global background, left_arrow, right_arrow, up_arrow, down_arrow, contents_color
    background = resource_loader.loadImage(
        ['background.jpg', 'background.png'], screen)
    gui.res.register("background", background)
    messagebox_buttons["ok"] = resource_loader.loadImage("button_ok.png")
    gui.res.register("button_ok", messagebox_buttons["ok"])
    messagebox_buttons["cancel"] = resource_loader.loadImage(
        "button_cancel.png")
    gui.res.register("button_cancel", messagebox_buttons["cancel"])

    left_arrow = resource_loader.loadImage("left.png")
    gui.res.register("left_arrow", left_arrow)
    right_arrow = resource_loader.loadImage("right.png")
    gui.res.register("right_arrow", right_arrow)
    up_arrow = resource_loader.loadImage("up.png")
    gui.res.register("list_up_arrow", up_arrow)
    down_arrow = resource_loader.loadImage("down.png")
    gui.res.register("list_down_arrow", down_arrow)
    gui.res.register("caution_sign",
                     resource_loader.loadImage("caution_sign.png"))
    gui.res.register("icon_status",
                     resource_loader.loadImage("icon_status.png"))
    gui.res.register("icon_volume",
                     resource_loader.loadImage("icon_volume.png"))
    gui.res.register("icon_domain",
                     resource_loader.loadImage("icon_domain.png"))
    gui.res.register("icon_app", resource_loader.loadImage("icon_app.png"))
    gui.res.register("icon_options",
                     resource_loader.loadImage("icon_options.png"))
    gui.res.register("icon_console",
                     resource_loader.loadImage("icon_console.png"))
    gui.res.register("icon_support",
                     resource_loader.loadImage("icon_support.png"))
    gui.res.register("icon_back", resource_loader.loadImage("icon_back.png"))
    gui.res.register("icon_shutdown",
                     resource_loader.loadImage("icon_shutdown.png"))
    gui.res.register("contents_panel",
                     resource_loader.loadImage("contents_panel.png"))

    # フォントのロード
    global fontfile, font, smallfont, extrasmallfont
    fontfile_candidates = [
        theme.getThemeFilePath("pfont.ttf"),
        "/System/Library/Fonts/ヒラギノ角ゴ ProN W3.otf",
        "/usr/share/fonts/vlgothic/VL-PGothic-Regular.ttf",
        "/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf"
    ]
    for fc in fontfile_candidates:
        if fc != None and os.path.exists(fc):
            fontfile = fc
            break

    gui.res.register("font_system", gui.FontFactory(fontfile))

    font = gui.res.font_system.getFont(28)
    smallfont = gui.res.font_system.getFont(22)
    extrasmallfont = gui.res.font_system.getFont(16)
    gui.res.register("font_messagebox", font)
    gui.res.register("font_select_option", smallfont)
    gui.res.register("font_splash_message", font)
    gui.res.register("font_splash_serialno", smallfont)

    # 音声リソースのロード
    if sound_materials != None:
        sound_materials["click"] = resource_loader.loadSound("click.ogg")
        sound_materials["cancel"] = resource_loader.loadSound("cancel.ogg")
        sound_materials["fail"] = resource_loader.loadSound("fail.ogg")
        sound_materials["success"] = resource_loader.loadSound("success.ogg")

    # クロックの初期化
    #global clock
    clock = pygame.time.Clock()
    gui.setClock(clock)

    # initialize dialog box subsystem
    dialogbox.init()
Пример #44
0
def src_block(src, dest, options):
    s = system.getSystem()
    with s.temporaryMount(src, None, "ro") as tmpdir:
        return src_dir(tmpdir, dest, options)
Пример #45
0
def src_lv(src, dest, options):
    s = system.getSystem()
    with s.openSnapshot(src, options.snapshot_size) as snapshot:
        return src_block(snapshot, dest, options)
Пример #46
0
                          (app, gui.res.string_app_description)))
    mainmenu_items.append(
        mainmenu.ListItem(gui.res.icon_options, gui.res.string_options,
                          (options, gui.res.string_options_description)))
    mainmenu_items.append(
        mainmenu.ListItem(gui.res.icon_support, gui.res.string_support,
                          (support, gui.res.string_support_description)))

    mainmenu.window.addItems(mainmenu_items)

    items_height = sum(map(lambda x: x.getHeight(), mainmenu_items))
    mainmenu.window.addItem(
        gui.list.Separator(332 - mainmenu.window.getMarginTop() -
                           items_height))

    s = system.getSystem()
    mainmenu.window.addItem(
        mainmenu.SmallListItem(
            gui.res.icon_back, gui.res.string_back
            if s.isRunningAsGetty() else gui.res.string_end,
            (back, gui.res.string_back_description
             if s.isRunningAsGetty() else gui.res.string_back_home_)))

    mainmenu.window.addItem(
        mainmenu.SmallListItem(
            gui.res.icon_shutdown, gui.res.string_shutdown,
            (shutdown, gui.res.string_shutdown_description)))

    desktop.addChild("header", header.window, (0, 0), -1,
                     CoordTransition((0, -header.window.getHeight())))
    desktop.addChild("footer", footer.window,
Пример #47
0
def run(domain):
    operations = []
    memory = domain.get("memory")
    domain_name = domain["name"]
    s = system.getSystem()
    if memory is None:
        operations.append({
            "id": "start",
            "label": gui.res.string_domain_operate_start
        })
    else:
        if s.isRunningAsGetty():
            operations.append({
                "id": "console",
                "label": gui.res.string_console
            })
        operations.append({"id": "shutdown", "label": gui.res.string_ins_ends})
        operations.append({"id": "reboot", "label": gui.res.string_restart})
        operations.append({"id": "destroy", "label": gui.res.string_stop})
    if domain["autostart"]:
        operations.append({
            "id": "noautostart",
            "label": gui.res.string_can_automatic
        })
    else:
        operations.append({
            "id": "autostart",
            "label": gui.res.string_auto_start
        })

    modifiable = domain.get("writable") and not domain.get(
        "open") and domain.get("fstype") == "xfs"

    if memory == None:
        if modifiable:
            operations.append({
                "id": "rename",
                "label": gui.res.string_name_ram
            })
            operations.append({
                "id": "expand",
                "label": gui.res.string_extend_space
            })
            operations.append({
                "id": "vpn",
                "label": gui.res.string_vpn_config
            })
        operations.append({"id": "delete", "label": gui.res.string_remove})
    operations.append({"id": "duplicate", "label": gui.res.string_replicate})

    metadata = get_va_metadata_from_cache(domain_name)
    instruction = None
    if metadata != None:
        instructions = metadata.findall("./instruction")
        if len(instructions) > 0:
            instruction = instructions[0].text

    if instruction != None:
        operations.append({"id": "instruction", "label": gui.res.string_learn})

    operation = gui.selectbox.execute(domain_name, operations)

    if operation == "start":
        return start(domain)
    elif operation == "console":
        return console(domain)
    elif operation == "shutdown":
        return shutdown(domain)
    elif operation == "reboot":
        return reboot(domain)
    elif operation == "destroy":
        return destroy(domain)
    elif operation == "delete":
        return delete(domain)
    elif operation == "rename":
        return rename(domain["name"], domain["device"])
    elif operation == "expand":
        return expand(domain)
    elif operation == "duplicate":
        return duplicate(domain)
    elif operation == "vpn":
        return vpn(domain)
    elif operation == "autostart":
        cli_autostart.set_autostart(domain_name, True)
        footer.window.setText(string_vm_autostart % (domain_name))
        return True

    elif operation == "noautostart":
        cli_autostart.set_autostart(domain_name, False)
        footer.window.setText(string_vm_no_autostart % (domain_name))
        return True

    elif operation == "instruction":
        dialogbox.messagebox.execute(instruction)
    return False
Пример #48
0
def create_new_domain(args):
    hostname = args["hostname"]
    vgname = args["vgname"]
    tarball = args["tarball"]
    memory = args["memory"]
    disk = args["disk"]
    vcpus = 1

    lvname = hostname
    device_name = system.create_logical_volume_in_GB(vgname, lvname, disk,
                                                     True, "@wbvm")
    if device_name == None:
        wbui.play_sound("fail")
        dialogbox.messagebox.execute(gui.res.string_domain_failed, None,
                                     gui.res.caution_sign)
        return

    metadata = None  # /etc/wb-va.xml
    configuration_messages = None

    # マーキーに作成中の仮想マシンに関する情報を表示
    footer.window.setText(gui.res.string_area_description %
                          (hostname, vgname, memory, disk))

    try:
        s = system.getSystem()
        with s.temporaryMount(device_name, None, "inode32") as tmpdir:
            with dialogbox.progressbar.open(
                    gui.res.string_download_description) as pb:
                with s.openWbForInput("extract_archive",
                                      (tarball, tmpdir)) as extract_archive:
                    nbr = s.getNonblockingReader(extract_archive.stdout)
                    line = nbr.readline()
                    while line != "":
                        if line != None:
                            (n, m) = map(lambda a: float(a), line.split('/'))
                            pb.setProgress(n / m)
                        if gui.yieldFrame():
                            extract_archive.send_signal(signal.SIGINT)
                        line = nbr.readline()

            cli_import.set_hostname(tmpdir, hostname)

            # https://github.com/wbrxcorp/walbrix/issues/39
            xen_conf_dir = os.path.join(tmpdir, "etc/xen")
            if not os.path.isdir(xen_conf_dir):
                if os.path.exists(xen_conf_dir): os.unlink(xen_conf_dir)
                os.makedirs(xen_conf_dir)
            with open(os.path.join(xen_conf_dir, "config"), "w") as f:
                f.write("memory=%d\n" % memory)
                f.write("vcpus=%d\n" % vcpus)

            # rootのパスワードをつける
            serialnum = status.get_serial_number()
            set_root_password(tmpdir, serialnum)

            # VAのメタデータを得る
            metadata = system.get_va_metadata(device_name, tmpdir)

            # メタデータを元に、コンフィギュレーションを行う
            if metadata != None:
                configuration_messages = configure_va(metadata, tmpdir)

    except Exception, e:
        s = system.getSystem()
        s.removeLogicalVolume(device_name)
        wbui.play_sound("fail")
        traceback.print_exc(file=sys.stderr)
        dialogbox.messagebox.execute(gui.res.string_create_failed % (e), None,
                                     gui.res.caution_sign)
        return False
Пример #49
0
 def setupTemplate(self):
   self.template.session = self.session
   self.template.account = self.account
   self.template.request = self.request
   self.template.system = system.getSystem()
   self.template.google_signin = users.create_login_url(self.request.path)
Пример #50
0
def delete_app(app):
    s = system.getSystem()
    s.removeLogicalVolume(app["device"])
    refresh()
    return True
Пример #51
0
def create():
    code = dialogbox.inputbox.TextInputBox(gui.res.string_app_code, "", 5, 32, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").execute()
    if code == None: return None
    json_url = "http://goo.gl/" + code # e.g. lLj8Q

    try:
        with dialogbox.messagebox.open(gui.res.string_app_code_check):
            rst = http_client.nonblockHttpGet(json_url)
            app = json.loads(rst)
            for key in ["id", "title","type"]: 
                if not key in app: raise ValueError("Invalid data")
            if app["type"] != "app":
                raise ValueError("type must be app")
    except ValueError:
        dialogbox.messagebox.execute(gui.res.string_code_invalid, None, gui.res.caution_sign)
        return None
    except http_client.Cancelled:
        dialogbox.messagebox.execute(gui.res.string_app_canceled)
        return None
    except http_client.CurlException as e:
        dialogbox.messagebox.execute(gui.res.string_app_comm_error % (e.getError(), e.getURL()), None, gui.res.caution_sign)
        return None

    images = app["images"] if "images" in app else None
    tarball = app["tarball"] if "tarball" in app else None
    minimum_hd = app["minimum_hd"] if "minimum_hd" in app else None
    title = app["title"] if "title" in app else None
    description = app["description"] if "description" in app else None

    s = system.getSystem()
    if not s.checkIfArchitectureIsSupported(app["arch"] if "arch" in app else "i686"):
         dialogbox.messagebox.execute(gui.res.string_app_not_supported % s.getArchitectureString(), None, gui.res.caution_sign)
         return False

    try:
        with dialogbox.messagebox.open(gui.res.string_apps_details):
            image_url = images[0]["url"] if images != None and len(images) > 0 and "url" in images[0] else None

            if image_url != None: 
                rst = http_client.nonblockHttpGet(image_url)
                image = pygame.image.load(io.BytesIO(rst)).convert_alpha()
            else:
                image = None

            contentLength = None
            if tarball != None:
                headers = http_client.nonblockingHttpHead(tarball)
                if "content-length" in headers:
                    contentLength = headers["content-length"]
    except http_client.Cancelled:
        dialogbox.messagebox.execute(gui.res.string_app_canceled)
        return False
    except http_client.CurlException as e:
        dialogbox.messagebox.execute(gui.res.string_app_comm_error % (e.getError(), e.getURL()), None, gui.res.caution_sign)
        return False

    buttons = []
    if tarball != None: buttons.append({ "id":"download", "icon":gui.res.icon_ok, "text":gui.res.string_app_download })
    buttons.append({ "id":"cancel", "icon":gui.res.icon_cancel, "text":gui.res.string_app_can})
    specs = []
    if contentLength != None: specs.append(gui.res.string_downl_capacity % (float(contentLength) / 1024 / 1024))
    if minimum_hd != None: specs.append(gui.res.string_app_minimum_hd % minimum_hd)

    apd = domain.create.VirtualApplianceDescription(title, image, description, " ".join(specs))

    if dialogbox.DialogBox(apd, buttons).execute() != "download": return False

    if exists(app["id"]):
        dialogbox.messagebox.execute(gui.res.string_app_exists % app["id"], None, gui.res.caution_sign)
        return False

    
    vgname = None

    while vgname == None:
        options = []
        for vg in volume.list_vgs():
            options.append({"id":vg["name"], "label":vg["name"]})
        vgname = gui.selectbox.execute(gui.res.string_app__select_area, options)
        if vgname == None: return False

        lvname = app["id"]
        try:
            device_name = s.createLogicalVolumeInMB(vgname, lvname, int(minimum_hd), "@wbapp")
        except Exception, e:
            traceback.print_exc(file=sys.stderr)
            dialogbox.messagebox.execute(gui.res.string_app_area_creation_failed_desc, None, gui.res.caution_sign)
            vgname = None
Пример #52
0
def src_lv(src, dest, options):
    s = system.getSystem()
    with s.openSnapshot(src, options.snapshot_size) as snapshot:
        return src_block(snapshot, dest, options)