Esempio n. 1
0
def get_power_status(conn, options):
    if options["--hmc-version"] == "3":
        conn.send("lssyscfg -r lpar -m " + options["--managed"] + " -n " +
                  options["--plug"] + " -F name,state\n")

        # First line (command) may cause parsing issues if long
        conn.readline()
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))

        try:
            status = re.compile("^" + options["--plug"] + ",(.*?),.*$",
                                re.IGNORECASE | re.MULTILINE).search(
                                    conn.before).group(1)
        except AttributeError as e:
            logging.error("Failed: {}".format(str(e)))
            fail(EC_STATUS_HMC)
    elif options["--hmc-version"] in ["4", "IVM"]:
        conn.send("lssyscfg -r lpar -m " + options["--managed"] +
                  " --filter 'lpar_names=" + options["--plug"] + "'\n")

        # First line (command) may cause parsing issues if long
        conn.readline()
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))

        try:
            status = re.compile(",state=(.*?),",
                                re.IGNORECASE).search(conn.before).group(1)
        except AttributeError as e:
            logging.error("Failed: {}".format(str(e)))
            fail(EC_STATUS_HMC)

    return _normalize_status(status)
Esempio n. 2
0
def get_power_status(conn, options):
    logger.debug("Starting status operation")
    try:
        instance = conn.instances.filter(Filters=[{
            "Name": "instance-id",
            "Values": [options["--plug"]]
        }])
        state = list(instance)[0].state["Name"]
        logger.info("Status operation for EC2 instance %s returned state: %s",
                    options["--plug"], state.upper())
        if state == "running":
            return "on"
        elif state == "stopped":
            return "off"
        else:
            return "unknown"

    except ClientError:
        fail_usage("Failed: Incorrect Access Key or Secret Key.")
    except EndpointConnectionError:
        fail_usage("Failed: Incorrect Region.")
    except IndexError:
        fail(EC_STATUS)
    except Exception as e:
        logging.error("Failed to get power status: %s", e)
        fail(EC_STATUS)
Esempio n. 3
0
def get_power_status(conn, options):
	del conn

	res = send_command(options, "<configResolveDn cookie=\"" + options["cookie"] +
			"\" inHierarchical=\"false\" dn=\"org-root" + options["--suborg"] + "/ls-" +
			options["--plug"] + "\"/>", int(options["--shell-timeout"]))

	result = RE_GET_PNDN.search(res)
	if result == None:
		fail(EC_STATUS)
	else:
		pndn = result.group(1)

	res = send_command(options, "<configResolveDn cookie=\"" + options["cookie"] +
			"\" inHierarchical=\"false\" dn=\"" + pndn +
			"\"/>", int(options["--shell-timeout"]))

	result = RE_GET_OPERPOWER.search(res)
	if result == None:
		fail(EC_STATUS)
	else:
		status = result.group(1)

	if status == "on":
		return "on"
	else:
		return "off"
Esempio n. 4
0
def get_power_status(conn, options):
    del conn

    res = send_command(
        options,
        '<configResolveDn cookie="'
        + options["cookie"]
        + '" inHierarchical="false" dn="org-root'
        + options["--suborg"]
        + "/ls-"
        + options["--plug"]
        + '/power"/>',
        int(options["--shell-timeout"]),
    )

    result = RE_STATUS.search(res)
    if result == None:
        fail(EC_STATUS)
    else:
        status = result.group(1)

    if status == "up":
        return "on"
    else:
        return "off"
def set_power_status(conn, options):
    action = {'on': "online", 'off': "offline"}[options["--action"]]

    try:
        conn.send_eol("set port " + options["--plug"] + " state " + action)
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))
    except pexpect.TIMEOUT:
        try:
            conn.send_eol("admin end")
            conn.send_eol("exit")
            conn.close()
        except Exception:
            pass
        fail(EC_TIMED_OUT)

    try:
        conn.send_eol("set port " + options["--plug"] + " state " + action)
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))
    except pexpect.TIMEOUT:
        try:
            conn.send_eol("admin end")
            conn.send_eol("exit")
            conn.close()
        except Exception:
            pass
        fail(EC_TIMED_OUT)
def get_list_devices(conn, options):
    outlets = {}

    try:
        conn.send_eol("show port")
        conn.log_expect(options["--command-prompt"],
                        int(options["--shell-timeout"]))

        list_re = re.compile(r"^\s+(\d+?)\s+(Online|Offline)\s+",
                             re.IGNORECASE)
        for line in conn.before.splitlines():
            if list_re.search(line):
                status = {
                    'online': "ON",
                    'offline': "OFF"
                }[list_re.search(line).group(2).lower()]
                outlets[list_re.search(line).group(1)] = ("", status)

    except pexpect.TIMEOUT:
        try:
            conn.send_eol("admin end")
            conn.send_eol("exit")
            conn.close()
        except Exception:
            pass
        fail(EC_TIMED_OUT)

    return outlets
def get_power_status(conn, options):
	del conn

	res = send_command(options, "<configResolveDn cookie=\"" + options["cookie"] +
			"\" inHierarchical=\"false\" dn=\"org-root" + options["--suborg"] + "/ls-" +
			options["--plug"] + "\"/>", int(options["--shell-timeout"]))

	result = RE_GET_PNDN.search(res)
	if result == None:
		pndn = ""
	else:
		pndn = result.group(1)

	if pndn.strip() == "":
		if "--missing-as-off" in options:
			return "off"
		else:
			fail(EC_STATUS)

	res = send_command(options, "<configResolveDn cookie=\"" + options["cookie"] +
			"\" inHierarchical=\"false\" dn=\"" + pndn +
			"\"/>", int(options["--shell-timeout"]))

	result = RE_GET_PRESENCE.search(res)
	if result == None:
		fail(EC_STATUS)
	else:
		status = result.group(1)

	if status in ["missing", "mismatch"]:
		return "off"
	else:
		return "on"
Esempio n. 8
0
def get_power_status(conn, options):
    del conn

    if options.get("--original-action", None) == "monitor":
        (return_code, reason_code, images_active) = get_list_of_images(options, "Check_Authentication", None)

        logging.debug("Check_Authenticate (%d,%d)", return_code, reason_code)
        if return_code == 0:
            return {}
        else:
            fail(EC_LOGIN_DENIED)

    if options["--action"] == "list":
        # '*' = list all active images
        options["--plug"] = "*"

    (return_code, reason_code, images_active) = get_list_of_images(options, "Image_Status_Query", options["--plug"])
    logging.debug("Image_Status_Query results are (%d,%d)", return_code, reason_code)

    if not options["--action"] == "list":
        if (return_code == 0) and (reason_code == 0):
            return "on"
        elif (return_code == 0) and (reason_code == 12):
            # We are running always with --missing-as-off because we can not check if image
            # is defined or not (look at rhbz#1188750)
            return "off"
        else:
            return "unknown"
    else:
        (return_code, reason_code, images_defined) = get_list_of_images(
            options, "Image_Name_Query_DM", options["--username"]
        )
        logging.debug("Image_Name_Query_DM results are (%d,%d)", return_code, reason_code)

        return dict([(i, ("", "on" if i in images_active else "off")) for i in images_defined])
