代码之家  ›  专栏  ›  技术社区  ›  Psyduck

从超慢速连续流日志中grep,一旦找到没有缓冲区的字符串就退出。

  •  0
  • Psyduck  · 技术社区  · 6 年前

    更新:

    有了@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流日志,然后将日志的每一行变灰,直到找到“指示器”,然后我想(立即)退出。我尝试过的命令如下:

    # 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"
    

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

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Tanktalus    6 年前

    我怀疑是因为 kubectl 还没有退出,因为外壳没有继续。如果你看 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 } }'
    

    你得把里面的东西换掉 打开 之后 "-|" 用你自己的命令, if (/BOOM/) 用你自己的regex,否则它会起作用。