logtailer.go
1 package system 2 3 import ( 4 "bufio" 5 "context" 6 "io" 7 "log" 8 "os" 9 "path/filepath" 10 "time" 11 12 dogeboxd "github.com/dogeorg/dogeboxd/pkg" 13 ) 14 15 func NewLogTailer(config dogeboxd.ServerConfig) LogTailer { 16 return LogTailer{ 17 config: config, 18 } 19 } 20 21 type LogTailer struct { 22 config dogeboxd.ServerConfig 23 } 24 25 func (t LogTailer) GetChan(pupId string) (context.CancelFunc, chan string, error) { 26 ctx, cancel := context.WithCancel(context.Background()) 27 28 out := make(chan string, 10) 29 30 go func() { 31 file, err := os.Open(filepath.Join(t.config.ContainerLogDir, "pup-"+pupId)) 32 if err != nil { 33 close(out) 34 log.Printf("Error opening log file: %+v", err) 35 return 36 } 37 defer file.Close() 38 39 log.Printf("Opened log file: %s", file.Name()) 40 41 // Seek to the end of the file 42 _, err = file.Seek(0, io.SeekEnd) 43 if err != nil { 44 close(out) 45 return 46 } 47 48 reader := bufio.NewReader(file) 49 50 for { 51 select { 52 case <-ctx.Done(): 53 close(out) 54 return 55 default: 56 line, err := reader.ReadString('\n') 57 if err != nil { 58 if err == io.EOF { 59 time.Sleep(100 * time.Millisecond) 60 continue 61 } 62 close(out) 63 return 64 } 65 out <- line 66 } 67 } 68 69 }() 70 return cancel, out, nil 71 }