Beispiel #1
0
    def __update_control_list(self, datastore, vmname, pdu, port):
        has_datastore = False
        for node_list in self.__nodes_control_list:
            if node_list.has_key(datastore):
                node_found = False
                for node_info in node_list[datastore]:
                    if node_info['node_name'] == vmname:
                        node_info['control_pdu'] = pdu
                        node_info['control_port'] = port
                        node_found = True

                if node_found is False:
                    node_info = {}
                    node_info['node_name'] = vmname
                    node_info['control_pdu'] = pdu
                    node_info['control_port'] = port
                    node_list[datastore].append(node_info)

                has_datastore = True

        if has_datastore is False:
            vm_list = {}
            vm_list[datastore] = []
            ni = {}
            ni['node_name'] = vmname
            ni['control_pdu'] = pdu
            ni['control_port'] = port
            vm_list[datastore].append(ni)
            self.__nodes_control_list.append(vm_list)

        logger.info("Updated. nodes control list: {0}".
                    format(self.__nodes_control_list))
Beispiel #2
0
    def main_loop(self):
        rlist = []
        rlist.append(self.__pipe.inform)
        timeout = 10
        print "Total threads: {0}".format(threading.activeCount())
        try:
            while self.__running:
                readable, _, _ = select.select(rlist, [], [], timeout)
                if not readable:
                    continue

                if self.__pipe.inform in readable:
                    try:
                        message = self.__pipe.read(256)
                    except OSError, exc:
                        logger.warn("[Error %d] appeared at reading pipe" %
                                    exc.errno)
                        continue

                    if len(message) == 0:
                        continue

                    pdu_id = message.split()[0].split('.')[-2]
                    pdu_index = self.to_index(int(pdu_id))
                    logger.info("Assign message to pdu {0}".format(pdu_id))
                    self.__pdus[pdu_index].handle_message(message)
        except KeyboardInterrupt:
            logger.error("Break by user.")
        except Exception, ex:
            logger.error("{0}: {1}".format(sys._getframe().f_code.co_name, ex))
Beispiel #3
0
    def send_command(self, cmd):
        logger.info("Executing command: {0}".format(cmd))
        if self.transport is None or self.transport.is_active() is False:
            self.reconnect()
            if self.transport is None or self.transport.is_active() is False:
                logger.error("Connection not established failed.")
                return -1, None

        try:
            session = self.transport.open_session()
            session.set_combine_stderr(True)
            session.get_pty()
            session.invoke_shell()
            if session.send_ready():
                index = 0
                input_data = self.__fix_indata(cmd)
                if index < len(input_data):
                    data = input_data[index] + '\n'
                    index += 1
                    session.send(data)
            else:
                logger.warn("session is not ready for send")
        except paramiko.SSHException as ex:
            logger.error("Exception for command '{0}: {1}'".format(cmd, ex))
            session.close()
            return -1, None
        output = self.poll(session)
        status = session.recv_exit_status()
        # send quit to notify server shutdown the channel
        session.send("quit\n")
        logger.info("Returned status {0}".format(status))
        session.close()
        return status, output
Beispiel #4
0
    def send_command(self, cmd):
        logger.info("Executing command: {0}".format(cmd))
        if self.transport is None or self.transport.is_active() is False:
            self.reconnect()
            if self.transport is None or self.transport.is_active() is False:
                logger.error("Connection not established failed.")
                return -1, None

        try:
            session = self.transport.open_session()
            session.set_combine_stderr(True)
            session.get_pty()
            session.invoke_shell()
            if session.send_ready():
                index = 0
                input_data = self.__fix_indata(cmd)
                if index < len(input_data):
                    data = input_data[index] + '\n'
                    index += 1
                    session.send(data)
            else:
                logger.warn("session is not ready for send")
        except paramiko.SSHException as ex:
            logger.error("Exception for command '{0}: {1}'".format(cmd, ex))
            session.close()
            return -1, None
        output = self.poll(session)
        status = session.recv_exit_status()
        # send quit to notify server shutdown the channel
        session.send("quit\n")
        logger.info("Returned status {0}".format(status))
        session.close()
        return status, output
Beispiel #5
0
    def update_snmprec_file(self, oid, val):
        old_file = os.path.join(self.config_instance.snmp_data_dir,
                                "public.snmprec")
        new_file = os.path.join(self.config_instance.snmp_data_dir,
                                "new.snmprec")
        logger.info("update oid %s, val %s" % (oid, str(val)))
        # open file
        try:
            old_fdh = open(old_file, 'r')
            new_fdh = open(new_file, 'w')
            while True:
                line = old_fdh.readline()
                if not line:
                    break
                record_list = line.strip(os.linesep).split('|')
                if record_list[0] == oid:
                    record_list[2] = val
                    new_line = '|'.join(["%s" % x for x in record_list])
                    new_fdh.write(new_line + os.linesep)
                else:
                    new_fdh.write(line)
        except IOError as e:
            logger.error(
                "Exception in updating snmprec file, exception: {}".format(e))
            return

        new_fdh.close()
        old_fdh.close()
        os.rename(new_file, old_file)
Beispiel #6
0
    def update_snmprec_file(self, oid, val):
        old_file = os.path.join(self.config_instance.snmp_data_dir,
                                "public.snmprec")
        new_file = os.path.join(self.config_instance.snmp_data_dir,
                                "new.snmprec")
        logger.info("update oid %s, val %s" % (oid, str(val)))
        # open file
        try:
            old_fdh = open(old_file, 'r')
            new_fdh = open(new_file, 'w')
            while True:
                line = old_fdh.readline()
                if not line:
                    break
                record_list = line.strip(os.linesep).split('|')
                if record_list[0] == oid:
                    record_list[2] = val
                    new_line = '|'.join(["%s" % x for x in record_list])
                    new_fdh.write(new_line + os.linesep)
                else:
                    new_fdh.write(line)
        except IOError as e:
            logger.error("Exception in updating snmprec file, exception: {}".
                         format(e))
            return

        new_fdh.close()
        old_fdh.close()
        os.rename(new_file, old_file)
Beispiel #7
0
    def __execute_command(self, cmd):
        '''
        Excute command
        '''
        if self.__ssh.connected() is False:
            logger.info("Connection is not connected")

        return self.__ssh.exec_command(cmd)
Beispiel #8
0
    def __execute_command(self, cmd):
        '''
        Excute command
        '''
        if self.__ssh.connected() is False:
            logger.info("Connection is not connected")

        return self.__ssh.exec_command(cmd)
