Ejemplo n.º 1
0
    def stop(self, force=False):
        """
        <comment-ja>
        制御対象サービスを停止する
        @param self: -
        @return boolean   成功:True  失敗:False
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """
        retval = False

        if force is False:
            pids = self.status()

        if force is False and len(pids) == 0:
            message = "Warning: '%s' already stopped." % (self.service_name, )
            self.error_msg.append(message)

        else:
            if os.path.exists(self.service_script) and is_executable(
                    self.service_script):
                command = "%s stop" % (self.service_script, )
                command_args = command.split()
                #print command
                (ret, res) = execute_command(command_args)

                time.sleep(self.sleep_time)
                if force is False:
                    pids = self.status()

                if force is True or len(pids) == 0:
                    message = "Notice: succeeded to stop '%s'." % (
                        self.service_name, )
                    #print message
                    retval = True
                else:
                    pids = [str(p) for p, q in zip(pids, pids[1:] + [None])]
                    message = "Error: failed to stop '%s'. [%s]" % (
                        self.service_name,
                        " ".join(res),
                    )
                    self.error_msg.append(message)
                    message = "Notice: '%s' is running. [PID:%s]" % (
                        self.service_name,
                        ",".join(pids),
                    )
                    retval = False
            else:
                message = "Error: '%s' not found." % (self.service_script, )
                self.error_msg.append(message)

        return retval
Ejemplo n.º 2
0
    def stop(self,force=False):
        """
        <comment-ja>
        制御対象サービスを停止する
        @param self: -
        @return boolean   成功:True  失敗:False
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """
        retval = False

        if force is False:
            pids = self.status()

        if force is False and len(pids) == 0:
            message = "Warning: '%s' already stopped." % (self.service_name,)
            self.error_msg.append(message)

        else:
            if os.path.exists(self.service_script) and is_executable(self.service_script):
                command = "%s stop" % (self.service_script,)
                command_args = command.split()
                #print command
                (ret,res) = execute_command(command_args)

                time.sleep(self.sleep_time)
                if force is False:
                   pids = self.status()

                if force is True or len(pids) == 0:
                    message = "Notice: succeeded to stop '%s'." % (self.service_name,)
                    #print message
                    retval = True
                else:
                    pids = [str(p) for p, q in zip(pids, pids[1:] + [None])]
                    message = "Error: failed to stop '%s'. [%s]" % (self.service_name," ".join(res),)
                    self.error_msg.append(message)
                    message = "Notice: '%s' is running. [PID:%s]" % (self.service_name,",".join(pids),)
                    retval = False
            else:
                message = "Error: '%s' not found." % (self.service_script,)
                self.error_msg.append(message)

        return retval
Ejemplo n.º 3
0
    def set_service_path(self,path=None):
        """
        <comment-ja>
        制御対象サービスの実行ファイル名をセットする
        @param self: -
        @param string path	制御対象サービスの実行ファイル名
        @return: なし
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        self.service_path = self._get_service_path(path)
        return os.path.exists(self.service_path) and is_executable(self.service_path)
Ejemplo n.º 4
0
    def set_service_path(self, path=None):
        """
        <comment-ja>
        制御対象サービスの実行ファイル名をセットする
        @param self: -
        @param string path	制御対象サービスの実行ファイル名
        @return: なし
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        self.service_path = self._get_service_path(path)
        return os.path.exists(self.service_path) and is_executable(
            self.service_path)
Ejemplo n.º 5
0
    def set_service_name(self,name=None):
        """
        <comment-ja>
        制御対象サービス名をセットする
        @param self: -
        @param string name	制御対象サービス名
        @return: なし
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        self.service_name = name
        self.service_script = "%s/%s" % (self.initrddir, name,)

        return os.path.exists(self.service_script) and is_executable(self.service_script)
Ejemplo n.º 6
0
    def _get_service_path(self, path=None):
        """
        <comment-ja>
        ベースネームの実行ファイル名から実行ファイルへの絶対パスを取得する
        @param self: -
        @param string path	実行ファイル名
        @return string		実行ファイルへの絶対パス
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        if path is None:
            path = self.service_name

        search_paths = [
            "/usr/share/karesansui/bin",
            "/usr/share/karesansui/sbin",
            "/usr/sbin",
            "/usr/bin",
            "/sbin",
            "/bin",
            "/usr/libexec",
            "/usr/libexec/postfix",
            "/usr/lib/courier-imap/libexec",
        ]

        if path[0:1] != "/":
            for _path in search_paths:
                _path = "%s/%s" % (
                    _path,
                    path,
                )
                if os.path.exists(_path) and is_executable(_path):
                    path = _path
                    break

        return path
