背景
????互聯(lián)網應用提供服務,與用戶的操作產生交互,其行為產生的流量蘊含著許多可挖掘的價值,如性能分析、數(shù)據對比、行為分析等等。用戶流量就如同是現(xiàn)實世界的石油,由其中我們可以提煉的演化的用法非常多。
????本系列從軟件測試角度對測試人員的流量展開了應用設計,形成一個集流量錄制、流量回放、實時對比、流量用例編輯、用戶管理于一體的流量管理平臺,以提高測試工作效率,多方面的驗證軟件產品質量。
架構設計

實現(xiàn)效果
錄制任務創(chuàng)建,代理并監(jiān)控日志:

根據流量生成用例:

功能設計
流量錄制模塊主要包含的功能是:
- 任務信息列表
- 創(chuàng)建錄制任務
- 修改任務信息
- 執(zhí)行任務
- 實時查看流量日志
- 查看詳情信息
- 自定義生成流量用例并存儲
- 用例列表
- 用例詳情、編輯
????系統(tǒng)所有的列表和詳情數(shù)據,都離不開“增、刪、改、查”4個接口,系統(tǒng)的刪除目前都是邏輯刪除,通過置狀態(tài)值來控制顯示,以備后續(xù)的數(shù)據恢復和問題追蹤。
????其中的比較特殊的是 實時流量日志展示 功能,由于http接口的異步特性,很難保證日志數(shù)據的實時性和序列化。因此這里采用的websocket長連接為主,http接口為輔的雙重保證。也是得益mitmproxy項目的開源,我結合系統(tǒng)api,對其接口方法進行了二次自定義開發(fā),以適應本系統(tǒng)的數(shù)據需求,保持數(shù)據的準確性。
問題與解決方案
一、多任務不同的配置需求如何隔離?
解決方案:
在系統(tǒng)首次啟動前,需先執(zhí)行已經封裝的DockerFile,創(chuàng)建我們所需的基礎鏡像。系統(tǒng)通過docker service,根據任務配置的信息(host、代理等),創(chuàng)建docker容器。實際此時的docker鏡像,已經封裝了容器運行時所需的工具和基本的配置。每個容器創(chuàng)建掛載在各自獨立的端口下,以達到隔離。