Beispiel #9
0
    def connect(self, timeout=30):
        logger.info("Connecting {username}@{host}:{port}".format(
            username=self.host_username,
            host=self.host_ip,
            port=self.host_port))
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        return self.reconnect(timeout)
Beispiel #10
0
def signal_handler(signum, frame):
    logger.info("Signal {0} receivced.".format(signum))
    if vpdu_handler:
        vpdu_handler.stop()

    if sim_serv:
        sim_serv.stop()
    logger.info("vPDU exit.")
    sys.exit(0)
Beispiel #11
0
    def handle_outlet(self, args):
        '''
        1. Get current outlet state
        2. Get the current outlet action
        '''
        # self.logger.info("handle outlet {0}/{1}".format(outlet, self.pdu))
        outlet = args[0]
        action = args[1]
        logger.info("handle outlet {0}/{1}, action: {2}"
                    .format(outlet, self.pdu, self.actions[int(action)]))
        vmname = self.__node_control_handler.get_node_name(1, int(outlet))
        if vmname is None:
            self.set_outlet_field(self.outlet_action_oid_offset, outlet, 0)
            logger.error("No virtual node found for outlet {0}".format(outlet))
            return

        datastore = self.__node_control_handler.get_node_datastore(vmname)
        if datastore is None:
            self.set_outlet_field(self.outlet_action_oid_offset, outlet, 0)
            logger.error("No datastore found for virtual node {0}"
                         .format(vmname))
            return

        # action = self.get_outlet_field(self.outlet_action_oid_offset, outlet)
        state = self.get_outlet_field(self.outlet_state_oid_offset, outlet)
        if self.actions[int(action)] == 'none' or \
                self.actions[int(action)] == self.states[int(state)]:
            logger.warn("No need to execute the action: {}"
                        .format(self.actions[int(action)]))
            return

        # restore the action default to "none"
        if self.actions[int(action)] == 'on':
            # 'on' state
            self.set_outlet_field(self.outlet_state_oid_offset, outlet, 5)
            status = self.__node_control_handler.power_on_node(datastore,
                                                               vmname)
        elif self.actions[int(action)] == 'off':
            # 'off' state
            self.set_outlet_field(self.outlet_state_oid_offset, outlet, 4)
            status = self.__node_control_handler.power_off_node(datastore,
                                                                vmname)
        elif self.actions[int(action)] == 'reboot':
            # 'off' state
            self.set_outlet_field(self.outlet_state_oid_offset, outlet, 8)
            status = self.__node_control_handler.reboot_node(datastore, vmname)
            # 'on' state
            self.set_outlet_field(self.outlet_state_oid_offset, outlet, 5)
        else:
            logger.error("Unknown action: {0}".format(action))
            return

        if status != 0:
            logger.error("Failed to {0} virtual node."
                         .format(self.actions[int(action)]))
            return
        self.set_outlet_field(self.outlet_action_oid_offset, outlet, 0)
Beispiel #12
0
    def connect(self, timeout=30):
        logger.info("Connecting {username}@{host}:{port}"
                    .format(username=self.host_username,
                            host=self.host_ip,
                            port=self.host_port))
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        return self.reconnect(timeout)
Beispiel #13
0
    def stop(self):
        # kill the service if already run
        pid = self.getpid()
        if pid < 0:
            logger.info("snmpsim service is not running.")
            return

        os.kill(pid, signal.SIGTERM)
        logger.info("Snmpsim service [%d] exit." % pid)
Beispiel #14
0
def signal_handler(signum, frame):
    logger.info("Signal {0} receivced.".format(signum))
    if vpdu_handler:
        vpdu_handler.stop()

    if sim_serv:
        sim_serv.stop()
    logger.info("vPDU exit.")
    sys.exit(0)
Beispiel #15
0
 def handle_message(self, message):
     logger.info("Got new message {0}".format(message))
     oid = message.split()[0]
     outlet = oid.split('.')[-1]
     value = message.split()[1]
     if oid.startswith(self.outlet_action_oid_offset):
         self.add_task("handle outlet {0}".format(outlet),
                       self.handle_outlet, int(outlet), value)
     else:
         logger.warn("{0} is not handled now.".format(message))
Beispiel #16
0
def signal_handler(signum, frame):
    vpdu_pid = get_vpdu_pid()
    if vpdu_pid > 0:
        os.kill(vpdu_pid, signal.SIGTERM)

    snmpsim_pid = SNMPSimService.getpid()
    if snmpsim_pid > 0:
        os.kill(snmpsim_pid, signal.SIGTERM)

    logger.info("Exit server.")
    sys.exit(0)
Beispiel #17
0
 def add_task(self, task_name, func, *args):
     '''
     tasks: (fun, args)
     '''
     task_name = "{task_name}-ID-{task_id}".\
         format(task_name=task_name, task_id=self.__task_id)
     self.__task_id += 1
     logger.info("Add task: {yellow}{task_name}{normal} for pdu {pdu}".
                 format(yellow=colors.YELLOW, task_name=task_name,
                        normal=colors.NORMAL, pdu=self.pdu))
     self.__tasks_queue.put((task_name, func, args))
Beispiel #18
0
 def handle_message(self, message):
     oid = message.split()[0]
     outlet = oid.split('.')[-1]
     value = message.split()[1]
     logger.info("Handle message {0}".format(message))
     if message.startswith(self.pduouton_oid_offset):
         self.add_task("handle_outlet-{0}".format(outlet),
                       self.handle_outlet, int(outlet), value)
     elif message.startswith(self.pduoutpwd_oid_offset):
         self.add_task("handle_password-{0}".format(outlet),
                       self.handle_password, int(outlet), value)
     else:
         logger.warn("{0} is not handled now.".format(message))
Beispiel #19
0
    def handle_outlet(self, args):
        outlet = args[0]
        action = args[1]

        logger.info("handle outlet {0}/{1}, action: {2}".
                    format(outlet, self.pdu, self.actions[int(action)]))

        on_offset = self.pduouton_oid_offset + "." + str(self.to_pdu(self.pdu))
        action_in_oid = self.extract(self.get_outlet_field(on_offset, outlet))

        logger.warn("action: {0}, action_in_oid: {1}".
                    format(self.actions[int(action)],
                           self.actions[int(action_in_oid)]))

        vmname = self.__node_control_handler.get_node_name(int(self.pdu),
                                                           int(outlet))
        if vmname is None:
            logger.error("No virtual node found for outlet {0}".format(outlet))
            return

        datastore = self.__node_control_handler.get_node_datastore(vmname)
        if datastore is None:
            logger.error("No datastore found for virtual node {0}".
                         format(vmname))
            return

        # Make sure the action as the last one
        logger.info("last action: {0}, current action: {1}".
                    format(self.action_list[int(outlet) - 1],
                           self.actions[int(action)]))
        if self.action_list[int(outlet) - 1] == self.actions[int(action)]:
            logger.warn("No need to execute action for {0}/{1}".
                        format(outlet, self.pdu))
            return

        if self.actions[int(action)] == 'on':
            status = self.__node_control_handler.power_on_node(datastore,
                                                               vmname)
        elif self.actions[int(action)] == 'off':
            status = self.__node_control_handler.power_off_node(datastore,
                                                                vmname)
        elif self.actions[int(action)] == 'reboot':
            status = self.__node_control_handler.reboot(datastore, vmname)
        else:
            logger.error("Unknown action: {0}".format(action))

        if status != 0:
            logger.error("Failed to {0} virtual node.".
                         format(self.actions[int(action)]))
            return
        self.action_list[int(outlet) - 1] = self.actions[int(action)]
