授之以漁-運(yùn)維平臺(tái)發(fā)布模塊二(Jenkins篇)

接上篇《授之以漁-運(yùn)維平臺(tái)發(fā)布模塊一(Jenkins篇)》冕茅,今天介紹下結(jié)合著Saltstack的MasterEven驹饺,用來做發(fā)布系統(tǒng)的結(jié)果監(jiān)控。

一民镜、Event介紹

SaltStack 0.10版本中, 新增了Event系統(tǒng), 官方在 Release Notes 對(duì)其描述如下:

The Salt Master now comes equipped with a new event system. This event system has replaced some of the back end of the Salt client and offers the beginning of a system which will make plugging external applications into Salt. The event system relies on a local ZeroMQ publish socket and other processes can connect to this socket and listen for events. The new events can be easily managed via Salt's event library.
同時(shí)官方也在 Salt Event系統(tǒng) 頁(yè)面中提供了監(jiān)聽event的例子程序, 基于其進(jìn)行下Event系統(tǒng)學(xué)習(xí).
我們所需要的就是監(jiān)聽event,然后把結(jié)果存儲(chǔ)到Mysql单起,Redis之類搏嗡,以便于我們后續(xù)進(jìn)行處理。

二佣耐、Event代碼:

import salt.utils.event
import redis

def redis_conect_db6():
    try:
        r = redis.StrictRedis('172.18.11.126', 6379, 6)
    except:
        pass
    return r

event = salt.utils.event.MasterEvent('/var/run/salt/master')
for data in event.iter_events(full=True):
    r = redis_conect_db6()
    ret = data['data']
    if 'salt/job/' in data['tag']:
        if ret.has_key("id") and ret.has_key("return") and ret.has_key("fun") :
            if ret['fun'] != 'mine.update':
                if len(ret['fun_args']) >0 and 'wwwlogs' not in ret['fun_args'][0]:
                    print data
                    print "====================================================="
                    if ret['fun'] == 'pkg.get_repo' and ret['return'] != {}:
                        r.set('%s:%s-%s'%(ret['return']['name'],ret['id'],ret['fun']), ret)
                    elif ret['fun'] == 'pkg.upgrade_available' :
                        r.set('%s:%s-%s'%(ret['fun_args'][0],ret['id'],ret['fun']), ret)
                    elif ret['fun'] == 'pkg.install' and ret['return'] != {}:
                        r.set('%s:%s-%s'%(ret['fun_args'][0],ret['id'],ret['fun']), ret)

這段event腳本的大體實(shí)現(xiàn)了過濾一些非必要信息政勃,把fun中包含pkg.get_repo(驗(yàn)證Yum是否存在),pkg.upgrade_available(驗(yàn)證Yum是否更新)兼砖,pkg.install(安裝)存儲(chǔ)到Redis中奸远。然后我只需要去Redis中取出數(shù)據(jù),并通過highcharts.js匯出圖即可讽挟。

三懒叛、后端處理Redis數(shù)據(jù)繪圖代碼:

