python腳本實現(xiàn)阿里云自動擴容

腳本位置:

zice服務(wù)器

/home/jerry/aliexpension/trigger.py  #服務(wù)器創(chuàng)建觸發(fā)器腳本
/home/jerry/aliexpension/deploy_mobile.sh  #自動部署腳本
/home/jerry/aliexpension/phj-web-aliexpansion.jar  #鄭敏的創(chuàng)建服務(wù)器腳本

腳本通過調(diào)用zabbix的API獲取監(jiān)控服務(wù)器的CPU段只、內(nèi)存和磁盤的觸發(fā)器狀態(tài)

狀態(tài)異常則觸發(fā)trigger.py腳本剥懒,調(diào)用鄭敏的金融云服務(wù)器創(chuàng)建腳本進行服務(wù)器的創(chuàng)建并調(diào)用部署部署shell腳本部署生產(chǎn)代碼瞧栗。

處理流程

服務(wù)器CPU宗挥、內(nèi)存索昂、磁盤其中任何一項發(fā)生警報-->觸發(fā)trigger.py腳本-->調(diào)用鄭敏服務(wù)器創(chuàng)建腳本窝撵,創(chuàng)建完畢服務(wù)器-->調(diào)用自動部署腳本部署完畢蝶缀。

trigger.py腳本報警邏輯

  • 當服務(wù)器異常導(dǎo)致觸發(fā)創(chuàng)建服務(wù)器的動作后丹喻,等待30s進行服務(wù)器創(chuàng)建
  • 在創(chuàng)建完畢第一個服務(wù)器后的6個小時內(nèi)不會再進行創(chuàng)建服務(wù)器
  • 若服務(wù)器異常一直持續(xù)了6個小時,則會在6個小時后創(chuàng)建第二個服務(wù)器翁都,邏輯返回到第一步碍论,以此類推。

trigger.py 腳本內(nèi)容:

vim /home/jerry/aliexpension/trigger.py

#導(dǎo)入腳本運行所需模塊
import requests, json, time, pickle, os
#獲取當前時間
def getcurrenttime(arg):
    if arg == 's':
        t = time.time()
    elif arg == 'd':
        t = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    else:
        print(arg+'時間獲取出錯')
    return t
headers = {'Content-Type': 'application/json-rpc'}
url = 'http://zabbix.puhuijia.com/zabbix/api_jsonrpc.php'
#url = 'http://10.2.2.19/pxzabbix/api_jsonrpc.php' '''測試環(huán)境地址'''
'''獲取驗證zabbix身份信息的token柄慰,返回token值'''
def getToken(username='zhaoliang', passwd='zhaoliang123'):
    '''獲取登陸zabbixapi的token信息鳍悠,返回token的值'''
    data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": username,
            "password": passwd
        },
        "id": 1
    }
    request = requests.post(url=url, headers=headers,data=json.dumps(data))
    dict = json.loads(request.text)
    return dict['result']

'''獲取某個服務(wù)器的某個觸發(fā)器的狀態(tài)信息税娜,返回0或者1,0表示狀態(tài)正常藏研,1表示狀態(tài)異常'''
def getstatus(token,hostid,triggerid):
    '''獲取服務(wù)器監(jiān)控項item的狀態(tài),即是否被觸發(fā),被觸發(fā)返回1,沒被觸發(fā)返回0'''
    data = {
        "jsonrpc": "2.0",
        "method": "trigger.get",
        "params": {
            "triggerids": triggerid,
            "hostids": hostid,
            "output": "extend",
            "selectFunctions": "extend"
        },
        "id": 1,
        "auth": token,
    }
    request = requests.post(url=url, headers=headers, data=json.dumps(data))
    dict = json.loads(request.text)
    return dict['result'][0]['value']