Beispiel #20
0
def start_vpdu():
    vpdu_command = "vpdud.py"
    if not os.path.exists("/usr/bin/vpdud.py") or \
            not os.path.exists("/usr/local/bin"):
        vpdu_command = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                    "vpdud.py")

    command = vpdu_command + " " + \
        "-d --logging-method=file:/var/log/vpdud/vpdud.log"
    logger.info(command)
    retcode = subprocess.call(command, shell=True)
    # wait service started
    time.sleep(10)
    return retcode
Beispiel #21
0
 def reboot_node(self, *args):
     '''
     Reboot VM
     '''
     datastore = args[0]
     vmname = args[1]
     logger.info("Reboot " + datastore + "/" + vmname + "...")
     status = self.power_off_node(datastore, vmname)
     if status != 0:
         return status
     # sleep 2 seconds
     time.sleep(2)
     status = self.power_on_node(datastore, vmname)
     return status
Beispiel #22
0
 def reboot_node(self, *args):
     '''
     Reboot VM
     '''
     datastore = args[0]
     vmname = args[1]
     logger.info("Reboot " + datastore + "/" + vmname + "...")
     status = self.power_off_node(datastore, vmname)
     if status != 0:
         return status
     # sleep 2 seconds
     time.sleep(2)
     status = self.power_on_node(datastore, vmname)
     return status
Beispiel #23
0
 def add_task(self, task_name, func, *args):
     '''
     tasks: (fun, args)
     '''
     task_name = "{task_name}-ID-{task_id}".\
         format(task_name=task_name, task_id=self.__task_id)
     self.__task_id += 1
     logger.info(
         "Add task: {yellow}{task_name}{normal} for pdu {pdu}".format(
             yellow=colors.YELLOW,
             task_name=task_name,
             normal=colors.NORMAL,
             pdu=self.pdu))
     self.__tasks_queue.put((task_name, func, args))
Beispiel #24
0
    def handle_outlet(self, args):
        outlet = args[0]
        action = args[1]

        logger.info("handle outlet {0}/{1}, action: {2}".format(
            outlet, self.pdu, self.actions[int(action)]))

        on_offset = self.pduouton_oid_offset + "." + str(self.to_pdu(self.pdu))
        action_in_oid = self.extract(self.get_outlet_field(on_offset, outlet))

        logger.warn("action: {0}, action_in_oid: {1}".format(
            self.actions[int(action)], self.actions[int(action_in_oid)]))

        vmname = self.__node_control_handler.get_node_name(
            int(self.pdu), int(outlet))
        if vmname is None:
            logger.error("No virtual node found for outlet {0}".format(outlet))
            return

        datastore = self.__node_control_handler.get_node_datastore(vmname)
        if datastore is None:
            logger.error(
                "No datastore found for virtual node {0}".format(vmname))
            return

        # Make sure the action as the last one
        logger.info("last action: {0}, current action: {1}".format(
            self.action_list[int(outlet) - 1], self.actions[int(action)]))
        if self.action_list[int(outlet) - 1] == self.actions[int(action)]:
            logger.warn("No need to execute action for {0}/{1}".format(
                outlet, self.pdu))
            return

        if self.actions[int(action)] == 'on':
            status = self.__node_control_handler.power_on_node(
                datastore, vmname)
        elif self.actions[int(action)] == 'off':
            status = self.__node_control_handler.power_off_node(
                datastore, vmname)
        elif self.actions[int(action)] == 'reboot':
            status = self.__node_control_handler.reboot(datastore, vmname)
        else:
            logger.error("Unknown action: {0}".format(action))

        if status != 0:
            logger.error("Failed to {0} virtual node.".format(
                self.actions[int(action)]))
            return
        self.action_list[int(outlet) - 1] = self.actions[int(action)]
Beispiel #25
0
 def handle_message(self, message):
     oid = message.split()[0]
     outlet = oid.split('.')[-1]
     value = message.split()[1]
     logger.info("Handle message {0}".format(message))
     if message.startswith(self.pduouton_oid_offset):
         self.add_task("handle_outlet-{0}".
                       format(outlet), self.handle_outlet,
                       int(outlet), value)
     elif message.startswith(self.pduoutpwd_oid_offset):
         self.add_task("handle_password-{0}".
                       format(outlet), self.handle_password,
                       int(outlet), value)
     else:
         logger.warn("{0} is not handled now.".format(message))
Beispiel #26
0
def write_password(pdu, port, password):
    _content = ''
    try:
        matched = False
        password_file = config.get_conf_instance().password_file
        fd = open(password_file, 'r+')
        lines = fd.readlines()
        fd.close()
        for line in lines:
            # Ignore blank line
            if line == os.linesep:
                _content += line
                continue

            # Ignore comments which begins with '#'
            result_obj = re.search(r"^#.*", line)
            if result_obj:
                _content += line
                continue

            l = line.split(':')
            # If the password is already in configuration file, then update it.
            if pdu == int(l[1]) and port == int(l[2]):
                matched = True
                # Update password
                line = ':'.join([str(time.time()), str(pdu),
                                 str(port), str(password)])
                line += os.linesep
                logger.info("Update password %s for PDU %d port %d" %
                            (password, pdu, port))
            _content += line

        # If the pdu and port have not been assigned a password,
        # then added the password
        if not matched:
            new_line = ':'.join([str(time.time()), str(pdu),
                                 str(port), str(password)])
            new_line += os.linesep
            _content = _content + new_line
            logger.info("Add password %s for PDU %d port %d" %
                        (password, pdu, port))

        # Write the password settings back to the configuration file
        fd = open(config.get_conf_instance().password_file, 'w')
        fd.writelines(_content)
        fd.close()
    except IOError as e:
        logger.error("Error in open password file.exception: {}".format(e))