@login_required
@my_permissionVerify
def release_status(request):
    if 'id' in request.GET:
        svn_name = request.GET['id']
        Svn_name = Svn.objects.get(svn_name = svn_name)
        r = redis_conect_db6()
        svn_list = []
        nodes = [{"area":0,"status":2,"no":0,"parent":[],"label":"%s" % str(Svn_name.svn_name)}]
        for svn_host in (Svn_name.svn_hosts).split(','):
            area_dict1 = {}
            area_dict2 = {}
            area_dict3 = {}
            svn_list_dict = {}
            area_dict1["area"] = 1
            area_dict1["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
            area_dict1["label"] = "%s" % str(svn_host)
            area_dict1["parent"] = [{"parea":0,"pno":0}]
            area_dict1["status"] = 0
            nodes.append(area_dict1)
            area_dict2["area"] = 2
            area_dict2["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
            area_dict2["label"] = "%s" % str(svn_host)
            area_dict2["parent"] = [{"parea":1,"pno":int(area_dict2["no"])}]
            area_dict2["status"] = 0
            nodes.append(area_dict2)
            area_dict3["area"] = 3
            area_dict3["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
            area_dict3["label"] = "%s" % str(svn_host)
            area_dict3["parent"] = [{"parea":2,"pno":int(area_dict3["no"])}]
            area_dict3["status"] = 0
            nodes.append(area_dict3)
            """排除同一個(gè)主機(jī),多個(gè)項(xiàng)目"""
            try:
                if str(Svn_name) in r.get('%s:%s-%s' % (svn_name, svn_host,'pkg.get_repo')):
                    nodes[0] = {"area":0,"status":3,"no":0,"parent":[],"label":"%s" % str(Svn_name.svn_name)}

                    if nodes[0]['status'] == 3:
                        area_dict1["status"] = 2
                        try:
                            if json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.get_repo')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['success'] == "True":
                                area_dict1["status"] = 3
                            else:
                                area_dict1["status"] = 1
                        except:
                            area_dict1["status"] = 0
                        area_dict1["area"] = 1
                        area_dict1["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
                        area_dict1["label"] = "%s" % str(svn_host)
                        area_dict1["parent"] = [{"parea":0,"pno":0}]
                        svn_list_dict['host'] = svn_host
                        svn_list_dict['name'] = Svn_name
                        svn_list_dict["release_svn"] = Svn_name.svn_no

                        """添加檢測(cè)YUM源存在時(shí)間"""
                        try:
                            svn_list_dict['get_repo_time'] = json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.get_repo')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['_stamp_localtime']
                        except:
                            svn_list_dict['get_repo_time'] = ''
                        nodes.append(area_dict1)
                        print 'nodes,',nodes[1]['status']
                    else:
                        area_dict1["status"] = 0

                    if nodes[1]['status'] == 3:
                        area_dict2["status"] = 2
                        try:
                            if json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.upgrade_available')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['success'] == "True":
                                area_dict2["status"] = 3
                            else:
                                area_dict2["status"] = 1
                        except:
                            area_dict2["status"] = 2
                        area_dict2["area"] = 2
                        area_dict2["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
                        area_dict2["label"] = "%s" % str(svn_host)
                        area_dict2["parent"] = [{"parea":1,"pno":int(area_dict2["no"])}]

                        """添加RPM檢測(cè)更新時(shí)間"""
                        try:
                            svn_list_dict['upgrade_available'] = json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.upgrade_available')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['_stamp_localtime']
                        except:
                            svn_list_dict['upgrade_available'] = ''
                        nodes.append(area_dict2)
                    else:
                        area_dict2["status"] = 0

                    if nodes[2]['status']  == 3:
                        area_dict3["status"] = 2
                        try:
                            if json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.install')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['success'] == "True":
                                if json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.install')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['return']['%s'% svn_name]['old'] != '':
                                    release_old = json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.install')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['return']['%s'% svn_name]['old'].split('-')[0]
                                else:
                                    release_old = 0
                                try:
                                    release_new = json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.install')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['return']['%s'% svn_name]['new'].split('-')[0]
                                except:
                                    release_new = ''
                                if (int(release_old)+1 == int(release_new)) and (int(release_new) == int(Svn_name.svn_no)):
                                    area_dict3["status"] = 3
                                elif int(release_old) == int(release_new):
                                    area_dict3["status"] = 2
                                else:
                                    area_dict3["status"] = 1
                            else:
                                area_dict3["status"] = 1
                        except:
                            area_dict3["status"] = 2
                        area_dict3["area"] = 3
                        area_dict3["no"] = (Svn_name.svn_hosts).split(',').index(svn_host)
                        area_dict3["label"] = "%s" % str(svn_host)
                        area_dict3["parent"] = [{"parea":2,"pno":int(area_dict3["no"])}]
                        """添加RPM安裝時(shí)間"""
                        try:
                            svn_list_dict['install'] = json.loads(r.get('%s:%s-%s' % (svn_name, svn_host, 'pkg.install')).replace("'", "\"").replace('True','"True"').replace('False','"False"'))['_stamp_localtime']

                            svn_list_dict["release_new"] = release_new
                        except:
                            svn_list_dict['install'] = ''

                        nodes.append(area_dict3)
                    else:
                        area_dict3["status"] = 0
                else:
                    pass
                svn_list.append(svn_list_dict)
            except Exception as err:
                print 'Release_status_err:',err
        return render_to_response('myrelease/release_status.html',{'svn_list':svn_list,'nodes':nodes},context_instance=RequestContext(request))
    else:
        return render_to_response('myrelease/release_status.html',context_instance=RequestContext(request))

這段代碼大體實(shí)現(xiàn)了通過判斷pkg.get_repo(驗(yàn)證Yum是否存在)耽梅,pkg.upgrade_available(驗(yàn)證Yum是否更新)薛窥,pkg.install(安裝)返回的狀態(tài),來輸出不同的status褐墅,前端會(huì)根據(jù)不同的status拆檬,繪制不同的顏色。

四妥凳、效果圖:

Paste_Image.png

五竟贯、前端代碼:

<script type="text/javascript">
    $(function () {
        var chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container_drawing',
                events: {
                    load: drawing
                }
            },
            title: {
                text: ''
            }
        });
    });
    /* 畫圖自定義函數(shù) */
    function drawing(){
        // Draw the flow chart
        var ren = this.renderer;
        var rightArrow = ['M', 0, 0, 'L', 100, 0, 'L', 95, 5, 'M', 100, 0, 'L', 95, -5];
        var colors = ['#2570a1','#d71345','#decb00','#1d953f'];//四種狀態(tài)對(duì)應(yīng)的顏色:未啟動(dòng),告警,正在運(yùn)行,完成

        // 分割線1
        ren.path(['M', 270, 40, 'L', 270, 600]).attr({'stroke-width': 3,stroke: 'silver',dashstyle: 'dash'}).add();
        // 分割線2
        ren.path(['M', 520, 40, 'L', 520, 600]).attr({'stroke-width': 3,stroke: 'silver',dashstyle: 'dash'}).add();
        // 分割線3
        ren.path(['M', 770, 40, 'L', 770, 600]).attr({'stroke-width': 3,stroke: 'silver',dashstyle: 'dash'}).add();
        // 分割線4
//        ren.path(['M', 1020, 40, 'L', 1020, 600]).attr({'stroke-width': 3,stroke: 'silver',dashstyle: 'dash'}).add();
        // 分割線5
//        ren.path(['M', 1270, 40, 'L', 1270, 600]).attr({'stroke-width': 3,stroke: 'silver',dashstyle: 'dash'}).add();




        // 區(qū)域標(biāo)題

        ren.label('包構(gòu)建', 110,50).css({fontWeight: 'bold'}).add();
        ren.label('驗(yàn)證源', 370,50).css({fontWeight: 'bold'}).add();
        ren.label('驗(yàn)證包更新', 610, 50).css({fontWeight: 'bold'}).add();
//        ren.label('前置命令', 880, 50).css({fontWeight: 'bold'}).add();
        ren.label('項(xiàng)目包安裝', 880, 50).css({fontWeight: 'bold'}).add();
//        ren.label('后置命令', 1380, 50).css({fontWeight: 'bold'}).add();

        // 遍歷生成圖形
        /**
            area:區(qū)域編碼,值為:0,1,2,null.
            no:節(jié)點(diǎn)序號(hào),值為:0,1,...,N,null.
            label:節(jié)點(diǎn)內(nèi)容.
            status:節(jié)點(diǎn)狀態(tài)值為:0為未執(zhí)行,1為錯(cuò)誤,2為執(zhí)行中,3為執(zhí)行完畢
            parea:父節(jié)點(diǎn)區(qū)域編碼,值為:0,1,2,null.
            pno:父節(jié)點(diǎn)序號(hào),值為:0,1,...,N,null.
        */
//        var nodes = [{"area":5,"status":2,"no":0,"parent":[{"parea":4,"pno":0}],"label":"md25-qnzs-app-13.youth.cn"},{"area":4,"status":3,"no":0,"parent":[{"parea":3,"pno":0}],"label":"md25-qnzs-app-13.youth.cn"},{"area":3,"status":3,"no":0,"parent":[{"parea":2,"pno":0}],"label":"md25-qnzs-app-13.youth.cn"},{"area":2,"status":3,"no":0,"parent":[{"parea":1,"pno":0},{"parea":1,"pno":1}],"label":"md25-qnzs-app-13.youth.cn"},{"area":1,"status":1,"no":0,"parent":[{"parea":0,"pno":0},{"parea":0,"pno":1},{"parea":0,"pno":3}],"label":"md25-qnzs-app-13.youth.cn"},{"area":1,"status":0,"no":1,"parent":[{"parea":0,"pno":1},{"parea":0,"pno":2}],"label":"md25-qnzs-app-13.youth.cn"},{"area":0,"status":0,"no":0,"parent":[],"label":"md25-qnzs-app-13.youth.cn"},{"area":0,"status":1,"no":1,"parent":[],"label":"md25-qnzs-app-13.youth.cn"},{"area":0,"status":2,"no":2,"parent":[],"label":"md25-qnzs-app-13.youth.cn"},{"area":0,"status":1,"no":3,"parent":[],"label":"md25-qnzs-app-13.youth.cn"}];
        var nodes = {% autoescape off %}{{ nodes}}{% endautoescape %}
        for(var i=0;i<nodes.length;i++){
            var node = nodes[i];
            ren.label(node.label, 30+node.area*250, 80+node.no*50).attr({fill: colors[node.status],stroke: '#f2eada','stroke-width': 2,padding: 5,r: 9,width:220,height:20}).css({color: 'white',fontSize:'xx-small',textAlign:'center',fontWeight: 'bold'}).add().shadow(true);
            for(var j=0;j<node.parent.length;j++){
                var parent = node.parent[j];
               ren.path(['M', 30+node.area*250, 75+node.no*50+20, 'L', 2+parent.parea*250+250+10, 75+parent.pno*50+20]).attr({'stroke-width': 2,stroke: '#4169E1'}).translate(0, 0).add();//
            }
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市逝钥,隨后出現(xiàn)的幾起案子屑那,更是在濱河造成了極大的恐慌拱镐,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件持际,死亡現(xiàn)場(chǎng)離奇詭異沃琅,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)蜘欲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門益眉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人姥份,你說我怎么就攤上這事郭脂。” “怎么了澈歉?”我有些...
    開封第一講書人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵展鸡,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我埃难,道長(zhǎng)莹弊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任涡尘,我火速辦了婚禮忍弛,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘悟衩。我一直安慰自己剧罩,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開白布座泳。 她就那樣靜靜地躺著惠昔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪挑势。 梳的紋絲不亂的頭發(fā)上镇防,一...
    開封第一講書人閱讀 49,749評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音潮饱,去河邊找鬼来氧。 笑死,一個(gè)胖子當(dāng)著我的面吹牛香拉,可吹牛的內(nèi)容都是我干的啦扬。 我是一名探鬼主播,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼凫碌,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼扑毡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起盛险,我...
    開封第一講書人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瞄摊,失蹤者是張志新(化名)和其女友劉穎勋又,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體换帜,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡楔壤,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了惯驼。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蹲嚣。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖跳座,靈堂內(nèi)的尸體忽然破棺而出端铛,到底是詐尸還是另有隱情,我是刑警寧澤疲眷,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布,位于F島的核電站您朽,受9級(jí)特大地震影響狂丝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜哗总,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一几颜、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧讯屈,春花似錦蛋哭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至叛本,卻和暖如春沪蓬,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背来候。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來泰國(guó)打工跷叉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人营搅。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓云挟,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親转质。 傳聞我的和親對(duì)象是個(gè)殘疾皇子园欣,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348

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