file_writer.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. // Copyright 2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package file
  15. import (
  16. "bufio"
  17. "fmt"
  18. "io"
  19. "os"
  20. "time"
  21. "github.com/klauspost/compress/gzip"
  22. "github.com/klauspost/compress/zstd"
  23. "github.com/lf-edge/ekuiper/internal/conf"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. )
  26. type fileWriter struct {
  27. File *os.File
  28. Writer io.Writer
  29. Hook writerHooks
  30. Start time.Time
  31. Count int
  32. Compress string
  33. fileBuffer *bufio.Writer
  34. // Whether the file has written any data. It is only used to determine if new line is needed when writing data.
  35. Written bool
  36. }
  37. func createFileWriter(ctx api.StreamContext, fn string, ft FileType, headers string, compressAlgorithm string) (_ *fileWriter, ge error) {
  38. ctx.GetLogger().Infof("Create new file writer for %s", fn)
  39. fws := &fileWriter{Start: conf.GetNow()}
  40. var (
  41. f *os.File
  42. err error
  43. )
  44. if _, err = os.Stat(fn); os.IsNotExist(err) {
  45. if _, err := os.Create(fn); err != nil {
  46. return nil, fmt.Errorf("fail to create file %s: %v", fn, err)
  47. }
  48. }
  49. f, err = os.OpenFile(fn, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModeAppend)
  50. if err != nil {
  51. return nil, fmt.Errorf("fail to open file sink for %s: %v", fn, err)
  52. }
  53. defer func() {
  54. if ge != nil {
  55. _ = f.Close()
  56. }
  57. }()
  58. fws.File = f
  59. switch ft {
  60. case JSON_TYPE:
  61. fws.Hook = jsonHooks
  62. case CSV_TYPE:
  63. fws.Hook = &csvWriterHooks{header: []byte(headers)}
  64. case LINES_TYPE:
  65. fws.Hook = linesHooks
  66. }
  67. fws.Compress = compressAlgorithm
  68. switch compressAlgorithm {
  69. case GZIP:
  70. fws.fileBuffer = bufio.NewWriter(f)
  71. fws.Writer = gzip.NewWriter(fws.fileBuffer)
  72. case ZSTD:
  73. fws.fileBuffer = bufio.NewWriter(f)
  74. enc, err := zstd.NewWriter(fws.fileBuffer)
  75. if err != nil {
  76. return nil, err
  77. }
  78. fws.Writer = enc
  79. default:
  80. fws.Writer = bufio.NewWriter(f)
  81. }
  82. _, err = fws.Writer.Write(fws.Hook.Header())
  83. if err != nil {
  84. return nil, err
  85. }
  86. return fws, nil
  87. }
  88. func (fw *fileWriter) Close(ctx api.StreamContext) error {
  89. var err error
  90. if fw.File != nil {
  91. ctx.GetLogger().Debugf("File sync before close")
  92. _, e := fw.Writer.Write(fw.Hook.Footer())
  93. if e != nil {
  94. ctx.GetLogger().Errorf("file sink fails to write footer with error %s.", e)
  95. }
  96. if fw.Compress != "" {
  97. e := fw.Writer.(io.Closer).Close()
  98. if e != nil {
  99. ctx.GetLogger().Errorf("file sink fails to close compress writer with error %s.", err)
  100. }
  101. err = fw.fileBuffer.Flush()
  102. if err != nil {
  103. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  104. }
  105. } else {
  106. err = fw.Writer.(*bufio.Writer).Flush()
  107. if err != nil {
  108. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  109. }
  110. }
  111. err = fw.File.Sync()
  112. if err != nil {
  113. ctx.GetLogger().Errorf("file sink fails to sync with error %s.", err)
  114. }
  115. ctx.GetLogger().Infof("Close file %s", fw.File.Name())
  116. return fw.File.Close()
  117. }
  118. return nil
  119. }