Beispiel #27
0
 def run(self):
     while self.__running:
         try:
             task_name, func, args = self.__tasks_queue.get()
             logger.info("Running task ... {peachblow}{task_name}{normal} \
                         on thread {threadname}".
                         format(peachblow=colors.PEACHBLOW,
                                task_name=task_name,
                                normal=colors.NORMAL,
                                threadname=self.getName()))
             func(args)
             self.__tasks_queue.task_done()
             logger.info("{cyan}{task_name}{normal} Done".
                         format(cyan=colors.CYAN,
                                task_name=task_name,
                                normal=colors.NORMAL))
         except Exception, ex:
             logger.error("{0}: {1}".
                          format(sys._getframe().f_code.co_name, ex))
Beispiel #28
0
 def run(self):
     while self.__running:
         try:
             task_name, func, args = self.__tasks_queue.get()
             logger.info("Running task ... {peachblow}{task_name}{normal} \
                         on thread {threadname}".format(
                 peachblow=colors.PEACHBLOW,
                 task_name=task_name,
                 normal=colors.NORMAL,
                 threadname=self.getName()))
             func(args)
             self.__tasks_queue.task_done()
             logger.info("{cyan}{task_name}{normal} Done".format(
                 cyan=colors.CYAN,
                 task_name=task_name,
                 normal=colors.NORMAL))
         except Exception, ex:
             logger.error("{0}: {1}".format(sys._getframe().f_code.co_name,
                                            ex))
Beispiel #29
0
 def __init__(self):
     '''
     Constructor
     '''
     super(VMwareHandler, self).__init__()
     self.__host_ip = None
     self.__username = None
     self.__password = None
     self.set_esxi_host_info()
     if self.__host_ip is not None:
         self.__ssh = sshclient.SSH(self.__host_ip, self.__username,
                                    self.__password)
         self.__ssh.connect()
         if self.__ssh.connected() is False:
             logger.error("Connection error for {0}@{1}".
                          format(self.__username, self.__host_ip))
         else:
             logger.info("Connection ok for {0}@{1}".
                         format(self.__username, self.__host_ip))
     else:
         logger.warn("ESXi is not set in configuration file.")
Beispiel #30
0
 def __init__(self):
     '''
     Constructor
     '''
     super(VMwareHandler, self).__init__()
     self.__host_ip = None
     self.__username = None
     self.__password = None
     self.set_esxi_host_info()
     if self.__host_ip is not None:
         self.__ssh = sshclient.SSH(self.__host_ip, self.__username,
                                    self.__password)
         self.__ssh.connect()
         if self.__ssh.connected() is False:
             logger.error("Connection error for {0}@{1}".format(
                 self.__username, self.__host_ip))
         else:
             logger.info("Connection ok for {0}@{1}".format(
                 self.__username, self.__host_ip))
     else:
         logger.warn("ESXi is not set in configuration file.")
Beispiel #31
0
    def start(self):
        if not os.path.exists('/usr/bin/snmpsimd.py') \
                and not os.path.exists('/bin/snmpsimd.py') \
                and not os.path.exists('/usr/local/bin/snmpsimd.py'):
            logger.error("snmpsimd.py does not exist!")
            return -1

        if self.__alive():
            self.stop()

        if not os.path.exists("/var/run/snmpsim"):
            os.mkdir("/var/run/snmpsim")

        if not os.path.exists("/var/log/snmpsim"):
            os.mkdir("/var/log/snmpsim")

        data_dir = self.__config_instance.snmp_data_dir
        db_path = os.path.join(data_dir, self.__config_instance.db_file)

        args_list = ["snmpsimd.py"]
        endpoint_param = "--agent-udpv4-endpoint=0.0.0.0"
        args_list.append(endpoint_param)
        process_user = "******"
        args_list.append(process_user)
        process_group = "--process-group=root"
        args_list.append(process_group)
        logging_option = "--logging-method=file:/var/log/snmpsim/snmpsimd.log"
        args_list.append(logging_option)
        pid_option = "--pid-file=" + snmpsim_pid_file
        args_list.append(pid_option)
        daemonize_option = "--daemonize"
        args_list.append(daemonize_option)
        data_dir_option = "--data-dir=" + data_dir
        args_list.append(data_dir_option)
        if self.__db_type == "SQLITE":
            variation_modules_dir = "--variation-modules-dir=" + \
                self.__config_instance.variation_modules_dir
            args_list.append(variation_modules_dir)
            sql_option = "--variation-module-options=sql:dbtype:sqlite3,database:" + db_path
            args_list.append(sql_option)
        elif self.__db_type == "WRITECACHE":
            writecache_option = "--variation-module-options=writecache:file:" + db_path
            args_list.append(writecache_option)
        else:
            return -1

        logger.info("Start snmpsimd service for {0}.".format(self.__pdu_name))
        logger.info(' '.join(args_list))
        retcode = subprocess.call(args_list)
        if retcode != 0:
            return -1

        time.sleep(1)
        pid = self.getpid()
        if pid < 0:
            logger.error("Failed to start snmpsim service!")
            return -1

        logger.info("Succeed to start snmpsim service, pid: %d." % pid)
        return 0
Beispiel #32
0
    def poll(self, session, timeout=30, indata=[]):
        session.setblocking(0)
        index = 0
        timeout_flag = False
        start = time.mktime(datetime.datetime.now().timetuple())
        output = ''
        while True:
            if session.recv_ready():
                data = session.recv(self.buffer_size)
                output += data

                if session.send_ready():
                    if index < len(indata):
                        data = indata[index] + '\n'
                        index += 1
                        logger.info("sending {0} bytes data".format(len(data)))
                        session.send(data)

            if session.exit_status_ready():
                break

            now = time.mktime(datetime.datetime.now().timetuple())
            delta = now - start

            if delta > timeout:
                timeout_flag = True
                break

            time.sleep(0.5)

        if session.recv_ready():
            data = session.recv(self.buffer_size)
            output += data
            logger.info("1: Got {0} bytes, total {1} bytes".
                        format(len(data), len(output)))

        if timeout_flag:
            output += '\nError: timeout after {0} seconds\n'.format(timeout)

        return output