'''要監(jiān)控的zabbix服務(wù)器信息'''
def monitoredhost(token=getToken()):
    '''通過myhost和triggername兩個列表來生成一個字典敬矩,它包含了我們所有需要監(jiān)控的服務(wù)器的監(jiān)控項,返回所有服務(wù)器信息字典'''
    myhost = ['dubbo1','dubbo2','dubbo3','dubbo4','dubbo5','dubbo6','dubbo7','dubbo8','dubbo9','dubbo10','web-mobile1','web-mobile2','web_back1','web_back2']
    triggername = ["{HOST.NAME}服務(wù)器可用內(nèi)存不足","{HOST.NAME}處理器負載過高","本機tomcat已3分鐘不可用"]
    data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["host","hostid"],
        },
        "id": 1,
        "auth": token
    }
    request = requests.post(url=url, headers=headers, data=json.dumps(data))
    hosts = json.loads(request.text)
    items = {}
    for i in hosts['result']:
        hostid = i['hostid']
        hostname = i['host']
        if hostname in myhost:
            items[hostname] = {"id":hostid, "triggers":{}}
            data = {
                "jsonrpc": "2.0",
                "method": "trigger.get",
                "params": {
                    'hostids': hostid
                },
                "id": 1,
                "auth": token
            }
            request = requests.post(url=url, headers=headers, data=json.dumps(data))
            dict = json.loads(request.text)
            for m in dict['result']:
                if m["description"] == triggername[0]:
                    items[hostname]["triggers"]["mem"] = m["triggerid"]
                elif m["description"] == triggername[1]:
                    items[hostname]["triggers"]["cpu"] = m["triggerid"]
                elif m["description"] == triggername[2]:
                    items[hostname]["triggers"]["heap"] = m["triggerid"]
                else:
                    continue

    return  items
def findall():
    '''返回異常服務(wù)器信息的字典,若無異常則返回0'''
    excep = {}
    error = 0
    items = monitoredhost()
    for host in items:
        excep[host] = {}
        for trigger in items[host]['triggers']:
            hostid = items[host]['id']
            triggerid = items[host]['triggers'][trigger]
            status = getstatus(token=getToken(),hostid=hostid,triggerid=triggerid)
            if status == str(0):
                '''狀態(tài)正常error=0'''
                print('{time} INFO:主機---> {0} 的觸發(fā)器 {1} 狀態(tài)為 {2} 正常'.format(host, trigger, status,time=getcurrenttime('d')))
            elif status == str(1):
                '''狀態(tài)異常error=1,隨后返回異常服務(wù)器信息的字典'''
                error = 1
                print('{time} INFO:主機---> {0} 的觸發(fā)器 {1} 狀態(tài)為 {2} 發(fā)生異常'.format(host, trigger, status,time=getcurrenttime('d')))
                excep[host][trigger] = triggerid
            else:
                return 1
    if error == 1:
        return excep
    else:
        return 0

def createcheck(hostname,hoststatus=1):
    '''檢查服務(wù)器當前狀態(tài)是否需要創(chuàng)建新的服務(wù)器,返回0表示需要進行服務(wù)器創(chuàng)建,返回1表示無需創(chuàng)建服務(wù)器'''
    status = 1
    if os.path.isfile('hoststatus.pkl'):
        '''文件已存在'''
        pass
    else:
        '''新建pkl文件'''
        f = open('hoststatus.pkl', 'w')
        f.close()
    if os.path.getsize('hoststatus.pkl') != 0:
        with open('hoststatus.pkl', 'rb') as fr:
            s = pickle.load(fr)
            s1 = s.copy()
        with open('hoststatus.pkl', 'wb') as f:
            if hostname in s1:
                s1[hostname]['time2'] = getcurrenttime('s')
                timecha = s1[hostname]['time2'] - s1[hostname]['time1']
                if timecha >= 30 and s1[hostname]['hoststatus'] == 1:
                    s1[hostname]['hoststatus'] = 0
                    print('{time} 首次觸發(fā)創(chuàng)建服務(wù)器 {0}'.format(hostname, time=getcurrenttime('d')))
                    status =  0
                elif timecha >=36000 and s1[hostname]['hoststatus'] == 0:
                    s1[hostname]['hoststatus'] = 1
                    s1[hostname]['time1'] = getcurrenttime('s')
                    print('{time} 異常已持續(xù)6小時,再次觸發(fā)創(chuàng)建服務(wù)器 {0}'.format(hostname, time=getcurrenttime('d')))
                    status = 0
                elif timecha < 30 and s1[hostname]['hoststatus'] == 1:
                    print('{time} 主機 {0} 正在等待30s'.format(hostname, time=getcurrenttime('d')))
                    status = 1
                elif timecha < 30 and s1[hostname]['hoststatus'] == 0:
                    print('{time} 主機 {0} 出現(xiàn)異常ERROR'.format(hostname, time=getcurrenttime('d')))
                    status = 1
                elif 36000 > timecha >= 30 and s1[hostname]['hoststatus'] == 0:
                    print('{time} 主機 {0} 狀態(tài)異常且在監(jiān)控中, 持續(xù)時間為 {1} 分鐘, {2} 分鐘后若持續(xù)保持異常狀態(tài)則會新建服務(wù)器.'.format(hostname,int(timecha/60),int(600-timecha/60),time=getcurrenttime('d')))
                    status = 1

            else:
                print('{time} 主機 {0} 首次出現(xiàn)異常,已添加到文件中.'.format(hostname, time=getcurrenttime('d')))
                s1[hostname] = {}
                s1[hostname]['time1'] = getcurrenttime('s')
                s1[hostname]['hoststatus'] = 1
                print('{time} 服務(wù)器狀態(tài)異常等待,若持續(xù)30s則創(chuàng)建服務(wù)器遥倦,等待30s......'.format(time=getcurrenttime('d')))
                status = 1
            pickle.dump(s1, f)
            return status

    else:
        print('pkl文件大邪:{0} 為空,初始化pkl文件'.format(os.path.getsize('hoststatus.pkl')))
        time = getcurrenttime('s')
        info = {}
        info[hostname] = {}
        info[hostname]['time1'] = time
        info[hostname]['hoststatus'] = 0
        with open('hoststatus.pkl', 'wb') as f1:
            pickle.dump(info, f1)
        print('{time} 服務(wù)器狀態(tài)異常等待,若持續(xù)30s則創(chuàng)建服務(wù)器袒哥,等待30s......'.format(time=getcurrenttime('d')))
    return 1