二、如何獲取實時流量日志?
解決方案:
容器中的mitmproxy有多種啟動方式,各有不同的使用場景,其中mitmweb方式啟動的代理會有一個socket服務,通過對該接口的自定義開發(fā),讓其支持我們的跨域連接,并解析其報文信息,再通過前端渲染,即可達到實時日志的展現(xiàn)功能。
三、日志太多界面卡死怎么辦?
解決方案:
日志內容大小最好根據實際的使用場景做限制,同時前端采用虛擬列表,只渲染在可視區(qū)域及少量即將可視的DOM數(shù)據,根據數(shù)據長度計算容器的高度。可以自己寫組件去創(chuàng)建、銷毀Dom,本系統(tǒng)中使用的是結合react-virtualized和antd的virtualizedtableforantd4組件,這樣做到日志展示模塊的穩(wěn)定與性能優(yōu)化。
四、流量生成用例時,數(shù)據量很大怎么處理?
解決方案:
對于大量數(shù)據的錄制用例,在生成用例時,會根據勾選的流量ID,通過請求傳值給自定義的dump接口,生成可以用于回放的dump文件并保存。同時為了便于前臺展示,和后續(xù)的編輯,流量需要入庫到用例表。數(shù)據量超過限制大小時,后臺會舍棄部分冗余字段值,切片入庫,保證系統(tǒng)的穩(wěn)定性。
五、https流量如何處理?
解決方案:
https流量需要通過安裝mitmproxy的中間人證書,才能解析獲取。這里有個注意點,安卓移動設備6.0后,無法通過偽造證書去解析https。簡單的做法是,拿到服務器證書,用openssl生成pem證書。在系統(tǒng)中針對項目進行pem證書的配置,當該項目的代理啟動時,以此證書去解析指定域名的https請求,這樣就是解決所有來源請求的https數(shù)據了。
核心代碼實現(xiàn)
本功能模塊的核心部分是圍繞著容器管理腳本,進行數(shù)據準備、配置管理和容器管理。
前端虛擬表組件設計
import React, { useRef, useEffect, useMemo } from 'react';
import { Table } from 'antd';
import { useVT } from 'virtualizedtableforantd4';
const MyRow = React.forwardRef((props, ref) => {
const { children, ...rest } = props;
return <tr {...rest} ref={ref}>{children}</tr>;
});
function CustomRowsHooks(props) {
const columns = useRef(props.columns);
const [VT, setVT] = useVT(() => ({ scroll: { y: 600 }, debug: true }));
useMemo(() => setVT({ body: { row: MyRow } }), [setVT]);
return (
<Table
{...props}
components={VT}
scroll={{ y: 600 }}
dataSource={props.dataSource}
columns={columns.current}
/>
);
}
export default CustomRowsHooks;
服務端核心腳本
完整腳本代碼如下:
#-*-coding:utf-8-*-
__author__="orion-c"
def buildContainer(taskInfo, mountPort, wsMountPort, projectDir):
for i in range(5):
if len(os.listdir(projectDir)) > 0:
break
time.sleep(1)
if sys.platform.startswith('win'):
projectDir = "/taskFile/"+projectDir.split('taskFile\\')[1]
formatHost = {}
try:
if taskInfo:
if taskInfo['hosts']:
hosts = taskInfo['hosts'].split('\n')
for host in hosts:
host = ' '.join(host.split())
host = host.split(' ')
if len(host) == 2:
formatHost[host[1]] = host[0]
try:
container = docker_client.containers.get(str(mountPort))
if container.status == 'exited':
container.remove()
logger.info('移除容器成功:{}'.format(str(mountPort)))
except:
logger.info('can build')
docker_client.containers.run(
name=mountPort,
image='myproxy:0.0.13',
command='/bin/bash -c "sh /root/script/start_sync.sh"',
volumes={
projectDir: {'bind': '/root/script', 'mode': 'rw'}
},
ports={'8080': mountPort, '8081': wsMountPort},
extra_hosts=formatHost,
stderr=True,
detach=True
)
logger.info('任務 {} 創(chuàng)建容器 {} 成功,ws端口 {}'.format(taskInfo['id'], mountPort, wsMountPort))
return str(mountPort)
except Exception as e:
logger.error(e)
logger.error('創(chuàng)建容器:{} 失敗'.format(mountPort))
logger.error('請檢查你的docker服務')
def copyDumpFile(projectDir, content):
dumpFilePath = content['suiteInfo']['dumpFile']
dumpFilePath = '../../' + dumpFilePath if os.path.isfile('../../' + dumpFilePath) else dumpFilePath
replayDumpFile = projectDir + '/replayDumpFile'
shutil.copyfile(dumpFilePath, replayDumpFile)
def makeSyncReplayShell(projectDir, mountPort, content):
shellPath = '../../templte/start_sync.sh' if os.path.isfile('../../templte/start_sync.sh') else 'templte/start_sync.sh'
with open(shellPath, 'r', encoding='utf-8') as shellFile:
shellTemplte = shellFile.read()
cmd = "mitmdump -nC /root/script/replayDumpFile -s /root/script/getReplayResponse.py --ssl-insecure --set ssl_version_client=all --set ssl_version_server=all"
if content['proxySetting']:
cmd = cmd + " --set http2=false --set mode=upstream:{proxySetting}".format(proxySetting=content['proxySetting'])
if content['cerPem'] and content['domain']:
cmd = cmd + " --certs {domain}=/root/script/cer.pem".format(domain= content['domain'])
shellConfig = shellTemplte.format(cmd= cmd)
with open(projectDir + '/start_sync.sh', 'w', encoding='utf-8') as file:
file.write(shellConfig)
def makePem(content,projectDir):
if content['cerPem'] and content['domain']:
with open(projectDir + '/cer.pem', 'w', encoding='utf-8') as file:
file.write(content['cerPem'])
def makeMiddlareScript(content,projectDir):
responsePath = '../../templte/getReplayResponse.py' if os.path.isfile('../../templte/getReplayResponse.py') else 'templte/getReplayResponse.py'
with open(responsePath, 'r', encoding='utf-8') as middlareFile:
middlareTemplte = middlareFile.read()
middlareConfig = middlareTemplte.format(appHost= app.config['HOST'],taskId=content['id'])
with open(projectDir + '/getReplayResponse.py', 'w', encoding='utf-8') as file:
file.write(middlareConfig)
def makeConfig(projectDir, mountPort, content):
copyDumpFile(projectDir,content)
makeSyncReplayShell(projectDir, mountPort,content)
makePem(content, projectDir)
makeMiddlareScript(content, projectDir)
@manager.option('-i','--taskId',dest='taskId',default='')
def runScript(taskId):
now = datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
taskRootPath = encrypt_name(now)
content = getTaskInfo(taskId)
for i in range(2):
if i == 0:
proxyMountPort = freeport.get()
else:
wsMountPort = freeport.get()
projectDir = createProjectDir(taskRootPath)
makeConfig(projectDir, proxyMountPort, content)
setTaskStatus(taskId, 2, taskRootPath)
containName = buildContainer(content, proxyMountPort, wsMountPort, projectDir)
if containName:
setTaskStatus(taskId, 3, taskRootPath, containName, wsMountPort)
else:
setTaskStatus(taskId, 6)
????本系統(tǒng)采用前后端分離架構,由于系統(tǒng)架構復雜,本文僅就 流量錄制 模塊的設計與實現(xiàn),做分析講解,其它模塊將在后續(xù)文章中拆分講述。