file_writer.go 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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/lf-edge/ekuiper/internal/compressor"
  22. "github.com/lf-edge/ekuiper/internal/conf"
  23. "github.com/lf-edge/ekuiper/pkg/api"
  24. )
  25. type fileWriter struct {
  26. File *os.File
  27. Writer io.Writer
  28. Hook writerHooks
  29. Start time.Time
  30. Count int
  31. Compress string
  32. fileBuffer *bufio.Writer
  33. // Whether the file has written any data. It is only used to determine if new line is needed when writing data.
  34. Written bool
  35. }
  36. func createFileWriter(ctx api.StreamContext, fn string, ft FileType, headers string, compressAlgorithm string) (_ *fileWriter, ge error) {
  37. ctx.GetLogger().Infof("Create new file writer for %s", fn)
  38. fws := &fileWriter{Start: conf.GetNow()}
  39. var (
  40. f *os.File
  41. err error
  42. )
  43. if _, err = os.Stat(fn); os.IsNotExist(err) {
  44. if _, err := os.Create(fn); err != nil {
  45. return nil, fmt.Errorf("fail to create file %s: %v", fn, err)
  46. }
  47. }
  48. f, err = os.OpenFile(fn, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModeAppend)
  49. if err != nil {
  50. return nil, fmt.Errorf("fail to open file sink for %s: %v", fn, err)
  51. }
  52. defer func() {
  53. if ge != nil {
  54. _ = f.Close()
  55. }
  56. }()
  57. fws.File = f
  58. switch ft {
  59. case JSON_TYPE:
  60. fws.Hook = jsonHooks
  61. case CSV_TYPE:
  62. fws.Hook = &csvWriterHooks{header: []byte(headers)}
  63. case LINES_TYPE:
  64. fws.Hook = linesHooks
  65. }
  66. fws.Compress = compressAlgorithm
  67. if compressAlgorithm == "" {
  68. fws.Writer = bufio.NewWriter(f)
  69. } else {
  70. fws.fileBuffer = bufio.NewWriter(f)
  71. fws.Writer, err = compressor.GetCompressWriter(compressAlgorithm, fws.fileBuffer)
  72. if err != nil {
  73. return nil, fmt.Errorf("fail to get compress writer for %s: %v", compressAlgorithm, err)
  74. }
  75. }
  76. _, err = fws.Writer.Write(fws.Hook.Header())
  77. if err != nil {
  78. return nil, err
  79. }
  80. return fws, nil
  81. }
  82. func (fw *fileWriter) Close(ctx api.StreamContext) error {
  83. var err error
  84. if fw.File != nil {
  85. ctx.GetLogger().Debugf("File sync before close")
  86. _, e := fw.Writer.Write(fw.Hook.Footer())
  87. if e != nil {
  88. ctx.GetLogger().Errorf("file sink fails to write footer with error %s.", e)
  89. }
  90. if fw.Compress != "" {
  91. e := fw.Writer.(io.Closer).Close()
  92. if e != nil {
  93. ctx.GetLogger().Errorf("file sink fails to close compress writer with error %s.", err)
  94. }
  95. err = fw.fileBuffer.Flush()
  96. if err != nil {
  97. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  98. }
  99. } else {
  100. err = fw.Writer.(*bufio.Writer).Flush()
  101. if err != nil {
  102. ctx.GetLogger().Errorf("file sink fails to flush with error %s.", err)
  103. }
  104. }
  105. err = fw.File.Sync()
  106. if err != nil {
  107. ctx.GetLogger().Errorf("file sink fails to sync with error %s.", err)
  108. }
  109. ctx.GetLogger().Infof("Close file %s", fw.File.Name())
  110. return fw.File.Close()
  111. }
  112. return nil
  113. }