Esempio n. 9
0
def get_power_status(conn, options):
    if options["enc_type"] == "superdome":
        cmd_send = "parstatus -M -p " + options["--plug"]
        powrestr = "^partition:\\d\\s+:\\w+\\s+/(\\w+)\\s.*$"
    else:
        cmd_send = "show server status " + options["--plug"]
        powrestr = "^\\s*Power: (.*?)\\s*$"

    conn.send_eol(cmd_send)
    conn.log_expect(options, options["--command-prompt"],
                    int(options["--shell-timeout"]))

    power_re = re.compile(powrestr)
    status = "unknown"
    for line in conn.before.splitlines():
        res = power_re.search(line)
        if res != None:
            if options["enc_type"] == "superdome":
                if res.group(1) == "DOWN":
                    status = "off"
                else:
                    status = "on"
            else:
                status = res.group(1)

    if status == "unknown":
        if "--missing-as-off" in options:
            return "off"
        else:
            fail(EC_STATUS)

    return status.lower().strip()
Esempio n. 10
0
def get_power_status5(conn, options):
    outlets = {}

    conn.send_eol("olStatus all")

    conn.log_expect(options["--command-prompt"],
                    int(options["--shell-timeout"]))
    lines = conn.before.split("\n")

    show_re = re.compile(r'^\s*(\d+): (.*): (On|Off)\s*$', re.IGNORECASE)

    for line in lines:
        res = show_re.search(line)
        if res != None:
            outlets[res.group(1)] = (res.group(2), res.group(3))

    if ["list", "monitor"].count(options["--action"]) == 1:
        return outlets
    else:
        try:
            (_, status) = outlets[options["--plug"]]
            return status.lower().strip()
        except KeyError as e:
            logging.error("Failed: {}".format(str(e)))
            fail(EC_STATUS)
Esempio n. 11
0
def get_power_status(conn, options):
    if options["--hmc-version"] == "3":
        conn.send("lssyscfg -r lpar -m " + options["--managed"] + " -n " +
                  options["--plug"] + " -F name,state\n")
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))

        try:
            status = re.compile("^" + options["--plug"] + ",(.*?),.*$",
                                re.IGNORECASE | re.MULTILINE).search(
                                    conn.before).group(1)
        except AttributeError:
            fail(EC_STATUS_HMC)
    elif options["--hmc-version"] in ["4", "IVM"]:
        conn.send("lssyscfg -r lpar -m " + options["--managed"] +
                  " --filter 'lpar_names=" + options["--plug"] + "'\n")
        conn.log_expect(options["--command-prompt"],
                        int(options["--power-timeout"]))

        try:
            status = re.compile(",state=(.*?),",
                                re.IGNORECASE).search(conn.before).group(1)
        except AttributeError:
            fail(EC_STATUS_HMC)

    ##
    ## Transformation to standard ON/OFF status if possible
    if status in ["Running", "Open Firmware", "Shutting Down", "Starting"]:
        status = "on"
    else:
        status = "off"

    return status
Esempio n. 12
0
def get_power_status(conn, options):
    del conn

    ### Obtain real ID from name
    res = send_command(options, "vms/?search=name%3D" + options["--plug"])

    result = RE_GET_ID.search(res)
    if result == None:
        # Unable to obtain ID needed to access virtual machine
        fail(EC_FETCH_VM_UUID)

    options["id"] = result.group(2)

    result = RE_STATUS.search(res)
    if result == None:
        # We were able to parse ID so output is correct
        # in some cases it is possible that RHEV-M output does not
        # contain <status> line. We can assume machine is OFF then
        return "off"
    else:
        status = result.group(1)

    if status.lower() == "down":
        return "off"
    else:
        return "on"
Esempio n. 13
0
def set_power_status(conn, options):
    outlets = {}
    action = {'on': "on", 'off': "off"}[options["--action"]]
    try:
        conn.send("LIST OUTLETS\r\n")
        conn.log_expect(options["--command-prompt"],
                        int(options["--shell-timeout"]))
        lines = conn.before.split("\n")
        # if options["api-version"] == "8":
        #    AA13  Arm-Console3
        #    AA14  Master_Outlet_14
        # else:
        #    .A12     TowerA_Outlet12
        #    .A12     test-01
        show_re = re.compile('(\S+)\s+(\w+|\w+\W\w+)\s+')
        for line in lines:
            res = show_re.search(line)
            if res != None:
                outlets[res.group(2)] = (res.group(1))
        conn.send(action + " " + outlets[options["--plug"]] + "\r\n")
        conn.log_expect(options["--command-prompt"],
                        int(options["--shell-timeout"]))
    except pexpect.EOF:
        fail(EC_CONNECTION_LOST)
    except pexpect.TIMEOUT:
        fail(EC_TIMED_OUT)
Esempio n. 14
0
def get_list_of_images(options, command, data_as_plug):
	conn = open_socket(options)

	packet = prepare_smapi_command(options, command, [data_as_plug])
	conn.send(packet)

	request_id = struct.unpack("!i", conn.recv(INT4))[0]
	(output_len, request_id, return_code, reason_code) = struct.unpack("!iiii", conn.recv(INT4 * 4))
	images = set()

	if output_len > 3*INT4:
		array_len = struct.unpack("!i", conn.recv(INT4))[0]
		data = ""

		while True:
			read_data = conn.recv(1024, socket.MSG_WAITALL)
			data += read_data
			if array_len == len(data):
				break
			elif not read_data:
				logging.error("Failed: Not enough data read from socket")
				fail(EC_TIMED_OUT)

		parsed_len = 0
		while parsed_len < array_len:
			string_len = struct.unpack("!i", data[parsed_len:parsed_len+INT4])[0]
			parsed_len += INT4
			image_name = struct.unpack("!%ds" % (string_len), data[parsed_len:parsed_len+string_len])[0]
			parsed_len += string_len
			images.add(image_name)

	conn.close()
	return (return_code, reason_code, images)
Esempio n. 15
0
def get_power_status(conn, options):
	if options["--hmc-version"] == "3":
		conn.send("lssyscfg -r lpar -m " + options["--managed"] + " -n " + options["--plug"] + " -F name,state\n")
		conn.log_expect(options["--command-prompt"], int(options["--power-timeout"]))

		try:
			status = re.compile("^" + options["--plug"] + ",(.*?),.*$",
					re.IGNORECASE | re.MULTILINE).search(conn.before).group(1)
		except AttributeError:
			fail(EC_STATUS_HMC)
	elif options["--hmc-version"] == "4":
		conn.send("lssyscfg -r lpar -m "+ options["--managed"] +
				" --filter 'lpar_names=" + options["--plug"] + "'\n")
		conn.log_expect(options["--command-prompt"], int(options["--power-timeout"]))

		try:
			status = re.compile(",state=(.*?),", re.IGNORECASE).search(conn.before).group(1)
		except AttributeError:
			fail(EC_STATUS_HMC)

	##
	## Transformation to standard ON/OFF status if possible
	if status in ["Running", "Open Firmware", "Shutting Down", "Starting"]:
		status = "on"
	else:
		status = "off"

	return status
Esempio n. 16
0
def get_power_status(conn, options):
	del conn

	### Obtain real ID from name
	res = send_command(options, "vms/?search=name%3D" + options["--plug"])

	result = RE_GET_ID.search(res)
	if result == None:
		# Unable to obtain ID needed to access virtual machine
		fail(EC_STATUS)

	options["id"] = result.group(2)

	result = RE_STATUS.search(res)
	if result == None:
		# We were able to parse ID so output is correct
		# in some cases it is possible that RHEV-M output does not
		# contain <status> line. We can assume machine is OFF then
		return "off"
	else:
		status = result.group(1)

	if status.lower() == "down":
		return "off"
	else:
		return "on"