Beispiel #33
0
def read_password(pdu, port):
    try:
        password_file = config.get_conf_instance().password_file
        fd = open(password_file, 'r')
        while True:
            line = fd.readline()
            if not line:
                break

            # Ignore blank line
            if line == os.linesep:
                continue

            # Ignore comments which begins with "#"
            result_obj = re.search(r"^#.*", line)
            if result_obj:
                continue

            # The format should be:
            # <timestamp> <pdu number> <pdu port> <password>
            l = line.strip(os.linesep).split(':')
            try:
                lpdu = int(l[1])
                lport = int(l[2])
            except ValueError:
                logger.error("Converting int or float error from string.")
                return ""

            password = l[3]
            if lpdu == pdu and lport == port:
                fd.close()
                logger.info("Return password %s for PDU %d port %d" %
                            (password, pdu, port))
                return password
        fd.close()
        logger.error("Not found password for PDU %d port %d" % (pdu, port))
        return ""
    except IOError as e:
        logger.error("Error in open password file.exception: {}".format(e))
        return ""
Beispiel #34
0
    def poll(self, session, timeout=30, indata=[]):
        session.setblocking(0)
        index = 0
        timeout_flag = False
        start = time.mktime(datetime.datetime.now().timetuple())
        output = ''
        while True:
            if session.recv_ready():
                data = session.recv(self.buffer_size)
                output += data

                if session.send_ready():
                    if index < len(indata):
                        data = indata[index] + '\n'
                        index += 1
                        logger.info("sending {0} bytes data".format(len(data)))
                        session.send(data)

            if session.exit_status_ready():
                break

            now = time.mktime(datetime.datetime.now().timetuple())
            delta = now - start

            if delta > timeout:
                timeout_flag = True
                break

            time.sleep(0.5)

        if session.recv_ready():
            data = session.recv(self.buffer_size)
            output += data
            logger.info("1: Got {0} bytes, total {1} bytes".format(
                len(data), len(output)))

        if timeout_flag:
            output += '\nError: timeout after {0} seconds\n'.format(timeout)

        return output
Beispiel #35
0
    def exec_command(self, cmd, indata=None, timeout=30):
        logger.info("Executing command: {0}".format(cmd))
        if self.transport is None or self.transport.is_active() is False:
            self.reconnect()
            if self.transport is None or self.transport.is_active() is False:
                logger.error("connection failed.")
                return -1, None

        input_data = self.__fix_indata(indata)

        try:
            session = self.transport.open_session()
            session.set_combine_stderr(True)
            session.get_pty()
            session.exec_command(cmd)
        except paramiko.SSHException as ex:
            logger.error("Exception for command '{0}: {1}'".format(cmd, ex))
            session.close()
            return -1, None
        output = self.poll(session, timeout, input_data)
        status = session.recv_exit_status()
        logger.info("Returned status {0}".format(status))
        session.close()
        return status, output
Beispiel #36
0
    def exec_command(self, cmd, indata=None, timeout=30):
        logger.info("Executing command: {0}".format(cmd))
        if self.transport is None or self.transport.is_active() is False:
            self.reconnect()
            if self.transport is None or self.transport.is_active() is False:
                logger.error("connection failed.")
                return -1, None

        input_data = self.__fix_indata(indata)

        try:
            session = self.transport.open_session()
            session.set_combine_stderr(True)
            session.get_pty()
            session.exec_command(cmd)
        except paramiko.SSHException as ex:
            logger.error("Exception for command '{0}: {1}'".format(cmd, ex))
            session.close()
            return -1, None
        output = self.poll(session, timeout, input_data)
        status = session.recv_exit_status()
        logger.info("Returned status {0}".format(status))
        session.close()
        return status, output
Beispiel #37
0
    def power_off_node(self, *args):
        '''
        Power off VM with ESXi CLI
        '''
        datastore = args[0]
        vmname = args[1]
        logger.info("Power off " + datastore + "/" + vmname + "...")
        command = self.__build_command(datastore, vmname, "getstate")
        status, ret = self.__execute_command(command)
        if status != 0:
            logger.error("Command failed, status : {0}".format(status))
            return status

        if "off" in ret:
            logger.info("%s already is off." % vmname)
            return 0

        command = self.__build_command(datastore, vmname, "off")
        status, ret = self.__execute_command(command)
        if status != 0:
            logger.error("Command failed, status : {0}".format(status))
            return status
        logger.info(ret.strip())
        return 0
Beispiel #38
0
    def power_off_node(self, *args):
        '''
        Power off VM with ESXi CLI
        '''
        datastore = args[0]
        vmname = args[1]
        logger.info("Power off " + datastore + "/" + vmname + "...")
        command = self.__build_command(datastore, vmname, "getstate")
        status, ret = self.__execute_command(command)
        if status != 0:
            logger.error("Command failed, status : {0}".format(status))
            return status

        if "off" in ret:
            logger.info("%s already is off." % vmname)
            return 0

        command = self.__build_command(datastore, vmname, "off")
        status, ret = self.__execute_command(command)
        if status != 0:
            logger.error("Command failed, status : {0}".format(status))
            return status
        logger.info(ret.strip())
        return 0
Beispiel #39
0
        rlist.append(self.__pipe.inform)
        timeout = 10
        try:
            while self.__running:
                readable, _, _ = select.select(rlist, [], [], timeout)
                if not readable:
                    continue

                if self.__pipe.inform in readable:
                    try:
                        message = self.__pipe.read(256)
                    except OSError, exc:
                        logger.warn("[Error %d] appeared at reading pipe" %
                                    exc.errno)
                        continue

                    if len(message) == 0:
                        continue

                    self.handle_message(message)
        except KeyboardInterrupt:
            logger.error("Break by user.")
        except Exception, ex:
            logger.error("{0}: {1}".format(sys._getframe().f_code.co_name, ex))
        finally:
            logger.info("vSentry service exits.")
            self.__pipe.close()

    def stop(self):
        self.__running = False
Beispiel #40
0
def signal_handler(signum, frame):
    logger.info("Signal {0} receivced.".format(signum))
    if pdu_sim is not None and pdu_sim.is_alive():
        pdu_sim.stop()
    logger.info("vPDU exit.")
    sys.exit(0)
