使用shell实现高精度时间日志记录与时间跳变检测

ops/2024/10/18 2:14:11/

文章目录

    • 0. 概述
    • 1. 使用说明
    • 1.1. 参数说明
      • 1.2. 运行脚本
    • 2. 脚本详细解析
      • 2.1. 参数初始化
      • 2.2. 参数解析与验证
      • 2.3 主循环条件
      • 2.4 时间跳变检测与处理
      • 2.5. 日志轮转机制
      • 2.6. 睡眠时间计算

0. 概述

之前写过单线程版本的高精度时间日志记录小程序:C++编程:实现简单的高精度时间日志记录小程序(单线程)
然后写了多线程版本的高精度时间日志记录小程序:使用C++实现高精度时间日志记录与时间跳变检测[多线程版本]

本文将使用shell脚本实现类似的功能,该脚本主要实现以下功能:

  1. 定时记录时间戳:按照指定的时间间隔(默认为20毫秒)记录当前时间戳
  2. 时间跳变检测与处理:当检测到系统时间回退或跳跃时,记录跳变前后的时间戳,以便后续分析。
  3. 日志轮转:当日志文件达到指定大小(默认为50MB)时,自动轮转日志文件,并保留一定数量的历史日志文件。
  4. 可配置参数:支持通过命令行参数自定义时间间隔、日志文件名、运行时长等配置。

1. 使用说明

1.1. 参数说明

脚本提供了多种可配置参数,用户可以根据需求进行调整:

  • -i, --interval <milliseconds>:设置记录时间戳的时间间隔,默认为20毫秒。
  • -f, --file <filename>:设置输出日志文件的名称,默认为timestamps_sh.txt
  • -t, --time <seconds>:设置脚本的运行时长,默认为72000秒(20小时)。
  • --disable_selective_logging:禁用选择性日志记录功能。
  • -h, --help:显示帮助信息。

1.2. 运行脚本

使用默认参数运行脚本:

./time_jump_check.sh

使用自定义参数运行脚本,例如设置间隔为500毫秒,运行时长为3600秒(1小时):

./time_jump_check.sh -i 500 -t 3600

禁用选择性日志记录功能:

./time_jump_check.sh --disable_selective_logging

2. 脚本详细解析

以下是time_jump_check.sh 脚本的完整代码:

