go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/_motor/providers/os/events/file.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package events
     5  
     6  import (
     7  	"github.com/rs/zerolog/log"
     8  	"github.com/spf13/afero"
     9  	"go.mondoo.com/cnquery/motor/providers"
    10  	"go.mondoo.com/cnquery/motor/providers/os"
    11  )
    12  
    13  // FileOp describes a set of file operations.
    14  type FileOp uint32
    15  
    16  // These are the generalized file operations that can trigger a notification.
    17  const (
    18  	Create FileOp = 1 << iota
    19  	Write
    20  	Remove
    21  	Rename
    22  	Chmod
    23  	Modify // is this the same of rewrite
    24  	Enoent
    25  	// TODO: distingush between file content and file metadata modify
    26  	Error
    27  )
    28  
    29  // file events handling
    30  type FileObservable struct {
    31  	identifier string
    32  	FileOp     FileOp
    33  	File       afero.File
    34  	Error      error
    35  }
    36  
    37  func (fo *FileObservable) Type() providers.ObservableType {
    38  	return providers.FileType
    39  }
    40  
    41  func (fo *FileObservable) ID() string {
    42  	return fo.identifier
    43  }
    44  
    45  func (fo *FileObservable) Op() FileOp {
    46  	return fo.FileOp
    47  }
    48  
    49  func NewFileRunnable(path string) func(m os.OperatingSystemProvider) (providers.Observable, error) {
    50  	return func(m os.OperatingSystemProvider) (providers.Observable, error) {
    51  		fileop := Modify
    52  		file, err := m.FS().Open(path)
    53  		// TODO: we may want to distingush further, but it does not make sense to do transport specific error handling here
    54  		// therefore we may need common types similar to https://github.com/golang/go/blob/master/src/os/error.go#L22-L23
    55  		if err != nil {
    56  			log.Debug().Err(err).Msg("watch on non-existing file")
    57  			fileop = Error
    58  		}
    59  		return &FileObservable{File: file, FileOp: fileop, Error: err}, nil
    60  	}
    61  }