解析ftrace-block

例子:

             fio-30749 [036] 5651360.257707: block_rq_issue: 8,0 WS 4096 () 1367650688 + 8 [fio]
             <idle>-0 [036] 5651360.257768: block_rq_complete: 8,0 WS () 1367650688 + 8 [0]
import os
import sys
import re
from openpyxl import Workbook

def parse_ftrace_file(file_path):
    #issue_pattern = re.compile(r'(\w+-\d+) \[(\d+)\] (\d+\.\d+): block_rq_issue: (\d+),(\d+) (\w+) (\d+) \(\) (\d+) \+ (\d+)')
    issue_pattern = re.compile(r'(\d+)\.(\d+): block_rq_issue: (\d+),(\d+) (\w+) (\d+) \(\) (\d+) \+ (\d+)')

    complete_pattern = re.compile(r'(\d+)\.(\d+): block_rq_complete: (\d+),(\d+) (\w+) \(\) (\d+) \+ (\d+)')

    with open(file_path, 'r') as f:
        lines = f.readlines()

    request_details = []
    request_counts = {}
    for line in lines:
        print(line)
        issue_match = issue_pattern.search(line)
        if issue_match:
            issue_time = float(issue_match.group(1)) + float(issue_match.group(2)) / 1e6
            operation = issue_match.group(5)
            lba = int(issue_match.group(7))
            size = int(issue_match.group(8))  # 獲取請求的大小
            request_details.append((operation, lba, size, issue_time, None, None))
            request_counts[operation] = request_counts.get(operation, 0) + 1
            continue

        complete_match = complete_pattern.search(line)
        if complete_match:
            complete_time = float(complete_match.group(1)) + float(complete_match.group(2)) / 1e6
            complete_request_id = (complete_match.group(5), int(complete_match.group(6)), int(complete_match.group(7)))
            print("complete_request_id:",complete_request_id)

            for i, details in enumerate(request_details):
                if details[0:3] == complete_request_id:
                    latency = complete_time - details[3]
                    request_details[i] = (details[0], details[1], details[2], details[3], complete_time, latency)
                    break

    return request_details, request_counts

def calculate_percentages(request_counts):
    total_count = sum(request_counts.values())
    percentages = {operation: count / total_count * 100 for operation, count in request_counts.items()}
    return percentages

def save_to_excel(request_details, request_counts, output_file):
    wb = Workbook()
    ws = wb.active

    ws['A1'] = 'Operation'
    ws['B1'] = 'Count'
    ws['C1'] = 'Percentage'

    percentages = calculate_percentages(request_counts)
    for i, (operation, count) in enumerate(request_counts.items(), start=2):
        ws[f'A{i}'] = operation
        ws[f'B{i}'] = count

    for i, (operation, percentage) in enumerate(percentages.items(), start=2):
        ws[f'C{i}'] = percentage

    ws['A{}'.format(len(request_counts) + 2)] = 'Operation'
    ws['B{}'.format(len(request_counts) + 2)] = 'LBA'
    ws['C{}'.format(len(request_counts) + 2)] = 'Size'
    ws['D{}'.format(len(request_counts) + 2)] = 'Issue Time'
    ws['E{}'.format(len(request_counts) + 2)] = 'Complete Time'
    ws['F{}'.format(len(request_counts) + 2)] = 'Latency'

    for i, details in enumerate(request_details, start=len(request_counts) + 3):
        ws[f'A{i}'] = details[0]
        ws[f'B{i}'] = details[1]
        ws[f'C{i}'] = details[2]
        ws[f'D{i}'] = details[3]
        ws[f'E{i}'] = details[4]
        ws[f'F{i}'] = details[5]

    wb.save(output_file)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py <path_to_ftrace_file<output_excel_file>")
        sys.exit(1)

    ftrace_file_path = sys.argv[1]
    output_excel_file = sys.argv[2]

    if not os.path.exists(ftrace_file_path):
        print(f"Error: File '{ftrace_file_path}' does not exist.")
        sys.exit(1)

    request_details, request_counts = parse_ftrace_file(ftrace_file_path)
    print(f"Request details: {request_details}")
    print(f"Request counts: {request_counts}")

    save_to_excel(request_details, request_counts, output_excel_file)
    print(f"Results saved to '{output_excel_file}'")

