file_logger.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. package main
  2. import (
  3. "compress/gzip"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/nsqio/go-nsq"
  13. "github.com/nsqio/nsq/internal/lg"
  14. )
  15. type FileLogger struct {
  16. logf lg.AppLogFunc
  17. opts *Options
  18. topic string
  19. consumer *nsq.Consumer
  20. out *os.File
  21. writer io.Writer
  22. gzipWriter *gzip.Writer
  23. logChan chan *nsq.Message
  24. filenameFormat string
  25. termChan chan bool
  26. hupChan chan bool
  27. // for rotation
  28. filename string
  29. openTime time.Time
  30. filesize int64
  31. rev uint
  32. }
  33. func NewFileLogger(logf lg.AppLogFunc, opts *Options, topic string, cfg *nsq.Config) (*FileLogger, error) {
  34. computedFilenameFormat, err := computeFilenameFormat(opts, topic)
  35. if err != nil {
  36. return nil, err
  37. }
  38. consumer, err := nsq.NewConsumer(topic, opts.Channel, cfg)
  39. if err != nil {
  40. return nil, err
  41. }
  42. f := &FileLogger{
  43. logf: logf,
  44. opts: opts,
  45. topic: topic,
  46. consumer: consumer,
  47. logChan: make(chan *nsq.Message, 1),
  48. filenameFormat: computedFilenameFormat,
  49. termChan: make(chan bool),
  50. hupChan: make(chan bool),
  51. }
  52. consumer.AddHandler(f)
  53. err = consumer.ConnectToNSQDs(opts.NSQDTCPAddrs)
  54. if err != nil {
  55. return nil, err
  56. }
  57. err = consumer.ConnectToNSQLookupds(opts.NSQLookupdHTTPAddrs)
  58. if err != nil {
  59. return nil, err
  60. }
  61. return f, nil
  62. }
  63. func (f *FileLogger) HandleMessage(m *nsq.Message) error {
  64. m.DisableAutoResponse()
  65. f.logChan <- m
  66. return nil
  67. }
  68. func (f *FileLogger) router() {
  69. pos := 0
  70. output := make([]*nsq.Message, f.opts.MaxInFlight)
  71. sync := false
  72. ticker := time.NewTicker(f.opts.SyncInterval)
  73. closeFile := false
  74. exit := false
  75. for {
  76. select {
  77. case <-f.consumer.StopChan:
  78. sync = true
  79. closeFile = true
  80. exit = true
  81. case <-f.termChan:
  82. ticker.Stop()
  83. f.consumer.Stop()
  84. sync = true
  85. case <-f.hupChan:
  86. sync = true
  87. closeFile = true
  88. case <-ticker.C:
  89. if f.needsRotation() {
  90. if f.opts.SkipEmptyFiles {
  91. closeFile = true
  92. } else {
  93. f.updateFile()
  94. }
  95. }
  96. sync = true
  97. case m := <-f.logChan:
  98. if f.needsRotation() {
  99. f.updateFile()
  100. sync = true
  101. }
  102. _, err := f.Write(m.Body)
  103. if err != nil {
  104. f.logf(lg.FATAL, "[%s/%s] writing message to disk: %s", f.topic, f.opts.Channel, err)
  105. os.Exit(1)
  106. }
  107. _, err = f.Write([]byte("\n"))
  108. if err != nil {
  109. f.logf(lg.FATAL, "[%s/%s] writing newline to disk: %s", f.topic, f.opts.Channel, err)
  110. os.Exit(1)
  111. }
  112. output[pos] = m
  113. pos++
  114. if pos == cap(output) {
  115. sync = true
  116. }
  117. }
  118. if sync || f.consumer.IsStarved() {
  119. if pos > 0 {
  120. f.logf(lg.INFO, "[%s/%s] syncing %d records to disk", f.topic, f.opts.Channel, pos)
  121. err := f.Sync()
  122. if err != nil {
  123. f.logf(lg.FATAL, "[%s/%s] failed syncing messages: %s", f.topic, f.opts.Channel, err)
  124. os.Exit(1)
  125. }
  126. for pos > 0 {
  127. pos--
  128. m := output[pos]
  129. m.Finish()
  130. output[pos] = nil
  131. }
  132. }
  133. sync = false
  134. }
  135. if closeFile {
  136. f.Close()
  137. closeFile = false
  138. }
  139. if exit {
  140. break
  141. }
  142. }
  143. }
  144. func (f *FileLogger) Close() {
  145. if f.out == nil {
  146. return
  147. }
  148. if f.gzipWriter != nil {
  149. err := f.gzipWriter.Close()
  150. if err != nil {
  151. f.logf(lg.FATAL, "[%s/%s] failed to close GZIP writer: %s", f.topic, f.opts.Channel, err)
  152. os.Exit(1)
  153. }
  154. }
  155. err := f.out.Sync()
  156. if err != nil {
  157. f.logf(lg.FATAL, "[%s/%s] failed to fsync output file: %s", f.topic, f.opts.Channel, err)
  158. os.Exit(1)
  159. }
  160. err = f.out.Close()
  161. if err != nil {
  162. f.logf(lg.FATAL, "[%s/%s] failed to close output file: %s", f.topic, f.opts.Channel, err)
  163. os.Exit(1)
  164. }
  165. // Move file from work dir to output dir if necessary, taking care not
  166. // to overwrite existing files
  167. if f.opts.WorkDir != f.opts.OutputDir {
  168. src := f.out.Name()
  169. dst := filepath.Join(f.opts.OutputDir, strings.TrimPrefix(src, f.opts.WorkDir))
  170. // Optimistic rename
  171. f.logf(lg.INFO, "[%s/%s] moving finished file %s to %s", f.topic, f.opts.Channel, src, dst)
  172. err := exclusiveRename(src, dst)
  173. if err == nil {
  174. return
  175. } else if !os.IsExist(err) {
  176. f.logf(lg.FATAL, "[%s/%s] unable to move file from %s to %s: %s", f.topic, f.opts.Channel, src, dst, err)
  177. os.Exit(1)
  178. }
  179. // Optimistic rename failed, so we need to generate a new
  180. // destination file name by bumping the revision number.
  181. _, filenameTmpl := filepath.Split(f.filename)
  182. dstDir, _ := filepath.Split(dst)
  183. dstTmpl := filepath.Join(dstDir, filenameTmpl)
  184. for i := f.rev + 1; ; i++ {
  185. f.logf(lg.WARN, "[%s/%s] destination file already exists: %s", f.topic, f.opts.Channel, dst)
  186. dst := strings.Replace(dstTmpl, "<REV>", fmt.Sprintf("-%06d", i), -1)
  187. err := exclusiveRename(src, dst)
  188. if err != nil {
  189. if os.IsExist(err) {
  190. continue // next rev
  191. }
  192. f.logf(lg.FATAL, "[%s/%s] unable to rename file from %s to %s: %s", f.topic, f.opts.Channel, src, dst, err)
  193. os.Exit(1)
  194. }
  195. f.logf(lg.INFO, "[%s/%s] renamed finished file %s to %s to avoid overwrite", f.topic, f.opts.Channel, src, dst)
  196. break
  197. }
  198. }
  199. f.out = nil
  200. }
  201. func (f *FileLogger) Write(p []byte) (int, error) {
  202. n, err := f.writer.Write(p)
  203. f.filesize += int64(n)
  204. return n, err
  205. }
  206. func (f *FileLogger) Sync() error {
  207. var err error
  208. if f.gzipWriter != nil {
  209. // finish current gzip stream and start a new one (concatenated)
  210. // gzip stream trailer has checksum, and can indicate which messages were ACKed
  211. err = f.gzipWriter.Close()
  212. if err != nil {
  213. return err
  214. }
  215. err = f.out.Sync()
  216. f.gzipWriter, _ = gzip.NewWriterLevel(f.out, f.opts.GZIPLevel)
  217. f.writer = f.gzipWriter
  218. } else {
  219. err = f.out.Sync()
  220. }
  221. return err
  222. }
  223. func (f *FileLogger) currentFilename() string {
  224. t := time.Now()
  225. datetime := strftime(f.opts.DatetimeFormat, t)
  226. return strings.Replace(f.filenameFormat, "<DATETIME>", datetime, -1)
  227. }
  228. func (f *FileLogger) needsRotation() bool {
  229. if f.out == nil {
  230. return true
  231. }
  232. filename := f.currentFilename()
  233. if filename != f.filename {
  234. f.logf(lg.INFO, "[%s/%s] new filename %s, rotating...", f.topic, f.opts.Channel, filename)
  235. return true // rotate by filename
  236. }
  237. if f.opts.RotateInterval > 0 {
  238. if s := time.Since(f.openTime); s > f.opts.RotateInterval {
  239. f.logf(lg.INFO, "[%s/%s] %s since last open, rotating...", f.topic, f.opts.Channel, s)
  240. return true // rotate by interval
  241. }
  242. }
  243. if f.opts.RotateSize > 0 && f.filesize > f.opts.RotateSize {
  244. f.logf(lg.INFO, "[%s/%s] %s currently %d bytes (> %d), rotating...",
  245. f.topic, f.opts.Channel, f.out.Name(), f.filesize, f.opts.RotateSize)
  246. return true // rotate by size
  247. }
  248. return false
  249. }
  250. func (f *FileLogger) updateFile() {
  251. f.Close() // uses current f.filename and f.rev to resolve rename dst conflict
  252. filename := f.currentFilename()
  253. if filename != f.filename {
  254. f.rev = 0 // reset revision to 0 if it is a new filename
  255. } else {
  256. f.rev++
  257. }
  258. f.filename = filename
  259. f.openTime = time.Now()
  260. fullPath := path.Join(f.opts.WorkDir, filename)
  261. err := makeDirFromPath(f.logf, fullPath)
  262. if err != nil {
  263. f.logf(lg.FATAL, "[%s/%s] unable to create dir: %s", f.topic, f.opts.Channel, err)
  264. os.Exit(1)
  265. }
  266. var fi os.FileInfo
  267. for ; ; f.rev++ {
  268. absFilename := strings.Replace(fullPath, "<REV>", fmt.Sprintf("-%06d", f.rev), -1)
  269. // If we're using a working directory for in-progress files,
  270. // proactively check for duplicate file names in the output dir to
  271. // prevent conflicts on rename in the normal case
  272. if f.opts.WorkDir != f.opts.OutputDir {
  273. outputFileName := filepath.Join(f.opts.OutputDir, strings.TrimPrefix(absFilename, f.opts.WorkDir))
  274. err := makeDirFromPath(f.logf, outputFileName)
  275. if err != nil {
  276. f.logf(lg.FATAL, "[%s/%s] unable to create dir: %s", f.topic, f.opts.Channel, err)
  277. os.Exit(1)
  278. }
  279. _, err = os.Stat(outputFileName)
  280. if err == nil {
  281. f.logf(lg.WARN, "[%s/%s] output file already exists: %s", f.topic, f.opts.Channel, outputFileName)
  282. continue // next rev
  283. } else if !os.IsNotExist(err) {
  284. f.logf(lg.FATAL, "[%s/%s] unable to stat output file %s: %s", f.topic, f.opts.Channel, outputFileName, err)
  285. os.Exit(1)
  286. }
  287. }
  288. openFlag := os.O_WRONLY | os.O_CREATE
  289. if f.opts.GZIP || f.opts.RotateInterval > 0 {
  290. openFlag |= os.O_EXCL
  291. } else {
  292. openFlag |= os.O_APPEND
  293. }
  294. f.out, err = os.OpenFile(absFilename, openFlag, 0666)
  295. if err != nil {
  296. if os.IsExist(err) {
  297. f.logf(lg.WARN, "[%s/%s] working file already exists: %s", f.topic, f.opts.Channel, absFilename)
  298. continue // next rev
  299. }
  300. f.logf(lg.FATAL, "[%s/%s] unable to open %s: %s", f.topic, f.opts.Channel, absFilename, err)
  301. os.Exit(1)
  302. }
  303. f.logf(lg.INFO, "[%s/%s] opening %s", f.topic, f.opts.Channel, absFilename)
  304. fi, err = f.out.Stat()
  305. if err != nil {
  306. f.logf(lg.FATAL, "[%s/%s] unable to stat file %s: %s", f.topic, f.opts.Channel, f.out.Name(), err)
  307. }
  308. f.filesize = fi.Size()
  309. if f.opts.RotateSize > 0 && f.filesize > f.opts.RotateSize {
  310. f.logf(lg.INFO, "[%s/%s] %s currently %d bytes (> %d), rotating...",
  311. f.topic, f.opts.Channel, f.out.Name(), f.filesize, f.opts.RotateSize)
  312. continue // next rev
  313. }
  314. break // good file
  315. }
  316. if f.opts.GZIP {
  317. f.gzipWriter, _ = gzip.NewWriterLevel(f.out, f.opts.GZIPLevel)
  318. f.writer = f.gzipWriter
  319. } else {
  320. f.writer = f.out
  321. }
  322. }
  323. func makeDirFromPath(logf lg.AppLogFunc, path string) error {
  324. dir, _ := filepath.Split(path)
  325. if dir != "" {
  326. return os.MkdirAll(dir, 0770)
  327. }
  328. return nil
  329. }
  330. func exclusiveRename(src, dst string) error {
  331. err := os.Link(src, dst)
  332. if err != nil {
  333. return err
  334. }
  335. err = os.Remove(src)
  336. if err != nil {
  337. return err
  338. }
  339. return nil
  340. }
  341. func computeFilenameFormat(opts *Options, topic string) (string, error) {
  342. hostname, err := os.Hostname()
  343. if err != nil {
  344. return "", err
  345. }
  346. shortHostname := strings.Split(hostname, ".")[0]
  347. identifier := shortHostname
  348. if len(opts.HostIdentifier) != 0 {
  349. identifier = strings.Replace(opts.HostIdentifier, "<SHORT_HOST>", shortHostname, -1)
  350. identifier = strings.Replace(identifier, "<HOSTNAME>", hostname, -1)
  351. }
  352. cff := opts.FilenameFormat
  353. if opts.GZIP || opts.RotateSize > 0 || opts.RotateInterval > 0 || opts.WorkDir != opts.OutputDir {
  354. if strings.Index(cff, "<REV>") == -1 {
  355. return "", errors.New("missing <REV> in --filename-format when gzip, rotation, or work dir enabled")
  356. }
  357. } else {
  358. // remove <REV> as we don't need it
  359. cff = strings.Replace(cff, "<REV>", "", -1)
  360. }
  361. cff = strings.Replace(cff, "<TOPIC>", topic, -1)
  362. cff = strings.Replace(cff, "<HOST>", identifier, -1)
  363. cff = strings.Replace(cff, "<PID>", fmt.Sprintf("%d", os.Getpid()), -1)
  364. if opts.GZIP && !strings.HasSuffix(cff, ".gz") {
  365. cff = cff + ".gz"
  366. }
  367. return cff, nil
  368. }