Esempio n. 17
0
def set_power_status(_, options):
    client = pywsman.Client(options["--ip"], int(options["--ipport"]), \
                            '/wsman', 'http', 'admin', options["--password"])

    method = 'RequestPowerStateChange'
    client_options = pywsman.ClientOptions()
    client_options.add_selector('Name', 'Intel(r) AMT Power Management Service')

    if options["--action"] == "on":
        target_state = POWER_ON
    elif options["--action"] == "off":
        target_state = POWER_OFF
    elif options["--action"] == "reboot":
        target_state = POWER_CYCLE
    if options["--action"] in ["on", "off", "reboot"] \
       and "--boot-option" in options:
        set_boot_order(_, client, options)

    doc = _generate_power_action_input(target_state)
    client_doc = client.invoke(client_options, CIM_PowerManagementService, \
                               method, doc)
    item = "ReturnValue"
    return_value = xml_find(client_doc, CIM_PowerManagementService, item).text
    if return_value != RET_SUCCESS:
        logging.error("Failed to set power state: %s for: %s", \
                      options["--action"], options["--ip"])
        fail(EC_STATUS)
Esempio n. 18
0
def get_power_status(conn, options):
	if options["enc_type"] == "superdome":
		cmd_send = "parstatus -M -p " + options["--plug"]
		powrestr = "^partition:\\d\\s+:\\w+\\s+/(\\w+)\\s.*$"
	else:
		cmd_send = "show server status " + options["--plug"]
		powrestr = "^\\s*Power: (.*?)\\s*$"

	conn.send_eol(cmd_send)
	conn.log_expect(options, options["--command-prompt"], int(options["--shell-timeout"]))

	power_re = re.compile(powrestr)
	status = "unknown"
	for line in conn.before.splitlines():
		res = power_re.search(line)
		if res != None:
			if options["enc_type"] == "superdome":
				if res.group(1) == "DOWN":
					status = "off"
				else:
					status = "on"
			else:
				status = res.group(1)

	if status == "unknown":
		if options.has_key("--missing-as-off"):
			return "off"
		else:
			fail(EC_STATUS)

	return status.lower().strip()
Esempio n. 19
0
def soap_login(options):
	run_delay(options)

	if options.has_key("--ssl"):
		url = "https://"
	else:
		url = "http://"

	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		conn = Client(url + "/vimService.wsdl")
		conn.set_options(location = url)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except Exception:
		fail(EC_LOGIN_DENIED)

	options["ServiceContent"] = ServiceContent
	options["mo_SessionManager"] = mo_SessionManager
	return conn
Esempio n. 20
0
def get_list_devices(conn, options):
	outlets = { }

	try:
		conn.send_eol("show port")
		conn.log_expect(options, options["--command-prompt"], int(options["--shell-timeout"]))

		list_re = re.compile(r"^\s+(\d+?)\s+(Online|Offline)\s+", re.IGNORECASE)
		for line in conn.before.splitlines():
			if list_re.search(line):
				status = {
					'online' : "ON",
					'offline' : "OFF"
				}[list_re.search(line).group(2).lower()]
				outlets[list_re.search(line).group(1)] = ("", status)

	except pexpect.TIMEOUT:
		try:
			conn.send_eol("admin end")
			conn.send_eol("exit")
			conn.close()
		except Exception:
			pass
		fail(EC_TIMED_OUT)

	return outlets
Esempio n. 21
0
def open_socket(options):
    try:
        if "--inet6-only" in options:
            protocol = socket.AF_INET6
        elif "--inet4-only" in options:
            protocol = socket.AF_INET
        else:
            protocol = 0
        (_, _, _, _, addr) = socket.getaddrinfo( \
          options["--ip"], options["--ipport"], protocol,
          0, socket.IPPROTO_TCP, socket.AI_PASSIVE
          )[0]
    except socket.gaierror:
        fail(EC_LOGIN_DENIED)

    if "--ssl" in options:
        import ssl
        sock = socket.socket()
        sslcx = ssl.create_default_context()
        if "--ssl-insecure" in options:
            sslcx.check_hostname = False
            sslcx.verify_mode = ssl.CERT_NONE
        conn = sslcx.wrap_socket(sock, server_hostname=options["--ip"])
    else:
        conn = socket.socket()
    conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    conn.settimeout(float(options["--shell-timeout"]) or None)
    try:
        conn.connect(addr)
    except socket.error as e:
        logging.debug(e)
        fail(EC_LOGIN_DENIED)

    return conn
Esempio n. 22
0
def get_power_status(conn, options):
    del conn

    res = send_command(
        options, "<configResolveDn cookie=\"" + options["cookie"] +
        "\" inHierarchical=\"false\" dn=\"org-root" + options["--suborg"] +
        "/ls-" + options["--plug"] + "\"/>", int(options["--shell-timeout"]))

    result = RE_GET_PNDN.search(res)
    if result == None:
        pndn = ""
    else:
        pndn = result.group(1)

    if pndn.strip() == "":
        if "--missing-as-off" in options:
            return "off"
        else:
            fail(EC_STATUS)

    res = send_command(
        options, "<configResolveDn cookie=\"" + options["cookie"] +
        "\" inHierarchical=\"false\" dn=\"" + pndn + "\"/>",
        int(options["--shell-timeout"]))

    result = RE_GET_PRESENCE.search(res)
    if result == None:
        fail(EC_STATUS)
    else:
        status = result.group(1)

    if status in ["missing", "mismatch"]:
        return "off"
    else:
        return "on"
Esempio n. 23
0
def vmware_run_command(options, add_login_params, additional_params,
                       additional_timeout):
    command = vmware_prepare_command(options, add_login_params,
                                     additional_params)

    try:
        logging.debug("%s\n", command)

        (res_output, res_code) = frun(
            command,
            int(options["--shell-timeout"]) + int(options["--login-timeout"]) +
            additional_timeout, True)

        if res_code == None:
            fail(EC_TIMED_OUT)
        if res_code != 0 and add_login_params:
            logging.debug("%s\n", res_output)
            fail_usage("%s returned %s" % (options["--exec"], res_output))
        else:
            logging.debug("%s\n", res_output)

    except pexpect.ExceptionPexpect:
        fail_usage("Cannot run command %s" % (options["--exec"]))

    return res_output
Esempio n. 24
0
def set_power_status(conn, options):
	action = {
		'on' : "online",
		'off' : "offline"
	}[options["--action"]]

	try:
		conn.send_eol("set port " + options["--plug"] + " state " + action)
		conn.log_expect(options, options["--command-prompt"], int(options["--power-timeout"]))
	except pexpect.TIMEOUT:
		try:
			conn.send_eol("admin end")
			conn.send_eol("exit")
			conn.close()
		except Exception:
			pass
		fail(EC_TIMED_OUT)

	try:
		conn.send_eol("set port " + options["--plug"] + " state " + action)
		conn.log_expect(options, options["--command-prompt"], int(options["--power-timeout"]))
	except pexpect.TIMEOUT:
		try:
			conn.send_eol("admin end")
			conn.send_eol("exit")
			conn.close()
		except Exception:
			pass
		fail(EC_TIMED_OUT)
Esempio n. 25
0
def set_power_status(_, options):
    client = pywsman.Client(options["--ip"], int(options["--ipport"]), \
                            '/wsman', 'http', 'admin', options["--password"])

    method = 'RequestPowerStateChange'
    client_options = pywsman.ClientOptions()
    client_options.add_selector('Name', 'Intel(r) AMT Power Management Service')

    if options["--action"] == "on":
        target_state = POWER_ON
    elif options["--action"] == "off":
        target_state = POWER_OFF
    elif options["--action"] == "reboot":
        target_state = POWER_CYCLE
    if options["--action"] in ["on", "off", "reboot"] \
       and "--boot-option" in options:
        set_boot_order(_, client, options)

    doc = _generate_power_action_input(target_state)
    client_doc = client.invoke(client_options, CIM_PowerManagementService, \
                               method, doc)
    item = "ReturnValue"
    return_value = xml_find(client_doc, CIM_PowerManagementService, item).text
    if return_value != RET_SUCCESS:
        logging.error("Failed to set power state: %s for: %s", \
                      options["--action"], options["--ip"])
        fail(EC_STATUS)