Ejemplo n.º 7
0
    def _get_service_path(self,path=None):
        """
        <comment-ja>
        ベースネームの実行ファイル名から実行ファイルへの絶対パスを取得する
        @param self: -
        @param string path	実行ファイル名
        @return string		実行ファイルへの絶対パス
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        if path is None:
            path = self.service_name

        search_paths = [
            "/usr/share/karesansui/bin",
            "/usr/share/karesansui/sbin",
            "/usr/sbin",
            "/usr/bin",
            "/sbin",
            "/bin",
            "/usr/libexec",
            "/usr/libexec/postfix",
            "/usr/lib/courier-imap/libexec",
        ]

        if path[0:1] != "/":
            for _path in search_paths:
                _path = "%s/%s" % (_path,path,)
                if os.path.exists(_path) and is_executable(_path):
                    path = _path
                    break

        return path
Ejemplo n.º 8
0
    def set_service_name(self, name=None):
        """
        <comment-ja>
        制御対象サービス名をセットする
        @param self: -
        @param string name	制御対象サービス名
        @return: なし
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """

        self.service_name = name
        self.service_script = "%s/%s" % (
            self.initrddir,
            name,
        )

        return os.path.exists(self.service_script) and is_executable(
            self.service_script)
Ejemplo n.º 9
0
    def onboot(self, flag=None, runlevel=None):
        """
        <comment-ja>
        制御対象サービスのマシン起動時の起動状態の有効/無効の切り替えを行う。
        または、その状態を取得する。
        @param self: -
        @param string flag 指定なし:状態を取得する
                           True    :起動時有効にする
                           False   :起動時無効にする
        @return boolean    True :状態取得なら起動時有効、起動時切替なら成功
                           False:状態取得なら起動時有効、起動時切替なら成功
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """
        retval = False

        if flag is not None and flag is not True and flag is not False:
            raise Exception("Invalid argument.")

        if os.path.exists(self.service_script) and is_executable(
                self.service_script):
            script_name = os.path.basename(self.service_script)

            old_lang = os.environ["LANG"]
            os.environ["LANG"] = "C"

            if flag is None:
                command = "%s --list %s" % (
                    self.command_chkconfig,
                    script_name,
                )
                command_args = command.split()
                (ret, res) = execute_command(command_args)

                if runlevel is None:
                    runlevel = self.runlevel
                try:
                    m = re.search("[ \t]+%s:on[ \t]+" % runlevel, res[0])
                    if m:
                        retval = True
                except:
                    pass

            else:
                if flag is True:
                    on_or_off = "on"
                else:
                    on_or_off = "off"
                if runlevel is None:
                    command = "%s %s %s" % (self.command_chkconfig,
                                            script_name, on_or_off)
                else:
                    command = "%s --level %s %s %s" % (self.command_chkconfig,
                                                       runlevel, script_name,
                                                       on_or_off)

                command_args = command.split()
                (ret, res) = execute_command(command_args)
                if ret == 0:
                    retval = True

            os.environ["LANG"] = old_lang

        else:
            message = "Error: '%s' not found." % (self.service_script, )
            self.error_msg.append(message)

        return retval
Ejemplo n.º 10
0
    def process(self):
        (opts, args) = getopts()

        start_msg = _("Generated by %s on %s") % (prog_name,time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
        print "# " + start_msg

        if is_executable(COMMAND_VIRSH):
            old_lang = os.environ.get('LANG')
            os.environ['LANG'] = "C"

            if opts.all is True or (opts.list is not True and opts.netlist is not True and opts.nodeinfo is not True and opts.poollist is not True):
                """ Show version """
                print ""
                print "## Version"
                (rc,res) = execute_command([COMMAND_VIRSH,"version"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line
                self.showKaresansuiVersion()

            if opts.all is True:
                """ Show uri """
                print ""
                print "## URI"
                (rc,res) = execute_command([COMMAND_VIRSH,"uri"])
                if rc == 0:
                    print _("Connecting URI: %s") %(res[0])

                """ Show hostname """
                print ""
                print "## Hostname"
                (rc,res) = execute_command([COMMAND_VIRSH,"hostname"])
                if rc == 0:
                    print _("Hypervisor hostname: %s") %(res[0])

            if opts.all is True or opts.nodeinfo is True:
                """ Show nodeinfo """
                print ""
                print "## Node Information"
                (rc,res) = execute_command([COMMAND_VIRSH,"nodeinfo"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.list is True:
                """ Show dom list """
                print ""
                print "## Domain List"
                (rc,res) = execute_command([COMMAND_VIRSH,"list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.netlist is True:
                """ Show net list """
                print ""
                print "## Network List"
                (rc,res) = execute_command([COMMAND_VIRSH,"net-list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.poollist is True:
                """ Show pool list """
                print ""
                print "## Pool List"
                (rc,res) = execute_command([COMMAND_VIRSH,"pool-list","--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            os.environ['LANG'] = old_lang
        else:
            try:
                conn = libvirt.openReadOnly(None)
                hypervisor = conn.getType()

                if opts.all is True or (opts.list is not True and opts.netlist is not True and opts.nodeinfo is not True and opts.poollist is not True):
                    """ Show version """
                    print ""
                    print "## Version"
                    ret = libvirtmod.virGetVersion(hypervisor)
                    libVersion = ret[0]
                    apiVersion = ret[1]

                    libVersion_major = libVersion / 1000000
                    libVersion %= 1000000
                    libVersion_minor = libVersion / 1000
                    libVersion_rel = libVersion % 1000
                    apiVersion_major = apiVersion / 1000000
                    apiVersion %= 1000000
                    apiVersion_minor = apiVersion / 1000
                    apiVersion_rel = apiVersion % 1000

                    print _("Using library: libvir %d.%d.%d") %(libVersion_major, libVersion_minor, libVersion_rel)
                    print _("Using API: %s %d.%d.%d") %(hypervisor, apiVersion_major, apiVersion_minor, apiVersion_rel)

                    try:
                        # See https://www.redhat.com/archives/libvir-list/2010-January/msg00723.html
                        ret = libvirtmod.virConnectGetVersion(conn._o)
                        hvVersion = ret
                        hvVersion_major = hvVersion / 1000000
                        hvVersion %= 1000000
                        hvVersion_minor = hvVersion / 1000
                        hvVersion_rel = hvVersion % 1000
                        print _("Running hypervisor: %s %d.%d.%d") %(hypervisor, hvVersion_major, hvVersion_minor, hvVersion_rel)
                    except:
                        if hypervisor == "QEMU":
                            (rc,res) = execute_command(["qemu","--version"])
                            if rc == 0:
                                p = re.compile("QEMU PC emulator version ([0-9\.]+),.*")
                                if p.search(res[0]):
                                    qemuVersion = p.sub("\\1",res[0])
                                    print _("Running hypervisor: %s %s") %(hypervisor, qemuVersion)

                    self.showKaresansuiVersion()

                if opts.all is True:
                    """ Show uri """
                    print ""
                    print "## URI"
                    uri = conn.getURI()
                    print _("Connecting URI: %s") %(uri)

                    """ Show hostname """
                    print ""
                    print "## Hostname"
                    hostname = conn.getHostname()
                    print _("Hypervisor hostname: %s") %(hostname)

                if opts.all is True or opts.nodeinfo is True:
                    """ Show nodeinfo """
                    print ""
                    print "## Node Information"
                    nodeInfo = conn.getInfo()
                    print "%-20s %s"    % (_("CPU model:")         ,nodeInfo[0])
                    print "%-20s %s"    % (_("CPU(s):")            ,nodeInfo[2])
                    print "%-20s %s MHz"% (_("CPU frequency:")     ,nodeInfo[3])
                    print "%-20s %s"    % (_("CPU socket(s):")     ,nodeInfo[5])
                    print "%-20s %s"    % (_("Core(s) per socket:"),nodeInfo[6])
                    print "%-20s %s"    % (_("Thread(s) per core:"),nodeInfo[7])
                    print "%-20s %s"    % (_("NUMA cell(s):")      ,nodeInfo[4])
                    print "%-20s %lu kB"% (_("Memory Size:")  ,(float)(nodeInfo[1])*1024)

                if opts.all is True or opts.list is True:
                    """ Show dom list """
                    print ""
                    print "## Domain List"
                    state_flags = [
                                  "no state",    # VIR_DOMAIN_NOSTATE
                                  "running",     # VIR_DOMAIN_RUNNING
                                  "idle",        # VIR_DOMAIN_BLOCKED
                                  "paused",      # VIR_DOMAIN_PAUSED
                                  "in shutdown", # VIR_DOMAIN_SHUTDOWN
                                  "shut off",    # VIR_DOMAIN_SHUTOFF
                                  "crashed",     # VIR_DOMAIN_CRASHED
                                  ]
                    #print "%3s %-20s %s" %(_("Id"), _("Name"), _("State"))
                    #print "----------------------------------"
                    print "%3s %-20s %-12s %-37s %-10s %-12s %-12s %-3s %-12s" %(_("Id"), _("Name"), _("State"), _("UUID"), _("Autostart"), _("MaxMem"), _("Memory"), _("Vcpus"), _("CPUTime"), )
                    print "---------------------------------------------------------------------------"

                    domains_ids = conn.listDomainsID()
                    for id in domains_ids:
                        dom = conn.lookupByID(id)
                        name    = dom.name()
                        domID   = id
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %("-", name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %(domID, name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])

                    defined_domains = conn.listDefinedDomains()
                    for name in defined_domains:
                        dom = conn.lookupByName(name)
                        #print dom.memoryStats()
                        domID   = dom.ID()
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %("-", name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" %(domID, name, state_flags[state], domUUID, locale_domAutostart, domInfo[1], domInfo[2], domInfo[3], domInfo[4])

                if opts.all is True or opts.netlist is True:
                    """ Show net list """
                    print ""
                    print "## Network List"
                    #print "%-20s %-10s %-10s" %(_("Name"), _("State"), _("Autostart"))
                    #print "-----------------------------------------"
                    print "%-20s %-10s %-37s %-10s" %(_("Name"), _("State"), _("UUID"), _("Autostart"), )
                    print "--------------------------------------------------------------------------"
                    networks = conn.listNetworks()
                    for name in networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Active"), uuid, locale_autostart)

                    defined_networks = conn.listDefinedNetworks()
                    for name in defined_networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Inactive"), uuid, locale_autostart)

                if opts.all is True or opts.poollist is True:
                    """ Show pool list """
                    #taizoa
                    print ""
                    print "## Pool List"
                    print "%-20s %-10s %-37s %-10s" %(_("Name"), _("State"), _("UUID"), _("Autostart"), )
                    print "--------------------------------------------------------------------------"
                    pools = conn.listStoragePools()
                    for name in pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Active"), uuid, locale_autostart)

                    defined_pools = conn.listDefinedStoragePools()
                    for name in defined_pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" %(name, _("Inactive"), uuid, locale_autostart)

            except:
                pass

        if opts.all is True:
            """ Show available uris """
            print ""
            print "## Available URIs"
            for mech,uri in available_virt_uris().iteritems():
               print uri

            """ Show available mechs """
            print ""
            print "## Available mechanisms"
            for mech in available_virt_mechs():
               print mech

            """ Show installed packages """
            print ""
            print "## Installed packages"
            (rc,res) = execute_command(["rpm","-qa",'--queryformat=%{NAME}\t%{VERSION}\t%{RELEASE}\t%{INSTALLTIME}\t%{BUILDHOST}\n'])
            if rc == 0:
                print "%-25s %-10s %-10s %-20s" %(_("Name"), _("Version"), _("Release"), _("InstallTime"), )
                print "------------------------------------------------------------------"
                p = re.compile("hde\.co\.jp")
                output = []
                for aline in res:
                    arr = aline.split("\t")
                    if p.search(arr[4]):
                        str = "%-25s %-10s %-10s %-20s" %(arr[0],arr[1],arr[2],time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(float(arr[3]))),)
                        output.append(str)
                print "\n".join(sorted(output))

        finish_msg = _("Completed on %s") % time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
        print ""
        print "# " + finish_msg

        return True
Ejemplo n.º 11
0
    def process(self):
        (opts, args) = getopts()

        start_msg = _("Generated by %s on %s") % (
            prog_name, time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
        print "# " + start_msg

        if is_executable(COMMAND_VIRSH):
            old_lang = os.environ.get('LANG')
            os.environ['LANG'] = "C"

            if opts.all is True or (opts.list is not True
                                    and opts.netlist is not True
                                    and opts.nodeinfo is not True
                                    and opts.poollist is not True):
                """ Show version """
                print ""
                print "## Version"
                (rc, res) = execute_command([COMMAND_VIRSH, "version"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line
                self.showKaresansuiVersion()

            if opts.all is True:
                """ Show uri """
                print ""
                print "## URI"
                (rc, res) = execute_command([COMMAND_VIRSH, "uri"])
                if rc == 0:
                    print _("Connecting URI: %s") % (res[0])
                """ Show hostname """
                print ""
                print "## Hostname"
                (rc, res) = execute_command([COMMAND_VIRSH, "hostname"])
                if rc == 0:
                    print _("Hypervisor hostname: %s") % (res[0])

            if opts.all is True or opts.nodeinfo is True:
                """ Show nodeinfo """
                print ""
                print "## Node Information"
                (rc, res) = execute_command([COMMAND_VIRSH, "nodeinfo"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.list is True:
                """ Show dom list """
                print ""
                print "## Domain List"
                (rc, res) = execute_command([COMMAND_VIRSH, "list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.netlist is True:
                """ Show net list """
                print ""
                print "## Network List"
                (rc,
                 res) = execute_command([COMMAND_VIRSH, "net-list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            if opts.all is True or opts.poollist is True:
                """ Show pool list """
                print ""
                print "## Pool List"
                (rc,
                 res) = execute_command([COMMAND_VIRSH, "pool-list", "--all"])
                if rc == 0:
                    for line in res:
                        if line != "":
                            print line

            os.environ['LANG'] = old_lang
        else:
            try:
                conn = libvirt.openReadOnly(None)
                hypervisor = conn.getType()

                if opts.all is True or (opts.list is not True
                                        and opts.netlist is not True
                                        and opts.nodeinfo is not True
                                        and opts.poollist is not True):
                    """ Show version """
                    print ""
                    print "## Version"
                    ret = libvirtmod.virGetVersion(hypervisor)
                    libVersion = ret[0]
                    apiVersion = ret[1]

                    libVersion_major = libVersion / 1000000
                    libVersion %= 1000000
                    libVersion_minor = libVersion / 1000
                    libVersion_rel = libVersion % 1000
                    apiVersion_major = apiVersion / 1000000
                    apiVersion %= 1000000
                    apiVersion_minor = apiVersion / 1000
                    apiVersion_rel = apiVersion % 1000

                    print _("Using library: libvir %d.%d.%d") % (
                        libVersion_major, libVersion_minor, libVersion_rel)
                    print _("Using API: %s %d.%d.%d") % (
                        hypervisor, apiVersion_major, apiVersion_minor,
                        apiVersion_rel)

                    try:
                        # See https://www.redhat.com/archives/libvir-list/2010-January/msg00723.html
                        ret = libvirtmod.virConnectGetVersion(conn._o)
                        hvVersion = ret
                        hvVersion_major = hvVersion / 1000000
                        hvVersion %= 1000000
                        hvVersion_minor = hvVersion / 1000
                        hvVersion_rel = hvVersion % 1000
                        print _("Running hypervisor: %s %d.%d.%d") % (
                            hypervisor, hvVersion_major, hvVersion_minor,
                            hvVersion_rel)
                    except:
                        if hypervisor == "QEMU":
                            (rc, res) = execute_command(["qemu", "--version"])
                            if rc == 0:
                                p = re.compile(
                                    "QEMU PC emulator version ([0-9\.]+),.*")
                                if p.search(res[0]):
                                    qemuVersion = p.sub("\\1", res[0])
                                    print _("Running hypervisor: %s %s") % (
                                        hypervisor, qemuVersion)

                    self.showKaresansuiVersion()

                if opts.all is True:
                    """ Show uri """
                    print ""
                    print "## URI"
                    uri = conn.getURI()
                    print _("Connecting URI: %s") % (uri)
                    """ Show hostname """
                    print ""
                    print "## Hostname"
                    hostname = conn.getHostname()
                    print _("Hypervisor hostname: %s") % (hostname)

                if opts.all is True or opts.nodeinfo is True:
                    """ Show nodeinfo """
                    print ""
                    print "## Node Information"
                    nodeInfo = conn.getInfo()
                    print "%-20s %s" % (_("CPU model:"), nodeInfo[0])
                    print "%-20s %s" % (_("CPU(s):"), nodeInfo[2])
                    print "%-20s %s MHz" % (_("CPU frequency:"), nodeInfo[3])
                    print "%-20s %s" % (_("CPU socket(s):"), nodeInfo[5])
                    print "%-20s %s" % (_("Core(s) per socket:"), nodeInfo[6])
                    print "%-20s %s" % (_("Thread(s) per core:"), nodeInfo[7])
                    print "%-20s %s" % (_("NUMA cell(s):"), nodeInfo[4])
                    print "%-20s %lu kB" % (_("Memory Size:"),
                                            (float)(nodeInfo[1]) * 1024)

                if opts.all is True or opts.list is True:
                    """ Show dom list """
                    print ""
                    print "## Domain List"
                    state_flags = [
                        "no state",  # VIR_DOMAIN_NOSTATE
                        "running",  # VIR_DOMAIN_RUNNING
                        "idle",  # VIR_DOMAIN_BLOCKED
                        "paused",  # VIR_DOMAIN_PAUSED
                        "in shutdown",  # VIR_DOMAIN_SHUTDOWN
                        "shut off",  # VIR_DOMAIN_SHUTOFF
                        "crashed",  # VIR_DOMAIN_CRASHED
                    ]
                    #print "%3s %-20s %s" %(_("Id"), _("Name"), _("State"))
                    #print "----------------------------------"
                    print "%3s %-20s %-12s %-37s %-10s %-12s %-12s %-3s %-12s" % (
                        _("Id"),
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                        _("MaxMem"),
                        _("Memory"),
                        _("Vcpus"),
                        _("CPUTime"),
                    )
                    print "---------------------------------------------------------------------------"

                    domains_ids = conn.listDomainsID()
                    for id in domains_ids:
                        dom = conn.lookupByID(id)
                        name = dom.name()
                        domID = id
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                "-", name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                domID, name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])

                    defined_domains = conn.listDefinedDomains()
                    for name in defined_domains:
                        dom = conn.lookupByName(name)
                        #print dom.memoryStats()
                        domID = dom.ID()
                        domInfo = dom.info()
                        domUUID = dom.UUIDString()
                        domAutostart = dom.autostart()
                        if domAutostart == True:
                            locale_domAutostart = _("enable")
                        else:
                            locale_domAutostart = _("disable")
                        state = domInfo[0]
                        if domID == -1:
                            #print "%3s %-20s %s" %("-", name, state_flags[state])
                            print "%3s %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                "-", name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])
                        else:
                            #print "%3d %-20s %s" %(domID, name, state_flags[state])
                            print "%3d %-20s %-12s %-37s %-10s %-12ld %-12ld %-3d %-12ld" % (
                                domID, name, state_flags[state], domUUID,
                                locale_domAutostart, domInfo[1], domInfo[2],
                                domInfo[3], domInfo[4])

                if opts.all is True or opts.netlist is True:
                    """ Show net list """
                    print ""
                    print "## Network List"
                    #print "%-20s %-10s %-10s" %(_("Name"), _("State"), _("Autostart"))
                    #print "-----------------------------------------"
                    print "%-20s %-10s %-37s %-10s" % (
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                    )
                    print "--------------------------------------------------------------------------"
                    networks = conn.listNetworks()
                    for name in networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Active"), uuid, locale_autostart)

                    defined_networks = conn.listDefinedNetworks()
                    for name in defined_networks:
                        net = conn.networkLookupByName(name)
                        uuid = net.UUIDString()
                        autostart = net.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Inactive"), uuid, locale_autostart)

                if opts.all is True or opts.poollist is True:
                    """ Show pool list """
                    #taizoa
                    print ""
                    print "## Pool List"
                    print "%-20s %-10s %-37s %-10s" % (
                        _("Name"),
                        _("State"),
                        _("UUID"),
                        _("Autostart"),
                    )
                    print "--------------------------------------------------------------------------"
                    pools = conn.listStoragePools()
                    for name in pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Active"), uuid, locale_autostart)

                    defined_pools = conn.listDefinedStoragePools()
                    for name in defined_pools:
                        pool = conn.storagePoolLookupByName(name)
                        uuid = pool.UUIDString()
                        autostart = pool.autostart()
                        if autostart == True:
                            locale_autostart = _("yes")
                        else:
                            locale_autostart = _("no")

                        print "%-20s %-10s %-37s %-10s" % (
                            name, _("Inactive"), uuid, locale_autostart)

            except:
                pass

        if opts.all is True:
            """ Show available uris """
            print ""
            print "## Available URIs"
            for mech, uri in available_virt_uris().iteritems():
                print uri
            """ Show available mechs """
            print ""
            print "## Available mechanisms"
            for mech in available_virt_mechs():
                print mech
            """ Show installed packages """
            print ""
            print "## Installed packages"
            (rc, res) = execute_command([
                "rpm", "-qa",
                '--queryformat=%{NAME}\t%{VERSION}\t%{RELEASE}\t%{INSTALLTIME}\t%{BUILDHOST}\n'
            ])
            if rc == 0:
                print "%-25s %-10s %-10s %-20s" % (
                    _("Name"),
                    _("Version"),
                    _("Release"),
                    _("InstallTime"),
                )
                print "------------------------------------------------------------------"
                p = re.compile("hde\.co\.jp")
                output = []
                for aline in res:
                    arr = aline.split("\t")
                    if p.search(arr[4]):
                        str = "%-25s %-10s %-10s %-20s" % (
                            arr[0],
                            arr[1],
                            arr[2],
                            time.strftime("%Y-%m-%d %H:%M:%S",
                                          time.localtime(float(arr[3]))),
                        )
                        output.append(str)
                print "\n".join(sorted(output))

        finish_msg = _("Completed on %s") % time.strftime(
            "%Y/%m/%d %H:%M:%S", time.localtime())
        print ""
        print "# " + finish_msg

        return True
Ejemplo n.º 12
0
    def onboot(self,flag=None,runlevel=None):
        """
        <comment-ja>
        制御対象サービスのマシン起動時の起動状態の有効/無効の切り替えを行う。
        または、その状態を取得する。
        @param self: -
        @param string flag 指定なし:状態を取得する
                           True    :起動時有効にする
                           False   :起動時無効にする
        @return boolean    True :状態取得なら起動時有効、起動時切替なら成功
                           False:状態取得なら起動時有効、起動時切替なら成功
        </comment-ja>
        <comment-en>
        constructor of class
        @param self: The object pointer
        @return: none
        </comment-en>
        """
        retval = False

        if flag is not None and flag is not True and flag is not False:
            raise Exception("Invalid argument.")

        if os.path.exists(self.service_script) and is_executable(self.service_script):
            script_name = os.path.basename(self.service_script)

            old_lang = os.environ["LANG"]
            os.environ["LANG"] = "C"

            if flag is None:
                command = "%s --list %s" % (self.command_chkconfig,script_name,)
                command_args = command.split()
                (ret,res) = execute_command(command_args)

                if runlevel is None:
                    runlevel = self.runlevel
                try:
                    m = re.search("[ \t]+%s:on[ \t]+" % runlevel ,res[0])
                    if m:
                        retval = True
                except:
                    pass

            else:
                if flag is True:
                    on_or_off = "on"
                else:
                    on_or_off = "off"
                if runlevel is None:
                    command = "%s %s %s" % (self.command_chkconfig,script_name,on_or_off)
                else:
                    command = "%s --level %s %s %s" % (self.command_chkconfig,runlevel,script_name,on_or_off)

                command_args = command.split()
                (ret,res) = execute_command(command_args)
                if ret == 0:
                    retval = True

            os.environ["LANG"] = old_lang

        else:
            message = "Error: '%s' not found." % (self.service_script,)
            self.error_msg.append(message)

        return retval