python调用ambari rest api刷新节点客户端配置

# -- coding:UTF-8 --

"""

参考: https://github.com/apache/ambari/blob/trunk/ambari-server/docs/api/v1/
参考: https://community.cloudera.com/t5/Support-Questions/How-to-restart-refresh-client-config-on-all-the-hosts-using/td-p/277334
参考: https://cwiki.apache.org/confluence/display/AMBARI/Restarting+host+components+via+the+API


"""

import requests, json
import time

ambari_ip = input("请输入ambari-server ip:")
cluster_name = input("请输入ambari cluster name:")
user = input("请输入ambari-server 账号:")
passwd = input("请输入ambari-server mm:")
# "http://your.ambari.server/api/v1/clusters/c1 ,拼接处基本的请求url

control_url = "http://{}:8080/api/v1/clusters/{}/hosts".format(ambari_ip, cluster_name)

requests_url = "http://{}:8080/api/v1/clusters/{}/requests".format(ambari_ip, cluster_name)
AUTH = (user, passwd)


def getHosts():
    hosts = []
    try:
        rep = requests.get(control_url, auth=AUTH)
        # 如果状态码是20x 则获取成功
        if (str(rep.status_code).startswith("20")):
            jsonrep = json.loads(rep.text)
            items = jsonrep['items']
            for itemjson in items:
                hosts.append(itemjson['Hosts']['host_name'])
        else:
            # 没有正常获取到状态
            print("无法访问该链接:%s" % rep)
    except Exception as e:
        print("===================异常发生==========================")
    return hosts


def getComponentStatus(host, component):
    get_component_status_url = control_url + "/{}/host_components/{}".format(host, component)

    try:
        rep = requests.get(get_component_status_url, auth=AUTH)
        if (str(rep.status_code).startswith("20")):
            jsonrep = json.loads(rep.text)
            status = jsonrep['HostRoles']['stale_configs']
            return status
        else:
            print("无法访问该链接:%s" % rep)

    except Exception as e:
        print("getComponentStatus方法有异常")


def getHostComponentsStatus(host):
    '''
    :param host:
    :return: component_dict  组件与其状态
    '''

    component_dict = {}
    get_host_components_status_url = control_url + "/{}/host_components".format(host)

    try:
        rep = requests.get(get_host_components_status_url, auth=AUTH)
        # 如果状态码是20x 则获取成功
        # print (rep.status_code)

        if (str(rep.status_code).startswith("20")):
            jsonrep = json.loads(rep.text)
            items = jsonrep['items']
            for itemjson in items:
                component = itemjson['HostRoles']['component_name']
                # 只要client 角色
                if  component != "OOZIE_CLIENT" and "CLIENT" in component or component == "HCAT":
                    compent_status = getComponentStatus(host, component)
                    if compent_status == True:
                        component_dict[component] = compent_status
        else:
            # 没有正常获取到状态
            print("无法访问该链接:%s" % get_host_components_status_url)
    except Exception as e:
        print("===================异常发生==========================")
    return component_dict


# 刷新客户端配置
def refreshClient(host_list, cluster_name):
    body = {}
    body["RequestInfo"] = {"command": "RESTART", "context": " RREFRESH CLIENT",
                           "operation_level": {"level": "HOST", "cluster_name": "{}".format(cluster_name)}}
    Client_list = []
    for host in host_list:
        component_dict = getHostComponentsStatus(host)

        # change_compent_url = control_url + "/{}/host_components".format(host)
        headers = {
            'X-Requested-By': 'X-Requested-By: ambari'
        }

        for k in component_dict:
            if "HCAT" in k:
                service = "HIVE"
            else:
                service = str(k).split("_")[0]
            Client_list.append({"service_name": "{}".format(service), "component_name": "{}".format(k),
                                "hosts": "{}".format(host)})
    if Client_list:
        body["Requests/resource_filters"] = Client_list
        data = json.dumps(body)
        rep = requests.post(requests_url, data=data, auth=AUTH, headers=headers)
        print (rep.status_code)
        print (rep.text)
        print(rep.json())
    else:
        print("没有需要更新配置的客户端")


if __name__ == '__main__':
    host_list = getHosts()
    refreshClient(host_list, cluster_name)

 

你可能感兴趣的:(大数据运维之python日常)