Esempio n. 26
0
def get_list(conn, options):
    outlets = {}

    try:
        command = "vcenter/vm"
        if "--filter" in options:
            command = command + "?" + options["--filter"]
        res = send_command(conn, command)
    except Exception as e:
        logging.debug("Failed: {}".format(e))
        if str(e).startswith("400"):
            if options.get("--original-action") == "monitor":
                return outlets
            else:
                logging.error(
                    "More than 1000 VMs returned. Use --filter parameter to limit which VMs to list."
                )
                fail(EC_STATUS)
        else:
            fail(EC_STATUS)

    for r in res["value"]:
        outlets[r["name"]] = ("", state[r["power_state"]])

    return outlets
Esempio n. 27
0
def main():
    device_opt = ["ipaddr", "login", "passwd", "port", "telnet"]

    atexit.register(atexit_handler)

    opt = process_input(device_opt)

    all_opt["ipport"]["default"] = "23"

    opt["eol"] = "\r\n"
    options = check_input(device_opt, opt)

    docs = {}
    docs["shortdesc"] = "I/O Fencing agent for Raritan Dominion PX"
    docs["longdesc"] = "fence_raritan is an I/O Fencing agent which can be \
used with the Raritan DPXS12-20 Power Distribution Unit. It logs into \
device via telnet and reboots a specified outlet. Lengthy telnet connections \
should be avoided while a GFS cluster is running because the connection will \
block any necessary fencing actions."

    docs["vendorurl"] = "http://www.raritan.com/"
    show_docs(options, docs)

    #  add support also for delay before login which is very useful for 2-node clusters
    run_delay(options)

    # Convert pure port/plug number to /system1/outlet${plug}
    try:
        plug_int = int(options["--plug"])
        options["--plug"] = "/system1/outlet" + str(plug_int)
    except ValueError:
        pass
    ##
    ## Operate the fencing device
    ## We can not use fence_login(), username and passwd are sent on one line
    ####
    try:
        conn = fspawn(options, options["--telnet-path"], encoding="latin1")
        conn.send("set binary\n")
        conn.send("open %s -%s\n" % (options["--ip"], options["--ipport"]))
        conn.read_nonblocking(size=100,
                              timeout=int(options["--shell-timeout"]))
        conn.log_expect("Login.*", int(options["--shell-timeout"]))
        conn.send_eol("%s" % (options["--username"]))
        conn.log_expect("Password.*", int(options["--shell-timeout"]))
        conn.send_eol("%s" % (options["--password"]))
        conn.log_expect("clp.*", int(options["--shell-timeout"]))
    except pexpect.EOF:
        fail(EC_LOGIN_DENIED)
    except pexpect.TIMEOUT:
        fail(EC_LOGIN_DENIED)

    result = 0
    if options["--action"] != "monitor":
        result = fence_action(conn, options, set_power_status,
                              get_power_status)

    fence_logout(conn, "exit\n")
    sys.exit(result)
Esempio n. 28
0
def main():
    atexit.register(atexit_handler)

    all_opt["node_name"] = {
        "getopt": "N:",
        "longopt": "nodename",
        "help": "-N, --nodename                 "
        "Node on which machine is located",
        "required": "0",
        "shortdesc": "Node on which machine is located. "
        "(Optional, will be automatically determined)",
        "order": 2
    }

    device_opt = ["ipaddr", "login", "passwd", "web", "port", "node_name"]

    all_opt["login"]["required"] = "0"
    all_opt["login"]["default"] = "root@pam"
    all_opt["ipport"]["default"] = "8006"
    all_opt["port"]["shortdesc"] = "Id of the virtual machine."
    all_opt["ipaddr"]["shortdesc"] = "IP Address or Hostname of a node " +\
     "within the Proxmox cluster."

    options = check_input(device_opt, process_input(device_opt))
    docs = {}
    docs["shortdesc"] = "Fencing agent for the Proxmox Virtual Environment"
    docs["longdesc"] = "The fence_pve agent can be used to fence virtual \
machines acting as nodes in a virtualized cluster."

    docs["vendorurl"] = "http://www.proxmox.com/"

    show_docs(options, docs)

    run_delay(options)

    if "--nodename" not in options or not options["--nodename"]:
        options["--nodename"] = None

    options["url"] = "https://" + options["--ip"] + ":" + str(
        options["--ipport"]) + "/api2/json/"

    options["auth"] = get_ticket(options)
    if options["auth"] is None:
        fail(EC_LOGIN_DENIED)

    # Workaround for unsupported API call on some Proxmox hosts
    outlets = get_outlet_list(
        None, options)  # Unsupported API-Call will result in value: None
    if outlets is None:
        result = fence_action(None, options, set_power_status,
                              get_power_status, None)
        sys.exit(result)

    result = fence_action(None, options, set_power_status, get_power_status,
                          get_outlet_list)

    sys.exit(result)
Esempio n. 29
0
def set_power_status(conn, options):
    action = {"on": "start", "off": "stop"}[options["--action"]]

    try:
        send_command(conn,
                     "vcenter/vm/{}/power/{}".format(options["id"],
                                                     action), "POST")
    except Exception as e:
        logging.debug("Failed: {}".format(e))
        fail(EC_STATUS)
Esempio n. 30
0
def set_power_status(conn, options):
    logging.debug("Starting set status operation")
    try:
        namespace = options.get("--namespace")
        name = options.get("--plug")
        action = 'start' if options["--action"] == "on" else 'stop'
        virtctl_vm_action(conn, action, namespace, name)
    except Exception as e:
        logging.error("Failed to set power status, with Exception: %s", e)
        fail(EC_STATUS)
Esempio n. 31
0
def soap_login(options):
    run_delay(options)

    if "--ssl" in options or "--ssl-secure" in options or "--ssl-insecure" in options:
        if "--ssl-insecure" in options:
            import ssl
            import urllib3
            if hasattr(ssl, '_create_unverified_context'):
                ssl._create_default_https_context = ssl._create_unverified_context
            urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
            verify = False
        else:
            verify = True
        url = "https://"
    else:
        verify = False
        url = "http://"

    url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

    tmp_dir = tempfile.mkdtemp()
    tempfile.tempdir = tmp_dir
    atexit.register(remove_tmp_dir, tmp_dir)

    try:
        headers = {
            "Content-Type": "text/xml;charset=UTF-8",
            "SOAPAction": "vim25"
        }
        login_timeout = int(options["--login-timeout"]) or 60
        conn = Client(url + "/vimService.wsdl",
                      location=url,
                      transport=RequestsTransport(verify=verify),
                      headers=headers,
                      timeout=login_timeout)

        mo_ServiceInstance = Property('ServiceInstance')
        mo_ServiceInstance._type = 'ServiceInstance'
        ServiceContent = conn.service.RetrieveServiceContent(
            mo_ServiceInstance)
        mo_SessionManager = Property(ServiceContent.sessionManager.value)
        mo_SessionManager._type = 'SessionManager'

        conn.service.Login(mo_SessionManager, options["--username"],
                           options["--password"])
    except requests.exceptions.SSLError as ex:
        fail_usage("Server side certificate verification failed: %s" % ex)
    except Exception as e:
        logging.error("Server side certificate verification failed: {}".format(
            str(e)))
        fail(EC_LOGIN_DENIED)

    options["ServiceContent"] = ServiceContent
    options["mo_SessionManager"] = mo_SessionManager
    return conn