Beispiel #41
0
    def command_vpdu(self, params):
        '''[<start/stop/restart/status>]
        Control vpdu service and get vpdu service status.
        vpdu start   - Start vPDU and SNMP simulator service
        vpdu stop    - Stop vPDU and SNMP simulator service
        vpdu restart - Restart vPDU and SNMP simulator service
        vpdu status  - Get vPDU and SNMP simulator status
        '''
        if len(params) == 0:
            return

        global pdu_sim
        logger.info("Executing action: %s" % params[0])
        if params[0] == 'start':
            if pdu_sim.is_alive():
                self.writeresponse("%svpdu service [%d] is alredy running.%s"
                                   % (colors.GREEN, pdu_sim.pid, colors.NORMAL))
            else:
                pdu_sim = pdusim.pdusim.PDUSim()
                pdu_sim.set_daemon()
                pdu_sim.start()
                time.sleep(1)
                if pdu_sim.is_alive():
                    self.writeresponse("%svpdu service [%d] is started.%s"
                                    % (colors.GREEN, pdu_sim.pid, colors.NORMAL))
        elif params[0] == 'stop':
            if not pdu_sim.is_alive():
                self.writeresponse("%svpdu service is already stopped.%s"
                                   % (colors.GREEN, colors.NORMAL))
                return

            if pdu_sim.is_alive():
                pdu_sim.stop()

            time.sleep(1)
            if not pdu_sim.is_alive():
                self.writeresponse("%svpdu service is stopped.%s"
                                    % (colors.GREEN, colors.NORMAL))

        elif params[0] == 'restart':
            if pdu_sim.is_alive():
                pdu_sim.stop()

            # Wait 1 second for snmpsim exit, and then end then check again
            time.sleep(1)

            if pdu_sim:
                pdu_sim = pdusim.pdusim.PDUSim()
                pdu_sim.set_daemon()
                pdu_sim.start()
                time.sleep(1)
                if pdu_sim.is_alive():
                    self.writeresponse("%svpdu service [%d] is restarted.%s"
                                    % (colors.GREEN, pdu_sim.pid, colors.NORMAL))
                    logger.info("vpdu service [%d] is restarted." % pdu_sim.pid)
                    return
            logger.error("Cannot restart vpdu service.")
        elif params[0] == 'status':
            if pdu_sim.is_alive() is True:
               response = "%svpdu service [%d] is running.%s" % \
                        (colors.GREEN, pdu_sim.pid, colors.NORMAL)
               self.writeresponse(response)
               logger.info(response)
            else:
                if pdu_sim.is_alive() is False:
                    response = \
                        "%svpdu service is not running.%s" % (colors.RED,
                                                            colors.NORMAL)
                    self.writeresponse(response)
                    logger.info(response)
Beispiel #42
0
    def command_config(self, params):
        '''<esxi|pdu> [<list/update/add/delete> | <set/get>] [<param.1> ... < param.n>]

        configure vPDU
        ----------------------------------
        config pdu set <name>
        - set PDU name
        e.g.
        config pdu set hawk

        config pdu set database <database file>
        - set pdu database file name
        e.g.
        config pdu set database ipia.db

        config pdu set datadir <snmp data dir>
        - set snmp data directory name
        e.g.
        config pdu set datadir hawk

        config pdu list
        -list pdu configurations


        config esxi
        --------------------------------------
        config esxi list
         - list configuration

        config esxi update <option name> <value>
         - update configuration
         e.g.
            Update esxi ip address in configuration file, run below command:
            config esxi update host 10.62.59.124

            Update esxi host "username"
            config esxi update uesrname root

            Update esxi host "password"
            config esxi update password root

        config esxi add <host> <uesrname> <password>
         - add configuration
         e.g.
            Add an ESXi host information including ip, username and passowrd
            config esxi add 10.62.59.128 root 1234567

        config esxi delete
         - delete configuration
         e.g.
            Delete section "esxihost"
            config esxi delete esxihost

        Note: After update/add the configuration, please run 'config list' to
        be sure that the changes you made are correct.
        '''
        if len(params) == 0:
            return

        if params[0] == "pdu":
            if params[1] == 'set':
                if params[2] == 'name':
                    self.config_instance.pdu_name = params[3]
                elif params[2] == 'database':
                    self.config_instance.db_file = params[3]
                elif params[2] == 'datadir':
                    self.config_instance.snmp_data_dir = params[3]

                self.config_instance.update()
            elif params[1] == 'get':
                self.config_instance.init()
                table = Texttable()
                table.add_row(['name', self.config_instance.pdu_name])
                table.add_row(['database', self.config_instance.db_file])
                table.add_row(['snmp data dir',
                               self.config_instance.snmp_data_dir])
                table_str = table.draw()
                self.writeresponse(table_str)
                logger.info("\n" + table_str)
            elif params[1] == 'list':
                self.config_instance.init()
                table = Texttable()
                table.add_row(['pdu name', self.config_instance.pdu_name])
                table.add_row(['dbtype', self.config_instance.db_type])
                table.add_row(['database', self.config_instance.db_file])
                table.add_row(['snmpdata', self.config_instance.snmp_data_dir])
                table.add_row(['simfile', self.config_instance.sim_file])
                table_str = table.draw()
                self.writeresponse(table_str)
                logger.info("\n" + table_str)

            else:
                logger.error("Unknown command {0}".format(params[0]))
        elif params[0] == "esxi":
            if params[1] == "list":
                self.config_instance.init()
                esxi_info = self.config_instance.esxi_info
                if esxi_info is not None:
                    table = Texttable()
                    table.header(["esxi host", "username", "password"])
                    table.add_row([
                        get_color_string(bcolors.GREEN, esxi_info['host']),
                        get_color_string(bcolors.GREEN, esxi_info["username"]),
                        get_color_string(bcolors.GREEN, esxi_info['password'])
                    ])
                    table_str = table.draw()
                    self.writeresponse(table_str)
                    logger.info("\n" + table_str)
                    return
                else:
                    self.writeresponse("%sNo ESXi host info in configuration \
                                       file.%s" % (colors.RED, colors.NORMAL))
            elif params[1] == "update":
                if len(params[2:]) == 2:
                    esxi_info = self.config_instance.esxi_info
                    if esxi_info is not None:
                        esxi_info[params[2]] = params[3]
                        self.config_instance.update()
                    else:
                        self.writeresponse("%sNo %s found in configuration \
                            file.%s" % (colors.RED, params[1], colors.NORMAL))
            elif params[1] == "add":
                if len(params[2:]) != 3:
                    return

                if self.config_instance.esxi_info is None:
                    esxi_info = {}
                    logger.info("Adding esxi host: {0}, {1}, {2}"
                                .format(params[2], params[3], params[4]))
                    esxi_info['host'] = params[2]
                    esxi_info['username'] = params[3]
                    esxi_info['password'] = params[4]
                    self.config_instance.esxi_info = esxi_info
                    self.config_instance.update()
                else:
                    self.writeresponse("ESXi info already exists.")
            elif params[1] == "delete":
                if self.config_instance.esxi_info is not None:
                    self.config_instance.delete()
                else:
                    self.writeresponse("ESXi info already deleted.")
            else:
                self.writeresponse("unknown parameters.")
        else:
            self.writeresponse("unknown parameters: {0}.".format(params[0]))
