登录
首页 >  Golang >  Go问答

在 docker 中向 os.Stdin 读取数据时遭到拦截

来源:stackoverflow

时间:2024-03-02 14:36:26 199浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《在 docker 中向 os.Stdin 读取数据时遭到拦截》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我正在尝试将程序的输出(日志)通过管道传输到 go 程序,该程序聚合/压缩输出并上传到 s3。运行该程序的命令是“/program1 | /logshipper”。 logshipper 是用 go 编写的,它只是从 os.stdin 读取并写入本地文件。本地文件将由另一个 goroutine 处理并定期上传到 s3。有一些现有的 docker 日志驱动程序,但我们在完全托管的提供商上运行容器,日志处理费用相当昂贵,因此我们希望绕过现有解决方案,只上传到 s3。

logshipper 的主要逻辑只是从 os.stdin 读取并写入某个文件。在本地计算机上运行时它可以正常工作,但是在 docker 中运行时,goroutine 会在 reader.readstring('\n') 处阻塞并且永远不会返回。

go func() {
    reader := bufio.NewReader(os.Stdin)
    mu.Lock()
    output = openOrCreateOutputFile(&uploadQueue, workPath)
    mu.Unlock()
    for {
    text, _ := reader.ReadString('\n')
    now := time.Now().Format("2006-01-02T15:04:05.000000000Z")
    mu.Lock()
    output.file.Write([]byte(fmt.Sprintf("%s %s", now, text)))
    mu.Unlock()
     }
}()

我在网上做了一些研究,但没有找到为什么它不起作用。我想的一种可能性是 docker 可能会将 stdout 重定向到某个地方,因此 pipe 的工作方式与在 linux 机器上运行的方式不同? (看起来它无法从程序1中读取任何内容)欢迎任何帮助或建议为什么它不起作用。谢谢。

编辑: 经过更多研究后,我意识到以这种方式处理日志是一种不好的做法。我应该更多地依赖docker的日志驱动程序来处理日志聚合和运输。不过,我仍然有兴趣找出为什么它没有从 pipe 源程序中读取任何内容。


解决方案


我不确定 docker 处理输出的方式,但我建议您使用 os.stdin.fd() 提取文件描述符,然后使用 golang.org/x/sys/unix 包,如下所示:

// Long way, for short one jump
// down straight to it.
//
// retrieve the file descriptor
// cast it to int, because Fd method
// returns uintptr
fd := int(os.Stdin.Fd())

// extract file descriptor flags
// it's safe to drop the error, since if it's there
// and it's not nil, you won't be able to read from
// Stdin anyway, unless it's a notice
// to try again, which mostly should not be 
// the case
flags, _ := unix.FcntlInt(fd, unix.F_GETFL, 0)

// check if the nonblocking reading in enabled
nb := flags & unix.O_NONBLOCK != 0

// if this is the case, just enable it with
// unix.SetNonblock which is also a
// -- SHORT WAY HERE --
err = unix.SetNonblock(fd, true)

long 和 short way 的区别在于,long way 肯定会告诉你问题是否出在非阻塞状态下。

如果情况并非如此。那么我个人就没有其他的想法了。

好了,本文到此结束,带大家了解了《在 docker 中向 os.Stdin 读取数据时遭到拦截》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>