#!/bin/bash# Default parameters
INTERVAL_MS=20               # Default interval 20 milliseconds
FILENAME="timestamps_sh.txt" # Default log file name
RUN_TIME_SECONDS=72000       # Default run time 72000 seconds (20 hours)
MAX_FILE_SIZE=50*1024*1024   # 50MB in bytes
SELECTIVE_LOGGING=true      # Default to enable selective logging
PRE_JUMP_RECORD=10          # Number of timestamps to record before jump
POST_JUMP_RECORD=10         # Number of timestamps to record after jump
MAX_LOG_FILES=2             # Maximum number of log files to keep# Function to show usage information
usage() {echo "Usage: $0 [options]"echo "Options:"echo "  -i, --interval <milliseconds>        Set the time interval, default is 20 milliseconds"echo "  -f, --file <filename>                Set the output file name, default is timestamps.txt"echo "  -t, --time <seconds>                 Set the run time, default is 72000 seconds (20 hours)"echo "      --disable_selective_logging      Disable selective logging feature"echo "  -h, --help                          Show this help message"exit 1
}# Parse command line arguments
while [[ $# -gt 0 ]]; dokey="$1"case $key in-i|--interval)INTERVAL_MS="$2"shift # past argumentshift # past value;;-f|--file)FILENAME="$2"shiftshift;;-t|--time)RUN_TIME_SECONDS="$2"shiftshift;;--disable_selective_logging)SELECTIVE_LOGGING=falseshift;;-h|--help)usage;;*)echo "Unknown option: $1"usage;;esac
done# Validate parameters
if ! [[ "$INTERVAL_MS" =~ ^[0-9]+$ ]] || [ "$INTERVAL_MS" -le 0 ]; thenecho "Error: Interval must be a positive integer."usage
fiif ! [[ "$RUN_TIME_SECONDS" =~ ^[0-9]+$ ]] || [ "$RUN_TIME_SECONDS" -le 0 ]; thenecho "Error: Run time must be a non-negative integer."usage
fi# Output configuration
echo "Time Interval: $INTERVAL_MS milliseconds"
echo "Output File: $FILENAME"
echo "Run Time: $RUN_TIME_SECONDS seconds"
echo "Selective Logging: $SELECTIVE_LOGGING"# Initialize variables
last_timestamp_us=0
second_last_timestamp_us=0
total_timestamps=0
in_jump_mode=false
jump_remaining=0
time_jump_count=0declare -a pre_jump_timestamps=()# Create or clear the log file
if ! > "$FILENAME"; thenecho "Error: Unable to create or clear log file '$FILENAME'."exit 1
fi# Main loop start time
START_TIME=$(date +%s)
while [[ $(($(date +%s) - START_TIME)) -lt $RUN_TIME_SECONDS || $time_jump_count -lt $RUN_TIME_SECONDS ]]; do# Get the current time stringcurrent_time_str=$(date +"%Y-%m-%d %H:%M:%S.%6N")# Convert current time to microseconds (since epoch)current_timestamp_us=$(date +"%s%6N")time_jump=falseif [[ $last_timestamp_us -ne 0 && $second_last_timestamp_us -ne 0 && $SELECTIVE_LOGGING == true ]]; thenif [[ $current_timestamp_us -lt $last_timestamp_us ]]; then# Time regression detectedtime_jump=trueelse# Check if the interval is too small based on second last timestampexpected_interval_us=$(( INTERVAL_MS * 1000 ))actual_interval_us=$(( current_timestamp_us - second_last_timestamp_us ))threshold_us=$(( expected_interval_us * 15 / 10 ))  # 1.5x thresholdif [[ $actual_interval_us -lt $threshold_us ]]; thentime_jump=truefififi# Update timestampssecond_last_timestamp_us=$last_timestamp_uslast_timestamp_us=$current_timestamp_us# Add current time to pre_jump_timestamps arraypre_jump_timestamps+=("$current_time_str")# Keep array length at most PRE_JUMP_RECORDif [[ ${#pre_jump_timestamps[@]} -gt $PRE_JUMP_RECORD ]]; thenpre_jump_timestamps=("${pre_jump_timestamps[@]: -$PRE_JUMP_RECORD}")fiif [[ $SELECTIVE_LOGGING == true && $time_jump == true && $in_jump_mode == false ]]; then# Detected a time jump, enter jump modein_jump_mode=truejump_remaining=$POST_JUMP_RECORD# Log pre-jump timestampsecho -e "\n--- TIME JUMP DETECTED ---" >> "$FILENAME"for ts in "${pre_jump_timestamps[@]}"; doecho "$ts" >> "$FILENAME"done# Log current timestamp with [TIME_JUMP] markerecho "$current_time_str [TIME_JUMP]" >> "$FILENAME"elif [[ $in_jump_mode == true ]]; then# In jump mode, record post-jump timestampsecho "$current_time_str" >> "$FILENAME"jump_remaining=$((jump_remaining - 1))if [[ $jump_remaining -le 0 ]]; thenin_jump_mode=falsefielse# Normal mode: log every 500 timestampstotal_timestamps=$((total_timestamps + 1))if [[ $((total_timestamps % 500)) -eq 0 ]]; thenecho "$current_time_str" >> "$FILENAME"fifi# Check and perform log rotationcurrent_size=$(stat -c%s "$FILENAME" 2>/dev/null || echo 0)if [[ $current_size -ge $MAX_FILE_SIZE ]]; thennew_filename="${FILENAME}.$(date +"%Y%m%d%H%M%S")"if ! mv "$FILENAME" "$new_filename"; thenecho "Error: Unable to rotate log file to '$new_filename'."exit 1fiecho "Rotated log file to $new_filename"# Create a new log fileif ! > "$FILENAME"; thenecho "Error: Unable to create new log file '$FILENAME'."exit 1fi# Remove oldest log file if there are more than MAX_LOG_FILESlog_files=($(ls -t "${FILENAME}".* 2>/dev/null))if [[ ${#log_files[@]} -gt $MAX_LOG_FILES ]]; thenfor (( i=$MAX_LOG_FILES; i<${#log_files[@]}; i++ )); doif ! rm "${log_files[$i]}"; thenecho "Error: Unable to remove old log file '${log_files[$i]}'."fidonefifi# Replace awk with bash and printf to calculate sleep_timeinteger_part=$(( INTERVAL_MS / 1000 ))fractional_part=$(( INTERVAL_MS % 1000 ))# Ensure fractional_part is three digits with leading zeros if necessaryfractional_part_padded=$(printf "%03d" "$fractional_part")sleep_time="${integer_part}.${fractional_part_padded}"# Sleep for the specified intervalsleep "$sleep_time"
doneecho "Program has ended."exit 0

2.1. 参数初始化

脚本开始部分定义了一系列默认参数,包括时间间隔、日志文件名、运行时长、最大日志文件大小、选择性日志记录开关、记录跳跃前后的时间戳数量以及最大保留的日志文件数量。

INTERVAL_MS=20               # 默认间隔20毫秒
FILENAME="timestamps_sh.txt" # 默认日志文件名
RUN_TIME_SECONDS=72000       # 默认运行时长72000秒(20小时)
MAX_FILE_SIZE=$((50*1024*1024))   # 50MB
SELECTIVE_LOGGING=true      # 默认启用选择性日志记录
PRE_JUMP_RECORD=10          # 跳跃前记录的时间戳数量
POST_JUMP_RECORD=10         # 跳跃后记录的时间戳数量
MAX_LOG_FILES=2             # 最大保留日志文件数量

2.2. 参数解析与验证

通过命令行参数,用户可以自定义脚本的运行参数。脚本使用while循环和case语句解析传入的参数,并进行必要的验证,确保参数的有效性。

# 解析命令行参数
while [[ $# -gt 0 ]]; dokey="$1"case $key in-i|--interval)INTERVAL_MS="$2"shift # 过去参数shift # 过去值;;-f|--file)FILENAME="$2"shiftshift;;-t|--time)RUN_TIME_SECONDS="$2"shiftshift;;--disable_selective_logging)SELECTIVE_LOGGING=falseshift;;-h|--help)usage;;*)echo "Unknown option: $1"usage;;esac
done# 验证参数
if ! [[ "$INTERVAL_MS" =~ ^[0-9]+$ ]] || [ "$INTERVAL_MS" -le 0 ]; thenecho "Error: Interval must be a positive integer."usage
fiif ! [[ "$RUN_TIME_SECONDS" =~ ^[0-9]+$ ]] || [ "$RUN_TIME_SECONDS" -le 0 ]; thenecho "Error: Run time must be a non-negative integer."usage
fi

2.3 主循环条件

主循环的条件为:

while [[ $(($(date +%s) - START_TIME)) -lt $RUN_TIME_SECONDS || $time_jump_count -lt $RUN_TIME_SECONDS ]]; do

这意味着,脚本将在以下两个条件之一满足时继续运行:

  1. 已经运行的时间未超过设定的RUN_TIME_SECONDS
  2. 检测到的时间跳变次数未超过RUN_TIME_SECONDS

这种设计确保了即使系统时间发生大幅跳变,脚本仍能继续运行,直到达到预定的运行时长。

2.4 时间跳变检测与处理

脚本通过比较当前时间戳与之前的时间戳来检测时间跳变。当检测到时间回退或时间间隔异常小时,触发跳变处理机制。

if [[ $current_timestamp_us -lt $last_timestamp_us ]]; then# 时间回退time_jump=truetime_jump_count=$((time_jump_count + 1))
else# 检查时间间隔是否异常expected_interval_us=$(( INTERVAL_MS * 1000 ))actual_interval_us=$(( current_timestamp_us - second_last_timestamp_us ))threshold_us=$(( expected_interval_us * 15 / 10 ))  # 1.5倍阈值if [[ $actual_interval_us -lt $threshold_us ]]; thentime_jump=truetime_jump_count=$((time_jump_count + 1))fi
fi

当检测到时间跳变时,脚本将:

  1. 记录跳变前的时间戳
  2. 标记当前时间戳为跳变时间。
  3. 在后续的循环中,记录一定数量的跳变后时间戳,确保日志的连续性。

2.5. 日志轮转机制

为防止日志文件过大,脚本实现了日志轮转功能。当日志文件大小超过MAX_FILE_SIZE时,脚本会:

  1. 将当前日志文件重命名为带有时间戳的文件名。
  2. 创建一个新的空日志文件。
  3. 保留最新的MAX_LOG_FILES个日志文件,删除最旧的文件。
# 检查并执行日志轮转
current_size=$(stat -c%s "$FILENAME" 2>/dev/null || echo 0)
if [[ $current_size -ge $MAX_FILE_SIZE ]]; thennew_filename="${FILENAME}.$(date +"%Y%m%d%H%M%S")"if ! mv "$FILENAME" "$new_filename"; thenecho "Error: Unable to rotate log file to '$new_filename'."exit 1fiecho "Rotated log file to $new_filename"# 创建新的日志文件if ! > "$FILENAME"; thenecho "Error: Unable to create new log file '$FILENAME'."exit 1fi# 如果日志文件超过MAX_LOG_FILES个,删除最旧的文件log_files=($(ls -t "${FILENAME}".* 2>/dev/null))if [[ ${#log_files[@]} -gt $MAX_LOG_FILES ]]; thenfor (( i=$MAX_LOG_FILES; i<${#log_files[@]}; i++ )); doif ! rm "${log_files[$i]}"; thenecho "Error: Unable to remove old log file '${log_files[$i]}'."fidonefi
fi

2.6. 睡眠时间计算

为了实现精确的时间间隔,脚本将INTERVAL_MS分解为整数部分和小数部分,并使用printf确保小数部分为三位数,最后组合成sleep命令所需的格式。

# 计算睡眠时间
integer_part=$(( INTERVAL_MS / 1000 ))
fractional_part=$(( INTERVAL_MS % 1000 ))
# 确保fractional_part为三位数,前面补零
fractional_part_padded=$(printf "%03d" "$fractional_part")
sleep_time="${integer_part}.${fractional_part_padded}"# 按指定间隔休眠
sleep "$sleep_time"

http://www.ppmy.cn/ops/126356.html

相关文章

前端布局,y轴超出滚动、x轴超出展示方案

想要实现布局效果&#xff0c;红区高度固定可滑动可收起。红区引用绿区组件。 一般会想到如下方案&#xff0c;红区样式&#xff1a; width&#xff1a;200px; height: 100%; overflow-y: auto; overflow-x: visible; 但是效果并不好&#xff0c;绿区直接隐藏了 最终采用布局方…

数字后端零基础入门系列 | Innovus零基础LAB学习Day1

一 Floorplan 数字IC后端设计如何从零基础快速入门&#xff1f;(内附数字IC后端学习视频&#xff09; Lab5-1这个lab学习目标很明确——启动Innovus工具并完成设计的导入。 在进入lab之前&#xff0c;我们需要进入我们的FPR工作目录。 其中ic062为个人服务器账户。比如你端…

C++初阶学习第七弹——string的模拟实现

C初阶学习第六弹------标准库中的string类_c语言返回string-CSDN博客 通过上篇我们已经学习到了string类的基本使用&#xff0c;这里我们就试着模拟实现一些&#xff0c;我们主要实现一些常用到的函数。 目录 一、string类的构造 二、string类的拷贝构造 三、string类的析构函…

JDBC增删改查操作的基本步骤

JDBC&#xff08;Java Database Connectivity&#xff09;是一种用于执行数据库操作的Java API。以下是使用JDBC进行增删改查&#xff08;CRUD&#xff09;操作的基本步骤和代码示例。 步骤&#xff1a; 加载数据库驱动&#xff1a;确保JDBC驱动程序类被加载。建立数据库连接…

WPF入门_02依赖属性

1、依赖属性主要有以下三个优点 1)依赖属性加入了属性变化通知、限制、验证等功能。这样可以使我们更方便地实现应用,同时大大减少了代码量 2)节约内存:在WinForm中,每个UI控件的属性都赋予了初始值,这样每个相同的控件在内存中都会保存一份初始值。而WPF依赖属性很好地…

GitHub如何推送文件到仓库?

要将本地项目推送到 GitHub 上&#xff0c;可以按照以下步骤操作&#xff1a; 在 GitHub 上创建一个新的仓库&#xff1a; 登录你的 GitHub 账号。点击页面右上角的 “” 按钮&#xff0c;并选择 “New repository”。填写仓库名称&#xff0c;可以选择是否公开&#xff08;Pub…

可变参数函数、可变参数模板和折叠表达式

可变参数函数 可变参数是在C编程中&#xff0c;允许函数接受不定数量的参数。这种特性可以帮助我们处理多种情况&#xff0c;例如日志记录、数学计算等。 在C中&#xff0c;可变参数通常通过C风格的可变参数函数实现&#xff0c;需要包含<cstdarg>头文件。 对可变参数…

小说漫画系统 fileupload.php 任意文件上传漏洞复现

FOFA搜索语句 "/Public/home/mhjs/jquery.js" 漏洞复现 1.向靶场发送如下数据包 POST /Public/webuploader/0.1.5/server/fileupload.php HTTP/2 Host: xxx.xxx.xx.xx Cookie: PHPSESSID54bc7gac1mgk0l3nm8cv6sek07; uloginid677742617 Cache-Control: max-age0…