首页 > 解决方案 > grep 从超慢连续流式日志中找到,一旦找到没有缓冲区的字符串就退出

问题描述

更新:

随着@Tanktalus 的回答,我意识到这是最左边的kubectl命令被缓冲了。

# will hang forever, because RHS pipe is broken, and LHS pipe need to send 
# the output to the pipe to realize the broken pipe, but as the buffer is 
# never filled, it's never broken
kubectl logs -f pod -n NAMESPACE | grep -q "Indicator"  

# put LHS to the background, because I don't care if it hang, I just need the log.
(kubectl logs -f pod -n NAMESPACE &) | grep -q "Indicator"  

但我有一个新问题,以下现在永远挂起:
(kubectl logs -f pod -n NAMESPACE &)| tee log >(grep -q "Indicator")


原始问题:
首先,这不会与其他类似问题重复,我已全部阅读。细微的区别是,我的流式日志在我尝试 grep 的字符串指示符之后立即处于非活动状态。

我有来自 kubernetes pod 的连续流式日志输出。指标字符串“Indicator”将出现在日志生成器应用程序的末尾,并且日志生成器进入sleep infinity. 所以日志仍然会被流式传输,但不会提供新的输出。

我正在尝试使用管道|重定向我的 kubernetes 的流式日志,然后 grep 日志的每一行,直到找到“指示器”,然后我想(立即)退出。我尝试过的命令如下:

# none of them worked, they all show the Indicator line, and then hangs forever.
kubectl logs -f pod -n NAMESPACE | tee test.log >(grep -q "Indicator")  
stdbuf -o 0 kubectl logs -f pod -n NAMESPACE | tee test.log >(grep -m1 "Indicator")
stdbuf -o 0 kubectl logs -f pod -n NAMESPACE | tee test.log >(grep -q --line-buffered "Indicator")
stdbuf -o 0 kubectl logs -f pod -n NAMESPACE | grep -q --line-buffered "Indicator"

但是因为在“Indicator”之后,只会多出一行日志“+ Sleep infinity”。我猜管道最左端的输出缓冲区没有满,因此它没有传递给 grep?

有没有办法解决这个问题?

标签: bashunixkubernetesbufferstdout

解决方案


我怀疑这是因为kubectl没有退出shell没有继续。如果您查看ps输出,您会注意到它grep -m1 ...确实退出了,并且不再存在,但管道的其余部分仍然存在。

所以我怀疑你需要颠倒这个。例如,在 perl 中,我会open打开一个到 kubectl 的管道,读取输出,直到找到我想要的,杀死孩子,然后退出。在 C 中,与popen. 我不确定 bash 是否提供了相当程度的控制。

例如:

 perl -E 'my $pid = open my $fh, "-|", qw(perl -E), q($|++; say for 1..10; say "BOOM"; say "Sleep Infinity"; sleep 50) or die "Cannot run: $!"; while(<$fh>) { if (/BOOM/) { say; kill "INT", $pid; exit 0 } }'

你必须用你自己的命令替换open后面的东西,用你自己的正则表达式替换,否则它应该可以工作。"-|"if (/BOOM/)


推荐阅读