Esempio n. 32
0
def get_power_status(conn, options):
    try:
        command = "cloud-instances/{}/pvm-instances/{}".format(
            options["--instance"], options["--plug"])
        res = send_command(conn, command)
        result = get_list(conn, options)[options["--plug"]][1]
    except KeyError as e:
        logging.debug("Failed: Unable to get status for {}".format(e))
        fail(EC_STATUS)

    return result
Esempio n. 33
0
def get_power_status(conn, options):
	res = send_command(conn, "vcenter/vm?filter.names={}".format(options["--plug"]))["value"]

	if len(res) == 0:
		fail(EC_STATUS)

	options["id"] = res[0]["vm"]

	result = res[0]["power_state"]

	return state[result]
Esempio n. 34
0
def main():
    global options_global
    device_opt = [
        "ipaddr", "login", "passwd", "ssl", "notls", "port", "web", "suborg",
        "missing_as_off"
    ]

    atexit.register(atexit_handler)
    atexit.register(logout)

    define_new_opts()

    options_global = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Cisco UCS"
    docs["longdesc"] = "fence_cisco_ucs is an I/O Fencing agent which can be \
used with Cisco UCS to fence machines."

    docs["vendorurl"] = "http://www.cisco.com"
    show_docs(options_global, docs)

    run_delay(options_global)
    ### Login
    try:
        res = send_command(
            options_global,
            "<aaaLogin inName=\"" + options_global["--username"] +
            "\" inPassword=\"" + options_global["--password"] + "\" />",
            int(options_global["--login-timeout"]))
        result = RE_COOKIE.search(res)
        if result == None:
            ## Cookie is absenting in response
            fail(EC_LOGIN_DENIED)
    except Exception as e:
        logging.error("Failed: {}".format(str(e)))
        fail(EC_LOGIN_DENIED)

    options_global["cookie"] = result.group(1)

    ##
    ## Modify suborg to format /suborg
    if options_global["--suborg"] != "":
        options_global["--suborg"] = "/" + options_global["--suborg"].lstrip(
            "/").rstrip("/")

    ##
    ## Fence operations
    ####
    result = fence_action(None, options_global, set_power_status,
                          get_power_status, get_list)

    ## Logout is done every time at atexit phase
    sys.exit(result)
Esempio n. 35
0
def main():
    global options_global
    device_opt = ["ipaddr", "login", "passwd", "ssl", "notls", "port", "web", "suborg"]

    atexit.register(atexit_handler)
    atexit.register(logout)

    define_new_opts()

    options_global = check_input(device_opt, process_input(device_opt))

    docs = {}
    docs["shortdesc"] = "Fence agent for Cisco UCS"
    docs[
        "longdesc"
    ] = "fence_cisco_ucs is an I/O Fencing agent which can be \
used with Cisco UCS to fence machines."
    docs["vendorurl"] = "http://www.cisco.com"
    show_docs(options_global, docs)

    run_delay(options_global)
    ### Login
    try:
        res = send_command(
            options_global,
            '<aaaLogin inName="'
            + options_global["--username"]
            + '" inPassword="******"--password"]
            + '" />',
            int(options_global["--login-timeout"]),
        )
        result = RE_COOKIE.search(res)
        if result == None:
            ## Cookie is absenting in response
            fail(EC_LOGIN_DENIED)
    except Exception:
        fail(EC_LOGIN_DENIED)

    options_global["cookie"] = result.group(1)

    ##
    ## Modify suborg to format /suborg
    if options_global["--suborg"] != "":
        options_global["--suborg"] = "/" + options_global["--suborg"].lstrip("/").rstrip("/")

        ##
        ## Fence operations
        ####
    result = fence_action(None, options_global, set_power_status, get_power_status, get_list)

    ## Logout is done every time at atexit phase
    sys.exit(result)
Esempio n. 36
0
def get_power_status(conn, options):
    res = send_command(conn, "vcenter/vm?filter.names={}".format(
        options["--plug"]))["value"]

    if len(res) == 0:
        fail(EC_STATUS)

    options["id"] = res[0]["vm"]

    result = res[0]["power_state"]

    return state[result]
def set_power_status(conn, options):
        action = {
                "on" : "powerOn",
                "off" : "powerOff",
                "shutdown": "shutdown",
                "suspend": "suspend",
                "reset": "reset"
                }[options["--action"]]
        try:
                VM = send_command(conn, "vApp/vm-{}/power/action/{}".format(options["--plug"], action), "POST")
        except Exception as e:
                logging.debug("Failed: {}".format(e))
                fail(EC_STATUS)
Esempio n. 38
0
def get_list(conn, options):
	outlets = {}

	try:
		res = send_command(conn, "vcenter/vm")
	except:
		logging.debug("Failed: {}".format(e))
		fail(EC_STATUS)

	for r in res["value"]:
		outlets[r["name"]] = ("", state[r["power_state"]])

	return outlets
Esempio n. 39
0
def set_boot_order(_, client, options):
    method_input = "ChangeBootOrder_INPUT"
    address = 'http://schemas.xmlsoap.org/ws/2004/08/addressing'
    anonymous = ('http://schemas.xmlsoap.org/ws/2004/08/addressing/'
                 'role/anonymous')
    wsman = 'http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'
    namespace = CIM_BootConfigSetting

    if options["--boot-option"] == "pxe":
        device = "Intel(r) AMT: Force PXE Boot"
    elif options["--boot-option"] == "hd" or "hdsafe":
        device = "Intel(r) AMT: Force Hard-drive Boot"
    elif options["--boot-option"] == "cd":
        device = "Intel(r) AMT: Force CD/DVD Boot"
    elif options["--boot-option"] == "diag":
        device = "Intel(r) AMT: Force Diagnostic Boot"
    else:
        logging.error('Boot device: %s not supported.', \
                      options["--boot-option"])
        return

    method = 'ChangeBootOrder'
    client_options = pywsman.ClientOptions()
    client_options.add_selector('InstanceID', \
                                'Intel(r) AMT: Boot Configuration 0')

    doc = pywsman.XmlDoc(method_input)
    root = doc.root()
    root.set_ns(namespace)

    child = root.add(namespace, 'Source', None)
    child.add(address, 'Address', anonymous)

    grand_child = child.add(address, 'ReferenceParameters', None)
    grand_child.add(wsman, 'ResourceURI', CIM_BootSourceSetting)

    g_grand_child = grand_child.add(wsman, 'SelectorSet', None)
    g_g_grand_child = g_grand_child.add(wsman, 'Selector', device)
    g_g_grand_child.attr_add(wsman, 'Name', 'InstanceID')
    if options["--boot-option"] == "hdsafe":
        g_g_grand_child = g_grand_child.add(wsman, 'Selector', 'True')
        g_g_grand_child.attr_add(wsman, 'Name', 'UseSafeMode')

    client_doc = client.invoke(client_options, CIM_BootConfigSetting, \
                               method, doc)
    item = "ReturnValue"
    return_value = xml_find(client_doc, CIM_BootConfigSetting, item).text
    if return_value != RET_SUCCESS:
        logging.error("Failed to set boot device to: %s for: %s", \
                      options["--boot-option"], options["--ip"])
        fail(EC_STATUS)