Beispiel #43
0
    logger.initialize("pdusim", "stdout")
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "dh",
                                   ["daemonize", "help", "logging-method="])
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                usage()
                sys.exit(1)
            elif opt in ("-d", "--daemonize"):
                daemon = True
            elif opt == "--logging-method":
                logger.initialize("pdusim", *arg.split(':'))
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    if daemon:
        pdusim.common.daemon.daemonize(server_pid_file)

    logger.info("vPDU started")
    init_signal()
    pdu_sim = pdusim.pdusim.PDUSim()
    pdu_sim.set_daemon()
    pdu_sim.start()
    logger.info("PDU service PID: {}".format(pdu_sim.pid))

    logger.info("Server started")
    server = vPDUHandler()
    server.serve_forever()
Beispiel #44
0
    def command_vpdu(self, params):
        '''[<start/stop/restart/status>]
        Control vpdu service and get vpdu service status.
        vpdu start   - Start vPDU and SNMP simulator service
        vpdu stop    - Stop vPDU and SNMP simulator service
        vpdu restart - Restart vPDU and SNMP simulator service
        vpdu status  - Get vPDU and SNMP simulator status
        '''
        if len(params) == 0:
            return

        global pdu_sim
        logger.info("Executing action: %s" % params[0])
        if params[0] == 'start':
            if pdu_sim.is_alive():
                self.writeresponse("%svpdu service [%d] is alredy running.%s" %
                                   (colors.GREEN, pdu_sim.pid, colors.NORMAL))
            else:
                pdu_sim = pdusim.pdusim.PDUSim()
                pdu_sim.set_daemon()
                pdu_sim.start()
                time.sleep(1)
                if pdu_sim.is_alive():
                    self.writeresponse(
                        "%svpdu service [%d] is started.%s" %
                        (colors.GREEN, pdu_sim.pid, colors.NORMAL))
        elif params[0] == 'stop':
            if not pdu_sim.is_alive():
                self.writeresponse("%svpdu service is already stopped.%s" %
                                   (colors.GREEN, colors.NORMAL))
                return

            if pdu_sim.is_alive():
                pdu_sim.stop()

            time.sleep(1)
            if not pdu_sim.is_alive():
                self.writeresponse("%svpdu service is stopped.%s" %
                                   (colors.GREEN, colors.NORMAL))

        elif params[0] == 'restart':
            if pdu_sim.is_alive():
                pdu_sim.stop()

            # Wait 1 second for snmpsim exit, and then end then check again
            time.sleep(1)

            if pdu_sim:
                pdu_sim = pdusim.pdusim.PDUSim()
                pdu_sim.set_daemon()
                pdu_sim.start()
                time.sleep(1)
                if pdu_sim.is_alive():
                    self.writeresponse(
                        "%svpdu service [%d] is restarted.%s" %
                        (colors.GREEN, pdu_sim.pid, colors.NORMAL))
                    logger.info("vpdu service [%d] is restarted." %
                                pdu_sim.pid)
                    return
            logger.error("Cannot restart vpdu service.")
        elif params[0] == 'status':
            if pdu_sim.is_alive() is True:
                response = "%svpdu service [%d] is running.%s" % \
                         (colors.GREEN, pdu_sim.pid, colors.NORMAL)
                self.writeresponse(response)
                logger.info(response)
            else:
                if pdu_sim.is_alive() is False:
                    response = \
                        "%svpdu service is not running.%s" % (colors.RED,
                                                            colors.NORMAL)
                    self.writeresponse(response)
                    logger.info(response)
Beispiel #45
0
        sys.exit(1)

    if daemon:
        pdusim.common.daemon.daemonize(server_pid_file)

    init_signal()
    # report_ip_thread = threading.Thread(target = pdusim.reportip.rptClient)
    # report_ip_thread.start()

    # Find the conf home dir
    for dir in install_data_dir:
        path = os.path.join(dir, 'conf', 'host.conf')
        if os.path.exists(path):
            config_home_dir = dir
            break

    if config_home_dir == "":
        logger.error("Cann't find conf dir.")
        sys.exit(1)

    conf = config.Config(config_home_dir)
    config.set_conf_instance(conf)

    mapping_file.set_mapping_file_handle(
        mapping_file.MappingFileHandle(config_home_dir)
    )

    logger.info("Server started")
    server = vPDUHandler()
    server.serve_forever()
Beispiel #46
0
    def command_config(self, params):
        '''<esxi|pdu> [<list/update/add/delete> | <set/get>] [<param.1> ... < param.n>]

        configure vPDU
        ----------------------------------
        config pdu set <name>
        - set PDU name
        e.g.
        config pdu set hawk

        config pdu set database <database file>
        - set pdu database file name
        e.g.
        config pdu set database ipia.db

        config pdu set datadir <snmp data dir>
        - set snmp data directory name
        e.g.
        config pdu set datadir hawk

        config pdu list
        -list pdu configurations


        config esxi
        --------------------------------------
        config esxi list
         - list configuration

        config esxi update <option name> <value>
         - update configuration
         e.g.
            Update esxi ip address in configuration file, run below command:
            config esxi update host 10.62.59.124

            Update esxi host "username"
            config esxi update uesrname root

            Update esxi host "password"
            config esxi update password root

        config esxi add <host> <uesrname> <password>
         - add configuration
         e.g.
            Add an ESXi host information including ip, username and passowrd
            config esxi add 10.62.59.128 root 1234567

        config esxi delete
         - delete configuration
         e.g.
            Delete section "esxihost"
            config esxi delete esxihost

        Note: After update/add the configuration, please run 'config list' to
        be sure that the changes you made are correct.
        '''
        if len(params) == 0:
            return

        if params[0] == "pdu":
            if params[1] == 'set':
                if params[2] == 'name':
                    self.config_instance.pdu_name = params[3]
                elif params[2] == 'database':
                    self.config_instance.db_file = params[3]
                elif params[2] == 'datadir':
                    self.config_instance.snmp_data_dir = params[3]

                self.config_instance.update()
            elif params[1] == 'get':
                self.config_instance.init()
                table = Texttable()
                table.add_row(['name', self.config_instance.pdu_name])
                table.add_row(['database', self.config_instance.db_file])
                table.add_row(['snmp data dir',
                               self.config_instance.snmp_data_dir])
                table_str = table.draw()
                self.writeresponse(table_str)
                logger.info("\n" + table_str)
            else:
                logger.error("Unknown command {0}".format(params[0]))
        elif params[0] == "esxi":
            if params[1] == "list":
                self.config_instance.init()
                esxi_info = self.config_instance.esxi_info
                if esxi_info is not None:
                    table = Texttable()
                    table.header(["esxi host", "username", "password"])
                    table.add_row([
                        get_color_string(bcolors.GREEN, esxi_info['host']),
                        get_color_string(bcolors.GREEN, esxi_info["username"]),
                        get_color_string(bcolors.GREEN, esxi_info['password'])
                    ])
                    table_str = table.draw()
                    self.writeresponse(table_str)
                    logger.info("\n" + table_str)
                    return
                else:
                    self.writeresponse("%sNo ESXi host info in configuration \
                                       file.%s" % (colors.RED, colors.NORMAL))
            elif params[1] == "update":
                if len(params[2:]) == 2:
                    esxi_info = self.config_instance.esxi_info
                    if esxi_info is not None:
                        esxi_info[params[2]] = params[3]
                        self.config_instance.update()
                    else:
                        self.writeresponse("%sNo %s found in configuration \
                            file.%s" % (colors.RED, params[1], colors.NORMAL))
            elif params[1] == "add":
                if len(params[2:]) != 3:
                    return

                if self.config_instance.esxi_info is None:
                    esxi_info = {}
                    logger.info("Adding esxi host: {0}, {1}, {2}"
                                .format(params[2], params[3], params[4]))
                    esxi_info['host'] = params[2]
                    esxi_info['username'] = params[3]
                    esxi_info['password'] = params[4]
                    self.config_instance.esxi_info = esxi_info
                    self.config_instance.update()
                else:
                    self.writeresponse("ESXi info already exists.")
            elif params[1] == "delete":
                if self.config_instance.esxi_info is not None:
                    self.config_instance.delete()
                else:
                    self.writeresponse("ESXi info already deleted.")
            else:
                self.writeresponse("unknown parameters.")
        else:
            self.writeresponse("unknown parameters: {0}.".format(params[0]))
