github.com/yankunsam/loki/v2@v2.6.3-0.20220817130409-389df5235c27/clients/pkg/promtail/targets/windows/bookmark.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package windows
     5  
     6  import (
     7  	"io/ioutil"
     8  	"os"
     9  
    10  	"github.com/spf13/afero"
    11  
    12  	"github.com/grafana/loki/clients/pkg/promtail/targets/windows/win_eventlog"
    13  )
    14  
    15  type bookMark struct {
    16  	handle win_eventlog.EvtHandle
    17  	file   afero.File
    18  	isNew  bool
    19  
    20  	buf []byte
    21  }
    22  
    23  // newBookMark creates a new windows event bookmark.
    24  // The bookmark will be saved at the given path. Use save to save the current position for a given event.
    25  func newBookMark(path string) (*bookMark, error) {
    26  	// 16kb buffer for rendering bookmark
    27  	buf := make([]byte, 16<<10)
    28  
    29  	_, err := fs.Stat(path)
    30  	// creates a new bookmark file if none exists.
    31  	if os.IsNotExist(err) {
    32  		file, err := fs.Create(path)
    33  		if err != nil {
    34  			return nil, err
    35  		}
    36  		bm, err := win_eventlog.CreateBookmark("")
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  		return &bookMark{
    41  			handle: bm,
    42  			file:   file,
    43  			isNew:  true,
    44  			buf:    buf,
    45  		}, nil
    46  	}
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	// otherwise open the current one.
    51  	file, err := fs.OpenFile(path, os.O_RDWR, 0666)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	fileContent, err := ioutil.ReadAll(file)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	fileString := string(fileContent)
    60  	// load the current bookmark.
    61  	bm, err := win_eventlog.CreateBookmark(fileString)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  	return &bookMark{
    66  		handle: bm,
    67  		file:   file,
    68  		isNew:  fileString == "",
    69  		buf:    buf,
    70  	}, nil
    71  }
    72  
    73  // save Saves the bookmark at the current event position.
    74  func (b *bookMark) save(event win_eventlog.EvtHandle) error {
    75  	newBookmark, err := win_eventlog.UpdateBookmark(b.handle, event, b.buf)
    76  	if err != nil {
    77  		return err
    78  	}
    79  	if err := b.file.Truncate(0); err != nil {
    80  		return err
    81  	}
    82  	if _, err := b.file.Seek(0, 0); err != nil {
    83  		return err
    84  	}
    85  	_, err = b.file.WriteString(newBookmark)
    86  	return err
    87  }
    88  
    89  // close closes the current bookmark file.
    90  func (b *bookMark) close() error {
    91  	return b.file.Close()
    92  }