Esempio n. 40
0
def set_boot_order(_, client, options):
    method_input = "ChangeBootOrder_INPUT"
    address = 'http://schemas.xmlsoap.org/ws/2004/08/addressing'
    anonymous = ('http://schemas.xmlsoap.org/ws/2004/08/addressing/'
                 'role/anonymous')
    wsman = 'http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'
    namespace = CIM_BootConfigSetting

    if options["--boot-option"] == "pxe":
        device = "Intel(r) AMT: Force PXE Boot"
    elif options["--boot-option"] == "hd" or "hdsafe":
        device = "Intel(r) AMT: Force Hard-drive Boot"
    elif options["--boot-option"] == "cd":
        device = "Intel(r) AMT: Force CD/DVD Boot"
    elif options["--boot-option"] == "diag":
        device = "Intel(r) AMT: Force Diagnostic Boot"
    else:
        logging.error('Boot device: %s not supported.', \
                      options["--boot-option"])
        return

    method = 'ChangeBootOrder'
    client_options = pywsman.ClientOptions()
    client_options.add_selector('InstanceID', \
                                'Intel(r) AMT: Boot Configuration 0')

    doc = pywsman.XmlDoc(method_input)
    root = doc.root()
    root.set_ns(namespace)

    child = root.add(namespace, 'Source', None)
    child.add(address, 'Address', anonymous)

    grand_child = child.add(address, 'ReferenceParameters', None)
    grand_child.add(wsman, 'ResourceURI', CIM_BootSourceSetting)

    g_grand_child = grand_child.add(wsman, 'SelectorSet', None)
    g_g_grand_child = g_grand_child.add(wsman, 'Selector', device)
    g_g_grand_child.attr_add(wsman, 'Name', 'InstanceID')
    if options["--boot-option"] == "hdsafe":
        g_g_grand_child = g_grand_child.add(wsman, 'Selector', 'True')
        g_g_grand_child.attr_add(wsman, 'Name', 'UseSafeMode')

    client_doc = client.invoke(client_options, CIM_BootConfigSetting, \
                               method, doc)
    item = "ReturnValue"
    return_value = xml_find(client_doc, CIM_BootConfigSetting, item).text
    if return_value != RET_SUCCESS:
        logging.error("Failed to set boot device to: %s for: %s", \
                      options["--boot-option"], options["--ip"])
        fail(EC_STATUS)
Esempio n. 41
0
def get_list_of_images(options, command, data_as_plug):
    conn = open_socket(options)

    if data_as_plug is None:
        packet = prepare_smapi_command(options, command, [])
    else:
        packet = prepare_smapi_command(options, command, [data_as_plug])

    conn.send(packet)

    try:
        request_id = struct.unpack("!i", conn.recv(INT4))[0]
        (output_len, request_id, return_code,
         reason_code) = struct.unpack("!iiii", conn.recv(INT4 * 4))
    except struct.error:
        logging.debug(sys.exc_info())
        fail_usage(
            "Failed: Unable to connect to {} port: {} SSL: {} \n".format(
                options["--ip"], options["--ipport"],
                bool("--ssl" in options)))

    images = set()

    if output_len > 3 * INT4:
        recvflag = socket.MSG_WAITALL if "--ssl-secure" not in options and "--ssl-insecure" not in options else 0
        array_len = struct.unpack("!i", conn.recv(INT4))[0]
        data = ""

        while True:
            read_data = conn.recv(1024, recvflag).decode("UTF-8")
            data += read_data
            if array_len == len(data):
                break
            elif not read_data:
                logging.error("Failed: Not enough data read from socket")
                fail(EC_TIMED_OUT)

        parsed_len = 0
        while parsed_len < array_len:
            string_len = struct.unpack(
                "!i", data[parsed_len:parsed_len + INT4].encode("UTF-8"))[0]
            parsed_len += INT4
            image_name = struct.unpack(
                "!%ds" % (string_len),
                data[parsed_len:parsed_len +
                     string_len].encode("UTF-8"))[0].decode("UTF-8")
            parsed_len += string_len
            images.add(image_name)

    conn.close()
    return (return_code, reason_code, images)
Esempio n. 42
0
def set_power_status(conn, options):
    action = {
        "on": '{"action" : "start"}',
        "off": '{"action" : "immediate-shutdown"}',
    }[options["--action"]]

    try:
        send_command(
            conn, "cloud-instances/{}/pvm-instances/{}/action".format(
                options["--instance"], options["--plug"]), "POST", action)
    except Exception as e:
        logging.debug("Failed: Unable to set power to {} for {}".format(
            options["--action"], e))
        fail(EC_STATUS)
Esempio n. 43
0
def set_power_status(conn, options):
    action = {
        "on": '{"type" : "start"}',
        "off": '{"type" : "stop"}',
    }[options["--action"]]

    try:
        command = "instances/{}/actions?version=2021-05-25&generation=2".format(
            options["--plug"])
        send_command(conn, command, "POST", action, 201)
    except Exception as e:
        logging.debug("Failed: Unable to set power to {} for {}".format(
            options["--action"], e))
        fail(EC_STATUS)
Esempio n. 44
0
def main():
	device_opt = ["ipaddr", "login", "passwd", "port", "telnet"]

	atexit.register(atexit_handler)

	opt = process_input(device_opt)

	all_opt["ipport"]["default"] = "23"

	opt["eol"] = "\r\n"
	options = check_input(device_opt, opt)

	docs = {}
	docs["shortdesc"] = "I/O Fencing agent for Raritan Dominion PX"
	docs["longdesc"] = "fence_raritan is an I/O Fencing agent which can be \
used with the Raritan DPXS12-20 Power Distribution Unit. It logs into \
device via telnet and reboots a specified outlet. Lengthy telnet connections \
should be avoided while a GFS cluster is running because the connection will \
block any necessary fencing actions."
	docs["vendorurl"] = "http://www.raritan.com/"
	show_docs(options, docs)

	#  add support also for delay before login which is very useful for 2-node clusters
	run_delay(options)

	##
	## Operate the fencing device
	## We can not use fence_login(), username and passwd are sent on one line
	####
	try:
		conn = fspawn(options, options["--telnet-path"])
		conn.send("set binary\n")
		conn.send("open %s -%s\n"%(options["--ip"], options["--ipport"]))
		conn.read_nonblocking(size=100, timeout=int(options["--shell-timeout"]))
		conn.log_expect("Login.*", int(options["--shell-timeout"]))
		conn.send_eol("%s" % (options["--username"]))
		conn.log_expect("Password.*", int(options["--shell-timeout"]))
		conn.send_eol("%s" % (options["--password"]))
		conn.log_expect("clp.*", int(options["--shell-timeout"]))
	except pexpect.EOF:
		fail(EC_LOGIN_DENIED)
	except pexpect.TIMEOUT:
		fail(EC_LOGIN_DENIED)

	result = 0
	if options["--action"] != "monitor":
		result = fence_action(conn, options, set_power_status, get_power_status)

	fence_logout(conn, "exit\n")
	sys.exit(result)
Esempio n. 45
0
def get_enclosure_type(conn, options):
	conn.send_eol("show enclosure info")
	conn.log_expect(options, options["--command-prompt"], int(options["--shell-timeout"]))

	type_re=re.compile(r"^\s*Enclosure Type: (\w+)(.*?)\s*$")
	enclosure="unknown"
	for line in conn.before.splitlines():
		res = type_re.search(line)
		if res != None:
			enclosure=res.group(1)

	if enclosure == "unknown":
		fail(EC_GENERIC_ERROR)

	return enclosure.lower().strip()