import re
import pandas as pd

讀取ftrace文件內(nèi)容
with open("path/to/your/ftrace_file.txt", "r") as f:
ftrace_output = f.read()

定義一個正則表達(dá)式模式,用于匹配block_rq_issue和block_rq_complete事件
pattern = r"(\d+.\d+):\s+(block_rq_issue|block_rq_complete):\s+(\d+),\s*(\d+)\s+([A-Z]+)\s+(\d+)\s+()\s+(\d+)\s++\s+(\d+)\s+[([a-zA-Z0-9_-]+)]"

使用正則表達(dá)式匹配ftrace輸出
matches = re.finditer(pattern, ftrace_output)

初始化變量
request_data = {}
data = []

遍歷匹配結(jié)果并提取信息
for match in matches:
timestamp = match.group(1)
event_type = match.group(2)
dev_major = match.group(3)
dev_minor = match.group(4)
rwbs = match.group(5)
sector = match.group(6)
nr_sector = match.group(7)
comm = match.group(8)

if event_type == "block_rq_issue":
request_id = (dev_major, dev_minor, sector, nr_sector, comm)
request_data[request_id] = {
"Timestamp Issue": timestamp,
"Dev Major": dev_major,
"Dev Minor": dev_minor,
"RWBS": rwbs,
"Sector": sector,
"Nr Sector": nr_sector,
"Comm": comm
}
elif event_type == "block_rq_complete":
request_id = (dev_major, dev_minor, sector, nr_sector, comm)
if request_id in request_data:
request_datarequest_id = timestamp
data.append(request_data[request_id])
del request_data[request_id]

將字典列表轉(zhuǎn)換為DataFrame
df = pd.DataFrame(data)

計算延遲并將其添加到DataFrame
df["Latency"] = df.apply(lambda row: float(row["Timestamp Complete"]) - float(row["Timestamp Issue"]), axis=1)

將DataFrame寫入Excel文件
df.to_excel("output.xlsx", index=False)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末矢棚,一起剝皮案震驚了整個濱河市毕莱,隨后出現(xiàn)的幾起案子嘹狞,更是在濱河造成了極大的恐慌,老刑警劉巖乎芳,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡取刃,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門出刷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來璧疗,“玉大人,你說我怎么就攤上這事馁龟”老溃” “怎么了?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵坷檩,是天一觀的道長却音。 經(jīng)常有香客問我,道長矢炼,這世上最難降的妖魔是什么系瓢? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮句灌,結(jié)果婚禮上夷陋,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好骗绕,可當(dāng)我...
    茶點故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布藐窄。 她就那樣靜靜地躺著,像睡著了一般酬土。 火紅的嫁衣襯著肌膚如雪枷邪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天诺凡,我揣著相機(jī)與錄音东揣,去河邊找鬼。 笑死腹泌,一個胖子當(dāng)著我的面吹牛嘶卧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播凉袱,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼芥吟,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了专甩?” 一聲冷哼從身側(cè)響起钟鸵,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎涤躲,沒想到半個月后棺耍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡种樱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年蒙袍,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嫩挤。...
    茶點故事閱讀 38,039評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡害幅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出岂昭,到底是詐尸還是另有隱情以现,我是刑警寧澤,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布约啊,位于F島的核電站邑遏,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏棍苹。R本人自食惡果不足惜无宿,卻給世界環(huán)境...
    茶點故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望枢里。 院中可真熱鬧孽鸡,春花似錦蹂午、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至巷疼,卻和暖如春晚胡,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背嚼沿。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工估盘, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人骡尽。 一個月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓遣妥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親攀细。 傳聞我的和親對象是個殘疾皇子箫踩,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,786評論 2 345