-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpipe.go
83 lines (69 loc) · 1.63 KB
/
pipe.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"syscall"
)
type Pipe struct {
Path string
Type string
Perms string
Output struct {
Template string
}
}
// Create and handle log data from pipe
func handlePipe(pipe Pipe) {
pipeExists := false
LoggerStdout.Verbose(fmt.Sprintf(" -> starting named pipe (%s)", pipe.Path))
// get pipe permissions
if pipe.Perms == "" {
pipe.Perms = "0600"
}
pipePerms, _ := strconv.ParseUint(pipe.Perms, 8, 32)
// check for existing file
fileInfo, err := os.Stat(pipe.Path)
if err == nil {
if (fileInfo.Mode() & os.ModeNamedPipe) > 0 {
pipeExists = true
} else {
fmt.Printf("%d != %d\n", os.ModeNamedPipe, fileInfo.Mode())
panic(fmt.Sprintf("Pipe %s exists, but it's not a named pipe (FIFO)", pipe.Path))
}
}
// Try to create pipe if needed
if !pipeExists {
err := syscall.Mkfifo(pipe.Path, uint32(pipePerms))
if err != nil {
panic(fmt.Sprintf("Creation of named pipe %s failed: %v", pipe.Path, err.Error()))
}
}
// Open pipe for reading
fd, err := os.Open(pipe.Path)
if err != nil {
panic(fmt.Sprintf("Failed opening named pipe %s: %v", pipe.Path, err.Error()))
}
defer fd.Close()
reader := bufio.NewReader(fd)
// loop messages
for {
message, err := reader.ReadString(0xa)
if err != nil && err != io.EOF {
panic(fmt.Sprintf("Reading from named pipe %s failed: %v", pipe.Path, err.Error()))
}
if message != "" {
if pipe.Output.Template != "" {
message = fmt.Sprintf(pipe.Output.Template, message)
}
switch pipe.Type {
case "stdout":
LoggerStdout.Print(message)
case "stderr":
LoggerStderr.Print(message)
}
}
}
}