def dubboapi():
    '''調(diào)用阿里云自動擴容dubbo服務(wù)器的url'''
    requests.get('http://localhost:7777/create_ecs_instance?instance_type=1')
    print('{time} 創(chuàng)建新的dubbo服務(wù)器完畢缩筛!'.format(time=getcurrenttime('d')))
def webmobileapi():
    '''調(diào)用阿里云自動擴容web服務(wù)器的url'''
    requests.get('http://localhost:7777/create_ecs_instance?instance_type=2')
    print('{time} 創(chuàng)建新的web服務(wù)器完畢!'.format(time=getcurrenttime('d')))


def createserver():
    '''主體函數(shù),用來將所有函數(shù)串聯(lián)起來'''
    print('{time} 開始進行狀態(tài)檢查.'.format(time=getcurrenttime('d')))
    result = findall()
    if result == 0:
        print('{time} 本次狀態(tài)檢查沒有發(fā)現(xiàn)有異常.'.format(time=getcurrenttime('d')))
    elif result == 1:
        print('{time} 本次狀態(tài)檢查沒有發(fā)現(xiàn)有異常,返回值為1.'.format(time=getcurrenttime('d')))
    else:
        for i in result:
            if 'dubbo' in i and result[i].get('trigger', 0):
                if createcheck(i, hoststatus=1) == 0:
                    for j in result[i]:
                        print('{time} {i} 服務(wù)器 {j} 參數(shù)值超過閾值,準備新建服務(wù)器.'.format(time=getcurrenttime('d'), j=j, i=i))
                    dubboapi()
                else:
                    continue
            elif 'mobile' in i and result[i].get('trigger', 0):
                if createcheck(i, hoststatus=1) == 0:
                    for j in result[i]:
                        print('{time} {i} 服務(wù)器 {j} 參數(shù)值超過閾值,準備新建服務(wù)器.'.format(time=getcurrenttime('d'), j=j, i=i))
                    webmobileapi()
                else:
                    continue
            elif 'web_back' in i and result[i].get('trigger', 0):
                pass

while True:
    createserver()
    time.sleep(30)

deploy_mobile.sh 腳本內(nèi)容

vim /home/jerry/aliexpension/deploy_mobile.sh

#!/bin/bash
# script usage:
#command line------> sh scriptname.sh IP TYPE
#DESCRIPTION
#           scriptname.sh:  the name of this script
#           IP:  the IP address of new server
#           TYPE:
#                1    the project type of web
#                2    the project type of dubbo