Esempio n. 46
0
def get_power_status(conn, options):
	try:
		res = send_command(conn, "vcenter/vm?filter.names={}".format(options["--plug"]))["value"]
	except Exception as e:
		logging.debug("Failed: {}".format(e))
		fail(EC_STATUS)

	if len(res) == 0:
		fail(EC_STATUS)

	options["id"] = res[0]["vm"]

	result = res[0]["power_state"]

	return state[result]
Esempio n. 47
0
def get_power_status(conn, options):
    try:
        command = "instances/{}?version=2021-05-25&generation=2".format(
            options["--plug"])
        res = send_command(conn, command)
        result = state[res["status"]]
        if options["--verbose-level"] > 1:
            logging.debug("Result:\n{}".format(json.dumps(res, indent=2)))
            logging.debug("Status: " + result)
    except Exception as e:
        logging.debug("Failed: Unable to get status for {}: {}".format(
            options["--plug"], e))
        fail(EC_STATUS)

    return result
def set_power_status(conn, options):
	node_cmd = r"system:blade\[" + options["--plug"] + r"\]>"

	conn.send_eol("env -T system:blade[" + options["--plug"] + "]")
	i = conn.log_expect(options, [node_cmd, "system>"], int(options["--shell-timeout"]))
	if i == 1:
		## Given blade number does not exist
		if options.has_key("--missing-as-off"):
			return
		else:
			fail(EC_GENERIC_ERROR)

	conn.send_eol("power -"+options["--action"])
	conn.log_expect(options, node_cmd, int(options["--shell-timeout"]))
	conn.send_eol("env -T system")
	conn.log_expect(options, options["--command-prompt"], int(options["--shell-timeout"]))
Esempio n. 49
0
def get_power_status(conn, options):
	conn.send_eol("show node list")
	conn.log_expect(options["--command-prompt"], int(options["--shell-timeout"]))

	nodes = {}
	for line in conn.before.splitlines():
		if len(line.split()) == 10:
			nodes[line.split()[1]] = ("", line.split()[8].lower().strip())

	if ["list", "monitor"].count(options["--action"]) == 1:
		return nodes
	else:
		try:
			(_, status) = nodes[options["--plug"]]
			return status.lower()
		except KeyError:
			fail(EC_STATUS)
def main():
	device_opt = ["ipaddr", "login", "passwd", "port"]

	atexit.register(atexit_handler)

	opt = process_input(device_opt)

	# set default port for telnet only
	if not opt.has_key("--ipport"):
		opt["--ipport"] = "1234"

	opt["eol"] = "\r\n"
	options = check_input(device_opt, opt)

	docs = {}
	docs["shortdesc"] = "I/O Fencing agent for Koukaam NETIO-230B"
	docs["longdesc"] = "fence_netio is an I/O Fencing agent which can be \
used with the Koukaam NETIO-230B Power Distribution Unit. It logs into \
device via telnet and reboots a specified outlet. Lengthy telnet connections \
should be avoided while a GFS cluster is running because the connection will \
block any necessary fencing actions."
	docs["vendorurl"] = "http://www.koukaam.se/"
	show_docs(options, docs)

	##
	## Operate the fencing device
	## We can not use fence_login(), username and passwd are sent on one line
	####
	run_delay(options)
	try:
		conn = fspawn(options, TELNET_PATH)
		conn.send("set binary\n")
		conn.send("open %s -%s\n"%(options["--ip"], options["--ipport"]))

		conn.read_nonblocking(size=100, timeout=int(options["--shell-timeout"]))
		conn.log_expect(options, "100 HELLO .*", int(options["--shell-timeout"]))
		conn.send_eol("login %s %s" % (options["--username"], options["--password"]))
		conn.log_expect(options, "250 OK", int(options["--shell-timeout"]))
	except pexpect.EOF:
		fail(EC_LOGIN_DENIED)
	except pexpect.TIMEOUT:
		fail(EC_LOGIN_DENIED)

	result = fence_action(conn, options, set_power_status, get_power_status, get_outlet_list)
	fence_logout(conn, "quit\n")
	sys.exit(result)
Esempio n. 51
0
def main():
	atexit.register(atexit_handler)

	all_opt["node_name"] = {
		"getopt" : "N:",
		"longopt" : "nodename",
		"help" : "-N, --nodename                 "
			"Node on which machine is located",
		"required" : "0",
		"shortdesc" : "Node on which machine is located. "
			"(Optional, will be automatically determined)",
		"order": 2
	}

	device_opt = ["ipaddr", "login", "passwd", "web", "port", "node_name"]

	all_opt["login"]["required"] = "0"
	all_opt["login"]["default"] = "root@pam"
	all_opt["ipport"]["default"] = "8006"
	all_opt["port"]["shortdesc"] = "Id of the virtual machine."
	all_opt["ipaddr"]["shortdesc"] = "IP Address or Hostname of a node " +\
		"within the Proxmox cluster."

	options = check_input(device_opt, process_input(device_opt))
	docs = {}
	docs["shortdesc"] = "Fencing agent for the Proxmox Virtual Environment"
	docs["longdesc"] = "The fence_pve agent can be used to fence virtual \
machines acting as nodes in a virtualized cluster."
	docs["vendorurl"] = "http://www.proxmox.com/"

	show_docs(options, docs)

	run_delay(options)

	if "--nodename" not in options or not options["--nodename"]:
		options["--nodename"] = None

	options["url"] = "https://" + options["--ip"] + ":" + str(options["--ipport"]) + "/api2/json/"

	options["auth"] = get_ticket(options)
	if options["auth"] is None:
		fail(EC_LOGIN_DENIED)

	result = fence_action(None, options, set_power_status, get_power_status, get_outlet_list)

	sys.exit(result)
Esempio n. 52
0
def connect(opt):
	conn = pycurl.Curl()

	## setup correct URL
	if "--ssl" in opt or "--ssl-secure" in opt or "--ssl-insecure" in opt:
		conn.base_url = "https:"
	else:
		conn.base_url = "http:"
	if "--api-path" in opt:
		api_path = opt["--api-path"]
	else:
		api_path = "/rest"

	conn.base_url += "//" + opt["--ip"] + ":" + str(opt["--ipport"]) + api_path + "/"

	## send command through pycurl
	conn.setopt(pycurl.HTTPHEADER, [
		"Accept: application/json",
	])

	conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
	conn.setopt(pycurl.USERPWD, opt["--username"] + ":" + opt["--password"])

	conn.setopt(pycurl.TIMEOUT, int(opt["--shell-timeout"]))
	if "--ssl" in opt or "--ssl-secure" in opt:
		conn.setopt(pycurl.SSL_VERIFYPEER, 1)
		conn.setopt(pycurl.SSL_VERIFYHOST, 2)

	if "--ssl-insecure" in opt:
		conn.setopt(pycurl.SSL_VERIFYPEER, 0)
		conn.setopt(pycurl.SSL_VERIFYHOST, 0)

	try:
		result = send_command(conn, "com/vmware/cis/session", "POST")
	except Exception as e:
		logging.debug("Failed: {}".format(e))
		fail(EC_LOGIN_DENIED)

	# set session id for later requests
	conn.setopt(pycurl.HTTPHEADER, [
		"Accept: application/json",
		"vmware-api-session-id: {}".format(result["value"]),
	])

	return conn
def get_power_status(conn, options):
	node_cmd = r"system:blade\[" + options["--plug"] + r"\]>"

	conn.send_eol("env -T system:blade[" + options["--plug"] + "]")
	i = conn.log_expect(options, [node_cmd, "system>"], int(options["--shell-timeout"]))
	if i == 1:
		## Given blade number does not exist
		if options.has_key("--missing-as-off"):
			return "off"
		else:
			fail(EC_STATUS)
	conn.send_eol("power -state")
	conn.log_expect(options, node_cmd, int(options["--shell-timeout"]))
	status = conn.before.splitlines()[-1]
	conn.send_eol("env -T system")
	conn.log_expect(options, options["--command-prompt"], int(options["--shell-timeout"]))

	return status.lower().strip()
