file_writer.go 3.5 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. "path/filepath"
  21. "time"
  22. "github.com/lf-edge/ekuiper/internal/compressor"
  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. Dir := filepath.Dir(fn)
  45. if _, err = os.Stat(Dir); os.IsNotExist(err) {
  46. if err := os.Mkdir(Dir, 0o777); err != nil {
  47. return nil, fmt.Errorf("fail to create file %s: %v", fn, err)
  48. }
  49. }
  50. if _, err = os.Stat(fn); os.IsNotExist(err) {
  51. if _, err := os.Create(fn); err != nil {
  52. return nil, fmt.Errorf("fail to create file %s: %v", fn, err)
  53. }
  54. }
  55. f, err = os.OpenFile(fn, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModeAppend)
  56. if err != nil {
  57. return nil, fmt.Errorf("fail to open file sink for %s: %v", fn, err)
  58. }
  59. defer func() {
  60. if ge != nil {
  61. _ = f.Close()
  62. }
  63. }()
  64. fws.File = f
  65. switch ft {
  66. case JSON_TYPE:
  67. fws.Hook = jsonHooks
  68. case CSV_TYPE:
  69. fws.Hook = &csvWriterHooks{header: []byte(headers)}
  70. case LINES_TYPE:
  71. fws.Hook = linesHooks
  72. }
  73. fws.Compress = compressAlgorithm
  74. if compressAlgorithm == "" {
  75. fws.Writer = bufio.NewWriter(f)
  76. } else {
  77. fws.fileBuffer = bufio.NewWriter(f)
  78. fws.Writer, err = compressor.GetCompressWriter(compressAlgorithm, fws.fileBuffer)
  79. if err != nil {
  80. return nil, fmt.Errorf("fail to get compress writer for %s: %v", compressAlgorithm, err)
  81. }
  82. }
  83. _, err = fws.Writer.Write(fws.Hook.Header())
  84. if err != nil {
  85. return nil, err
  86. }
  87. return fws, nil
  88. }
  89. func (fw *fileWriter) Close(ctx api.StreamContext) error {
  90. var err error
  91. if fw.File != nil {
  92. ctx.GetLogger().Debugf("File sync before close")
  93. _, e := fw.Writer.Write(fw.Hook.Footer())
  94. if e != nil {
  95. ctx.GetLogger().Errorf("file sink fails to write footer with error %s.", e)
  96. }
  97. if fw.Compress != "" {
  98. e := fw.Writer.(io.Closer).Close()
  99. if e != nil {
  100. ctx.GetLogger().Errorf("file sink fails to close compress writer with error %s.", err)
  101. }
  102. err = fw.fileBuffer.Flush()
  103. if err != nil {
  104. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  105. }
  106. } else {
  107. err = fw.Writer.(*bufio.Writer).Flush()
  108. if err != nil {
  109. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  110. }
  111. }
  112. err = fw.File.Sync()
  113. if err != nil {
  114. ctx.GetLogger().Errorf("file sink fails to sync with error %s.", err)
  115. }
  116. ctx.GetLogger().Infof("Close file %s", fw.File.Name())
  117. return fw.File.Close()
  118. }
  119. return nil
  120. }