• websocket 和 ansible配合Tomcat实时日志给前端展示


    业务流程图如下

    效果图展示

    1.django安装websocket模块

    pip install dwebsocket
    

    2.shell脚本

    用来传递不同的行号输出不同的内容;
    第一个参数为0的时候,默认输出最后200行内容
    第一个参数为其余数字时候,和总行数比较,取差值内容

    #!/bin/bash
    LOGDIR=/export/Instances/*/*/logs/
    LineNum=$1
    CatalinaLogFilename=`ls -lrt $LOGDIR | grep catalina.out | tail -1 | awk '{print $NF}'`
    LocalhostLogFilename=`ls -lrt $LOGDIR | grep localhost | tail -1 | awk '{print $NF}'`
    
    CatalinaLogFullFilename="${LOGDIR}${CatalinaLogFilename}"
    LocalhostLogFullFilename="${LOGDIR}${LocalhostLogFilename}"
    
    #echo $CatalinaLogFullFilename
    #echo $LocalhostLogFullFilename
    getLogContent(){
    	wc -l ${CatalinaLogFullFilename} | awk '{print $1}'
    	echo '###########################Catalina.out#######################################'
        /usr/bin/tail -200 ${CatalinaLogFullFilename}
    }
    if [ -z $LineNum ];then
    	getLogContent
    elif [ $LineNum -eq 0 ];then
    	getLogContent
    else
    	totalNum=`wc -l ${CatalinaLogFullFilename} | awk '{print $1}'`
    	let catNum=totalNum-LineNum
    	if [ $catNum -ne 0 ];then
    		echo $totalNum
    		/usr/bin/tail -${catNum} ${CatalinaLogFullFilename}
    	fi
    fi
    

    3.django后台试图函数

    views.py对应了/index/websocket_demo/函数处理
    应用名字叫做app

    from dwebsocket import require_websocket
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
    
    '''websokcet测试函数接收用户发送过来的IP数'''
    require_websocket
    def websocket_demo(request):
        flag = True
        # num用作判断是不是第一次请求,取最后200行内容的判断
        num = 0
        line_num = 0
        while flag:
    	    # read方法是非阻塞的方法,所以每3秒收集一次,防止前端挂掉
            message = request.websocket.read()
            # 客户端发过来的是close的话关闭websocket连接
            if message == 'close':
                    flag = False
    	            # 关闭连接
                    request.websocket.close()
                    break
            #message = request.websocket.wait()
            # 如果客户端没发送数据,就是None,再判断是否num 为1,为1代表第一次读数据已读过
            elif not message:
                    if num != 1:
                            pass
                    else:
                            print '捕获更新日志开始'
                            from CeleryTasks import ansible_play
                            instance = ansible_play.Ansible_Playbook(3,[ip,])
                            print line_num
                            result = instance.script_shell('/export/App/DevOPS/Python_20160906/CeleryTasks/tomcatLog.sh %s'%line_num)
                            if result:
                                    line_num = result.split('
    ')[0].strip()
                                    request.websocket.send(str(result))
                            else:
                                    pass
                            print '捕获更新日志结束'
            else:
    		        # 第一次请求取最后200行内容,此时line_num为0
                    num = 1
                    ip = message
                    print '捕获初始日志开始'
                    #request.websocket.send('return')
                    from CeleryTasks import ansible_play
                    instance = ansible_play.Ansible_Playbook(3,[ip,])
                    print line_num
                    result = instance.script_shell('/export/App/DevOPS/Python_20160906/CeleryTasks/tomcatLog.sh %s'%line_num)
    #               print result.split('
    ')
                    line_num = result.split('
    ')[0].strip()
    #               #message = request.websocket.wait()
    #               #print message
                    request.websocket.send(str(result))
                    print '捕获初始日志结束'
    #               time.sleep(5)
    #               request.websocket.close()
    #               break
            time.sleep(3)
    

    4.前端页面

    $(function() {
        t=null;
        // connection全局,关闭弹窗作用,websocket关闭操作时候
        connection=null;
        // 连接成功后,置为true
        flag=false;
        // 关闭模态框调用的函数
        $('#myModal').on('hide.bs.modal',
        function() {
            //alert('嘿,我听说您喜欢模态框...');
            if(t == null){
            }else{
                    clearInterval(t); 
            }
            //clearInterval(t);
            $('.modal-footer').empty();
            if(connection == null){
            }else{
    		        // 关闭websocket连接
                    connection.send('close');
            }
            
        })
    });
    
    //pre标签外部的div标签,实现弹窗的滚轮一直在下面
    function Setdeep(){
        $('.modal-body').scrollTop($('.modal-body')[0].scrollHeight);
    }
    
    /*
            下面定义一些函数,用做websocket的连接相关
    */
    // 发送关闭websocket命令函数
    function wsClose () {
            connection.send('close');
            console.log("Closed");
    }
    // 收到callback函数回调,插入内容
    function wsMessage (event) {
                    $('.modal-body').find('pre').append('<code class="avrasm">' + event.data + '</code>');
                    Setdeep();
    }
    // 连接成功,调用函数回调,flag置为true
    function wsOpen (event,ip) {
            flag = true;
            console.log('Connected to: ' + event.currentTarget.URL);
            //connection.send('10.187.109.116');
    }
    // websocket异常报错console输出
    function wsError(event) {
            console.log("Error: " + event.data);
    }
    
    //Tomcat日志查看清理函数,弹窗
    function tomcatLog(ths){
            //if( connection == null ){}else{connection.send('close');}
            $('#myModal').find('.modal-dialog').removeClass('modal-sm');
            $('#myModal').find('.modal-dialog').addClass('modal-lg');
            var ip = $(ths).parents('tr').find("td:first").text();
            $('#myModal').find('.modal-body').removeClass('hide');
            $('#myModal').find('.modal-body').empty();
            $('#myModal').find('.modal-body').css("height","750px");
            $('.modal-footer').empty();
            $('#myModal').find('.modal-body').append('<img src="/static/image/loading.gif"></img>');
            $('#myModalLabel').text(ip + ' Tomcat日志');
            $('.modal-body').append('<pre>' + '<code class="avrasm">' + '</code>' + '</pre>');
            // 建立websocket连接,ws是标签协议,目前nginx上还没更改;
            connection = new WebSocket('ws://10.187.196.225:65535/index/websocket_demo/');
            connection.onopen = wsOpen;
            connection.onclose = wsClose;
            connection.onmessage = wsMessage;
            connection.onerror = wsError;
            // 每2秒判断一下是否成功连接上了
            setInterval(function(){
                    if(flag){
                            $('.modal-body').find('img').remove();
                            connection.send(ip);
                            // 连接置位符置位false,防止频繁发送数据给服务器,主要服务器推数据
                            flag = false;
                            $('.modal-footer').append('<button type="button" class="btn btn-danger" onclick="wsClose();buttonDisabled(this);">关闭实时刷新</button>')
                            $('.modal-footer').append('<button type="button" class="btn btn-default" onclick="dowlandTomcatLog(this);">下载日志文件</button>');
                    }
            },2000);
    }
    
    
    //获取pre标签的中内容给用户下载
    function dowlandTomcatLog(ths){
            var tomcatLogContent = $('.modal-body').find('pre').first().text();
            var blob = stringToBlob(tomcatLogContent);
            //var blob = stringToBlob('hello jd.com
    hello baidu.com');
            download('tomcatLog.txt', blob);
    }
    /* fileName: 默认下载文件名
    blob: 下载Blob对象
    */
    function download(fileName, blob){
        var aLink = document.createElement('a');
        var evt = document.createEvent("MouseEvents");
        evt.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(evt);
    }
     
    /* 文本转Blob对象 */
    function stringToBlob(text) {
        var arr_text = text.split("
    ");
        for (var i = 0;i<arr_text.length;i++){
                    arr_text[i] = arr_text[i] + '
    ';
        }
        var blob = new Blob([arr_text],{type : 'text/html'});
        return blob;
    }
    
  • 相关阅读:
    mysql性能调优
    java面试大全
    JVM调优总结
    大数据行业跳槽面试前你需要做什么
    什么是分布式锁?实现分布式锁的方式
    如何保障mysql和redis之间的数据一致性?
    数据倾斜的原因和解决方案
    hive优化
    c# 系统换行符
    12种增强CSS技能并加快开发速度的资源
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/6519409.html
Copyright © 2020-2023  润新知