Esempio n. 54
0
def get_power_status(conn, options):
	conn.send_eol("show server status " + options["--plug"])
	conn.log_expect(options["--command-prompt"], int(options["--shell-timeout"]))

	power_re = re.compile(r"^\s*Power: (.*?)\s*$")
	status = "unknown"
	for line in conn.before.splitlines():
		res = power_re.search(line)
		if res != None:
			status = res.group(1)

	if status == "unknown":
		if options.has_key("--missing-as-off"):
			return "off"
		else:
			fail(EC_STATUS)

	return status.lower().strip()
Esempio n. 55
0
def soap_login(options):
	imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
	url = 'https://www.ovh.com/soapi/soapi-re-1.59.wsdl'
	imp.filter.add('http://soapi.ovh.com/manager')
	d = ImportDoctor(imp)

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		soap = Client(url, doctor=d)
		session = soap.service.login(options["--username"], options["--password"], 'en', 0)
	except Exception:
		fail(EC_LOGIN_DENIED)

	options["session"] = session
	return soap
Esempio n. 56
0
def detect_login_telnet(options):
    options["--ipport"] = 23
    re_login_string = r"([\r\n])((?!Last )login\s*:)|((?!Last )Login Name:  )|(username: )|(User Name :)"
    re_login = re.compile(re_login_string, re.IGNORECASE)
    re_pass = re.compile("(password)|(pass phrase)", re.IGNORECASE)

    options["eol"] = "\r\n"
    conn = fencing.fspawn(options, options["--telnet-path"])
    conn.send("set binary\n")
    conn.send("open %s -%s\n"%(options["--ip"], options["--ipport"]))

    conn.log_expect(re_login, int(options["--login-timeout"]))
    conn.send_eol(options["--username"])

    ## automatically change end of line separator
    screen = conn.read_nonblocking(size=100, timeout=int(options["--shell-timeout"]))
    if re_login.search(screen) != None:
        options["eol"] = "\n"
        conn.send_eol(options["--username"])
        conn.log_expect(re_pass, int(options["--login-timeout"]))
    elif re_pass.search(screen) == None:
        conn.log_expect(re_pass, int(options["--shell-timeout"]))

    try:
        conn.send_eol(options["--password"])
        valid_password = conn.log_expect([re_login] + \
                [pexpect.TIMEOUT], int(options["--shell-timeout"]))
        if valid_password == 0:
            ## password is invalid or we have to change EOL separator
            options["eol"] = "\r"
            conn.send_eol("")
            screen = conn.read_nonblocking(size=100, timeout=int(options["--shell-timeout"]))
            ## after sending EOL the fence device can either show 'Login' or 'Password'
            if re_login.search(conn.after + screen) != None:
                conn.send_eol("")
            conn.send_eol(options["--username"])
            conn.log_expect(re_pass, int(options["--login-timeout"]))
            conn.send_eol(options["--password"])
            conn.log_expect(pexpect.TIMEOUT, int(options["--login-timeout"]))
    except KeyError:
        fencing.fail(fencing.EC_PASSWORD_MISSING)

    found_cmd_prompt = guess_prompt(conn, options, conn.before)
    return (found_cmd_prompt, conn)
Esempio n. 57
0
def soap_login(options):
	run_delay(options)

	if "--ssl" in options or "--ssl-secure" in options or "--ssl-insecure" in options:
		if "--ssl-insecure" in options:
			import ssl
			from requests.packages.urllib3.exceptions import InsecureRequestWarning
			if hasattr(ssl, '_create_unverified_context'):
				ssl._create_default_https_context = ssl._create_unverified_context
			requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
			verify = False
		else:
			verify = True
		url = "https://"
	else:
		verify = False
		url = "http://"

	url += options["--ip"] + ":" + str(options["--ipport"]) + "/sdk"

	tmp_dir = tempfile.mkdtemp()
	tempfile.tempdir = tmp_dir
	atexit.register(remove_tmp_dir, tmp_dir)

	try:
		headers = {"Content-Type" : "text/xml;charset=UTF-8", "SOAPAction" : ""}
		conn = Client(url + "/vimService.wsdl", location=url, transport=RequestsTransport(verify=verify), headers=headers)

		mo_ServiceInstance = Property('ServiceInstance')
		mo_ServiceInstance._type = 'ServiceInstance'
		ServiceContent = conn.service.RetrieveServiceContent(mo_ServiceInstance)
		mo_SessionManager = Property(ServiceContent.sessionManager.value)
		mo_SessionManager._type = 'SessionManager'

		conn.service.Login(mo_SessionManager, options["--username"], options["--password"])
	except requests.exceptions.SSLError as ex:
		fail_usage("Server side certificate verification failed")
	except Exception:
		fail(EC_LOGIN_DENIED)

	options["ServiceContent"] = ServiceContent
	options["mo_SessionManager"] = mo_SessionManager
	return conn
Esempio n. 58
0
	def run_command(self, command, additional_timeout=0):
		try:
			logging.debug("%s\n", command)

			(res_output, res_code) = frun(command,
					int(self.options["--shell-timeout"]) +
					int(self.options["--login-timeout"]) +
					additional_timeout, True)

			if res_code == None:
				fail(EC_TIMED_OUT)

			logging.debug("%s\n", res_output)

			if (res_code != 0) or (re.search("^Error ", res_output, re.MULTILINE) != None):
				fail_usage("Returned %d: %s"% (res_code, res_output))
		except pexpect.ExceptionPexpect:
			fail_usage("Cannot run command %s"%(command))

		return res_output
Esempio n. 59
0
def vmware_run_command(options, add_login_params, additional_params, additional_timeout):
	command = vmware_prepare_command(options, add_login_params, additional_params)

	try:
		logging.debug("%s\n", command)

		(res_output, res_code) = frun(command,
				int(options["--shell-timeout"]) + int(options["--login-timeout"]) + additional_timeout, True)

		if res_code == None:
			fail(EC_TIMED_OUT)
		if res_code != 0 and add_login_params:
			logging.debug("%s\n", res_output)
			fail_usage("%s returned %s"% (options["--exec"], res_output))
		else:
			logging.debug("%s\n", res_output)

	except pexpect.ExceptionPexpect:
		fail_usage("Cannot run command %s"% (options["--exec"]))

	return res_output
Esempio n. 60
0
def get_power_status(_, options):
    client = pywsman.Client(options["--ip"], int(options["--ipport"]), \
                            '/wsman', 'http', 'admin', options["--password"])
    namespace = CIM_AssociatedPowerManagementService
    client_options = pywsman.ClientOptions()
    doc = client.get(client_options, namespace)
    _SOAP_ENVELOPE = 'http://www.w3.org/2003/05/soap-envelope'
    item = 'Fault'
    fault = xml_find(doc, _SOAP_ENVELOPE, item)
    if fault is not None:
        logging.error("Failed to get power state for: %s port:%s", \
                      options["--ip"], options["--ipport"])
        fail(EC_STATUS)

    item = "PowerState"
    try: power_state = xml_find(doc, namespace, item).text
    except AttributeError:
        logging.error("Failed to get power state for: %s port:%s", \
                      options["--ip"], options["--ipport"])
        fail(EC_STATUS)
    if power_state == POWER_ON:
        return "on"
    elif power_state == POWER_OFF:
        return "off"
    else:
        fail(EC_STATUS)