使用CDH的api接口对cdh服务进行滚动重启

因为企业版的licence的过期了。无法在界面上滚动重启。同时cdh的大数据服务对用户都是黑盒。无法直接操作。写了个py脚本实现此功能

import time
import requests
import json
import sys
#可操作的服务列表
server_list=['hdfs','yarn','zookeeper','hbase','spark_on_yarn','hive','impala','sentry','hue','kafka','solr']
#可操作的动作
operator_list=['start','stop','restart']
#服务器id
hostid = []
#服务器上的角色
host_role = []
#用户名
user = 'admin'
#密码
passwd = 'admin'
urls = 'http://192.168.1.1:7180'
#集群名称
cluster = 'TEST_pro'
#执行脚本跟随的第一个选项,在可操作的服务列表选择
role_name=sys.argv[1]
if role_name not in server_list:
    print('能操作的服务不存在,只能在'+server_list+'中选择')
    exit()
#执行脚本跟随的第一个选项,在可操作的动作列表选择
command=sys.argv[2]
if command not in operator_list:
    print('能操作的动作不存在,只能在'+operator_list+'中选择')
    exit()
#用来匹配状态
if operator_list =='start':
    operator_status='STARTED'
if operator_listl == 'restart':
    operator_status = 'STARTED'
if operator_list == 'stop':
    operator_status = 'STOPPED'

all_info = requests.get(urls + '/api/v33/hosts', auth=(user, passwd))
hosts = json.loads(all_info.text)
f = dict(hosts)
f2 = f['items']
# 取到所有的主机id,用主机id获取role_id
for i in f2:
    hostid.append(i['hostId'])
for server in hostid:
    roles = requests.get(urls+'/api/v33/hosts/'+server, auth=(user, passwd))
    role = json.loads(roles.text)
    f = dict(role)
    f2 = f['roleRefs']
    for i in f2:
        host_role.append(i['roleName'])

character ='GATEWAY'
# 去掉gateway
host_role = [item for item in host_role if character not in item]
#取出需要的服务role
use_role= [item for item in host_role if role_name in item]
print(role_name+'有'+str(len(use_role))+'个节点')

for service in use_role:
    service =[service]

    def restart():
        print('正在操作'+str(service))
        url = urls + '/api/v33/clusters/' + cluster + '/services/'+ role_name + '/roleCommands/'+ command
        header ={
            'Content-Type' : 'application/json',
            'Accept' : 'application/json'
        }
        auth =(user, passwd)
        payload = {
            'items': service
        }
        response = requests.post(
            url=url,
            headers=header,
            auth=auth,
            data=json.dumps(payload)
        ).json()

    restart()
    service = str(service[0])

    def status_check():
        role_status = requests.get(
            urls + '/api/v33/clusters/'+ cluster + '/services/'+ role_name + '/roles/'+ service,auth=(user,passwd))
        role_status = json.loads(role_status.text)
        role_status = dict(role_status)
        return (role_status['roleState'])

    while status_check() != operator_status:
        time.sleep(30)
    else:
        continue

你可能感兴趣的:(大数据,python)