Beispiel #47
0
    def command_vpdu(self, params):
        '''[<start/stop/restart/status>]
        Control vpdu service and get vpdu service status.
        vpdu start   - Start vPDU and SNMP simulator service
        vpdu stop    - Stop vPDU and SNMP simulator service
        vpdu restart - Restart vPDU and SNMP simulator service
        vpdu status  - Get vPDU and SNMP simulator status
        '''
        if len(params) == 0:
            return

        logger.info("Executing action: %s" % params[0])
        if params[0] == 'start':
            pid = get_vpdu_pid()
            logger.info("vpdu pid: %d" % pid)
            if pid > 0:
                self.writeresponse("%svpdu service [%d] is alredy running.%s"
                                   % (colors.GREEN, pid, colors.NORMAL))
            else:
                ret = start_vpdu()
                if ret == 0:
                    pid = get_vpdu_pid()
                    if pid > 0:
                        self.writeresponse("%svpdu service [%d] is started.%s"
                                           % (colors.GREEN, pid, colors.NORMAL))
                        return
                else:
                    # check if the snmpsim service is already running.
                    snmpsim_pid = SNMPSimService.getpid()
                    if snmpsim_pid > 0:
                        os.kill(snmpsim_pid, signal.SIGTERM)
                    self.writeresponse("%sFailed to start vpdu service.%s"
                                       % (colors.RED, colors.NORMAL))
                    logger.error("Failed to start vpdu service.")
        elif params[0] == 'stop':
            pid = get_vpdu_pid()
            if pid < 0:
                self.writeresponse("%svpdu service is already stopped.%s"
                                   % (colors.GREEN, colors.NORMAL))
                return

            if pid > 0:
                os.kill(pid, signal.SIGTERM)

            # Wait 1 second for snmpsim exit, and then end then check again
            time.sleep(1)
            snmpsim_pid = SNMPSimService.getpid()
            if snmpsim_pid > 0:
                os.kill(snmpsim_pid, signal.SIGTERM)

            pid = get_vpdu_pid()
            snmpsim_pid = SNMPSimService.getpid()

            if pid < 0 and snmpsim_pid < 0:
                self.writeresponse("%svpdu service is stopped.%s"
                                   % (colors.GREEN, colors.NORMAL))
            else:
                self.writeresponse("%sCannot stop vpdu service.vpdu pid %d, \
                                   snmpsim pid %d.%s"
                                   % (colors.RED, pid, snmpsim_pid,
                                      colors.NORMAL))
                logger.error("Cannot stop vpdu service. vpdu pid %d, \
                             snmpsim pid %d" % (pid, snmpsim_pid))
        elif params[0] == 'restart':
            pid = get_vpdu_pid()
            if pid > 0:
                os.kill(pid, signal.SIGTERM)

            # Wait 1 second for snmpsim exit, and then end then check again
            time.sleep(1)
            snmpsim_pid = SNMPSimService.getpid()
            if snmpsim_pid > 0:
                os.kill(snmpsim_pid, signal.SIGTERM)

            self.writeresponse("{0}vpdu service is stopped.{1}"
                               .format(colors.GREEN, colors.NORMAL))
            logger.info("vpdu service is stopped.")
            ret = start_vpdu()
            if ret == 0:
                pid = get_vpdu_pid()
                snmpsim_pid = SNMPSimService.getpid()
                if pid > 0 and snmpsim_pid > 0:
                    self.writeresponse("{0}vpdu service [{1}] is restarted.{2}"
                                       .format(colors.GREEN, pid, colors.NORMAL)
                                       )
                    logger.info("vpdu service [%d] is restarted." % pid)
                    return
            self.writeresponse("{0}Cannot restart vpdu service. pid {1}, \
                               snmpsimd pid {2}{3}".format(colors.RED, pid,
                                                           snmpsim_pid,
                                                           colors.NORMAL)
                               )
            logger.error("Cannot restart vpdu service.")
        elif params[0] == 'status':
            vpdu_pid = get_vpdu_pid()
            snmpsim_pid = SNMPSimService.getpid()
            response = ""
            if vpdu_pid > 0 and snmpsim_pid > 0:
                response = "%svpdu service [%d] is running.%s" % \
                        (colors.GREEN, vpdu_pid, colors.NORMAL)
                self.writeresponse(response)
                logger.info(response)
            elif vpdu_pid < 0 and snmpsim_pid < 0:
                response = \
                    "%svpdu service is not running.%s" % (colors.RED,
                                                          colors.NORMAL)
                self.writeresponse(response)
                logger.info(response)
            else:
                response = "{0}There is an exception, \
                    vpdu pid {1}, snmp sim pid {2}.{3}"\
                    .format(colors.RED, vpdu_pid, snmpsim_pid, colors.NORMAL)
                self.writeresponse(response)
                logger.info(response)
Beispiel #48
0
def signal_handler(signum, frame):
    logger.info("Signal {0} receivced.".format(signum))
    if pdu_sim is not None and pdu_sim.is_alive():
        pdu_sim.stop()
    logger.info("vPDU exit.")
    sys.exit(0)