dubbo() {
hostname=dubbo`date +%m%d%H%M%S`
ssh -o StrictHostKeyChecking=no -p 20022 $1 "ls"
scp -P 20022 /etc/init.d/dubbo $1:/home/jerry/
ssh -o StrictHostKeyChecking=no -p 20022 $1 "/bin/expect <<EOF
spawn su - root
expect \"assword\"
send \"Puhuijia@123\r\"
send \"hostnamectl set-hostname ${hostname}\r\"
send \"mkdir -p /alidata/puhuijia/puhuijia_mobile_log/ /dubbo_provider/log /alidata/puhuijia/puhuijia_mobile_properties /dubbo_provider/service_mobile\r\"
send \"chown -R jerry:jerry /dubbo_provider/\r\"
send \"chown -R jerry:jerry /alidata/\r\"
send \"rm -rf /etc/init.d/dubbo\r\"
send \"cp -rf /home/jerry/dubbo /etc/init.d/\r\"
send \"echo $1 $hostname >> /etc/hosts\r\"
expect eof
EOF"
ssh -p 20022 $1 "rm -rf /dubbo_provider/service_mobile/*"
rsync -e  'ssh -p 20022' -avz /dubbo_provider/service_mobile/ $1:/dubbo_provider/service_mobile/
rsync -e  'ssh -p 20022' -avz /home/jerry/aliexpension/puhuijia_mobile_properties/ $1:/alidata/puhuijia/puhuijia_mobile_properties/
ssh -p 20022 $1 "/etc/init.d/dubbo service_mobile restart"
}
web() {
hostname=web_mobile`date +%m%d%H%M%S`
ssh -o StrictHostKeyChecking=no -p 20022 $1 "ls"
scp -P 20022 /etc/init.d/tomcat $1:/home/jerry/
ssh -o StrictHostKeyChecking=no -p 20022 $1 "/bin/expect <<EOF
spawn su - root
expect \"assword\"
send \"Puhuijia@123\r\"
send \"hostnamectl set-hostname ${hostname}\r\"
send \"mkdir -p /alidata/puhuijia/puhuijia_mobile_log/ /alidata/puhuijia/puhuijia_mobile_properties\r\"
send \"tar -zxvf /usr/local/soft/apache-tomcat-8.0.36.tar.gz -C /usr/local/\r\"
send \"mv -f /usr/local/apache-tomcat-8.0.36 /usr/local/tomcat_mobile\r\"
send \"chown -R jerry:jerry /usr/local/tomcat_mobile\r\"
send \"rm -rf /etc/init.d/tomcat\r\"
send \"cp -rf /home/jerry/tomcat /etc/init.d/\r\"
send \"echo $1 $hostname >> /etc/hosts\r\"
expect eof
EOF"
ssh -p 20022 $1 "rm -rf /usr/local/tomcat_mobile/webapps/*"
rsync -e 'ssh -p 20022' -avz /usr/local/tomcat_zice/webapps/app $1:/usr/local/tomcat_mobile/webapps/
rsync -e  'ssh -p 20022' -avz /home/jerry/aliexpension/puhuijia_mobile_properties/ $1:/alidata/puhuijia/puhuijia_mobile_properties/
ssh -p 20022 $1 "cd /usr/local/tomcat_mobile/bin;mv catalina.sh catalina.sh.bak${hostname};wget https://coding.net/u/himan/p/staticfile/git/raw/master/catalina.sh;sed -i  's/\r//' catalina.sh;chmod 755 catalina.sh"
ssh -p 20022 $1 "/etc/init.d/tomcat tomcat_mobile restart"
ssh -p 20022 $1 "/etc/init.d/tomcat tomcat_mobile restart"
}



case $2 in
1)
  web $1
;;
2)
  dubbo $1
;;
esac
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末堡称,一起剝皮案震驚了整個濱河市瞎抛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌却紧,老刑警劉巖桐臊,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異晓殊,居然都是意外死亡断凶,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門巫俺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來认烁,“玉大人,你說我怎么就攤上這事介汹∪次耍” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵嘹承,是天一觀的道長窗价。 經(jīng)常有香客問我,道長叹卷,這世上最難降的妖魔是什么撼港? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮豪娜,結(jié)果婚禮上餐胀,老公的妹妹穿的比我還像新娘。我一直安慰自己瘤载,他們只是感情好否灾,可當我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著鸣奔,像睡著了一般墨技。 火紅的嫁衣襯著肌膚如雪惩阶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天扣汪,我揣著相機與錄音断楷,去河邊找鬼。 笑死崭别,一個胖子當著我的面吹牛冬筒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播茅主,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼舞痰,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了诀姚?” 一聲冷哼從身側(cè)響起响牛,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎赫段,沒想到半個月后呀打,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡糯笙,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年贬丛,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片给涕。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡瘫寝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稠炬,到底是詐尸還是另有隱情,我是刑警寧澤咪啡,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布首启,位于F島的核電站,受9級特大地震影響撤摸,放射性物質(zhì)發(fā)生泄漏毅桃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一准夷、第九天 我趴在偏房一處隱蔽的房頂上張望钥飞。 院中可真熱鬧,春花似錦衫嵌、人聲如沸读宙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽结闸。三九已至唇兑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間桦锄,已是汗流浹背扎附。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留结耀,地道東北人留夜。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像图甜,于是被迫代替她去往敵國和親碍粥。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容