8000 remove pid file on exit by geyslan · Pull Request #3075 · aquasecurity/tracee · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

remove pid file on exit #3075

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions pkg/cmd/tracee.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@ package cmd
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"syscall"

"github.com/aquasecurity/tracee/pkg/cmd/printer"
tracee "github.com/aquasecurity/tracee/pkg/ebpf"
"github.com/aquasecurity/tracee/pkg/errfmt"
"github.com/aquasecurity/tracee/pkg/events"
"github.com/aquasecurity/tracee/pkg/logger"
"github.com/aquasecurity/tracee/pkg/server"
"github.com/aquasecurity/tracee/pkg/utils"
)

type Runner struct {
Expand Down Expand Up @@ -53,6 +58,16 @@ func (r Runner) Run(ctx context.Context) error {
return errfmt.Errorf("error initializing Tracee: %v", err)
}

// Manage PID file
if err := writePidFile(t.OutDir); err != nil {
return errfmt.WrapError(err)
}
defer func() {
if err := removePidFile(t.OutDir); err != nil {
logger.Errorw("error removing pid file", "error", err)
}
}()

broadcast := printer.NewBroadcast(r.Printers)

// Start event channel reception
Expand Down Expand Up @@ -173,3 +188,29 @@ func GetContainerMode(cfg tracee.Config) printer.ContainerMode {

return containerMode
}

const pidFileName = "tracee.pid"

// Initialize PID file
func writePidFile(dir *os.File) error {
pidFile, err := utils.OpenAt(dir, pidFileName, syscall.O_WRONLY|syscall.O_CREAT, 0640)
if err != nil {
return errfmt.Errorf("error creating readiness file: %v", err)
}

_, err = pidFile.Write([]byte(strconv.Itoa(os.Getpid()) + "\n"))
if err != nil {
return errfmt.Errorf("error writing to readiness file: %v", err)
}

return nil
}

// Remove PID file
func removePidFile(dir *os.File) error {
if err := utils.RemoveAt(dir, pidFileName, 0); err != nil {
return errfmt.Errorf("%v", err)
}

return nil
}
4 changes: 2 additions & 2 deletions pkg/ebpf/events_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func (t *Tracee) processSchedProcessExec(event *trace.Event) error {
// capture exec'ed files ?
if t.config.Capture.Exec {
destinationDirPath := containerId
if err := utils.MkdirAtExist(t.outDir, destinationDirPath, 0755); err != nil {
if err := utils.MkdirAtExist(t.OutDir, destinationDirPath, 0755); err != nil {
return errfmt.WrapError(err)
}
destinationFilePath := filepath.Join(
Expand All @@ -218,7 +218,7 @@ func (t *Tracee) processSchedProcessExec(event *trace.Event) error {
// have a big performance impact)
err := utils.CopyRegularFileByRelativePath(
sourceFilePath,
t.outDir,
t.OutDir,
destinationFilePath,
)
if err != nil {
Expand Down
36 changes: 6 additions & 30 deletions pkg/ebpf/tracee.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"strconv"
"strings"
"sync/atomic"
"syscall"
"time"
"unsafe"

Expand Down Expand Up @@ -168,7 +167,7 @@ type Tracee struct {
startTime uint64
running atomic.Bool
done chan struct{} // signal to safely stop end-stage processing
outDir *os.File // use utils.XXX functions to access this file
OutDir *os.File // use utils.XXX functions to create or write to this file
stats metrics.Stats
sigEngine *engine.Engine
// Events
Expand Down Expand Up @@ -516,15 +515,15 @@ func (t *Tracee) Init() error {
return errfmt.Errorf("error creating output path: %v", err)
}

t.outDir, err = utils.OpenExistingDir(t.config.Capture.OutputPath)
t.OutDir, err = utils.OpenExistingDir(t.config.Capture.OutputPath)
if err != nil {
t.Close()
return errfmt.Errorf("error opening out directory: %v", err)
}

// Initialize network capture (all needed pcap files)

t.netCapturePcap, err = pcaps.New(t.config.Capture.Net, t.outDir)
t.netCapturePcap, err = pcaps.New(t.config.Capture.Net, t.OutDir)
if err != nil {
t.Close()
return errfmt.Errorf("error initializing network capture: %v", err)
Expand Down Expand Up @@ -1529,13 +1528,6 @@ func (t *Tracee) Run(ctx gocontext.Context) error {
t.bpfLogsPerfMap.Poll(pollTimeout)
go t.processBPFLogs(ctx)

// write pid file
err = t.writePid()
if err != nil {
// not able to write pid, abort
return errfmt.WrapError(err)
}

// set running state after writing pid file
t.running.Store(true)

Expand All @@ -1554,7 +1546,7 @@ func (t *Tracee) Run(ctx gocontext.Context) error {
// record index of written files
if t.config.Capture.FileWrite {
destinationFilePath := "written_files"
f, err := utils.OpenAt(t.outDir, destinationFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
f, err := utils.OpenAt(t.OutDir, destinationFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errfmt.Errorf("error logging written files")
}
Expand Down Expand Up @@ -1602,8 +1594,7 @@ func (t *Tracee) Close() {
logger.Errorw("failed to clean containers module when closing tracee", "err", err)
}
}
err := t.cgroups.Destroy()
if err != nil {
if err := t.cgroups.Destroy(); err != nil {
logger.Errorw("Cgroups destroy", "error", err)
}

Expand All @@ -1618,7 +1609,7 @@ func (t *Tracee) Running() bool {
}

func (t *Tracee) computeOutFileHash(fileName string) (string, error) {
f, err := utils.OpenAt(t.outDir, fileName, os.O_RDONLY, 0)
f, err := utils.OpenAt(t.OutDir, fileName, os.O_RDONLY, 0)
if err != nil {
return "", errfmt.WrapError(err)
}
Expand Down Expand Up @@ -1835,18 +1826,3 @@ func (t *Tracee) triggerMemDump(event trace.Event) error {
func (t *Tracee) triggerMemDumpCall(address uint64, length uint64, eventHandle uint64) error {
return nil
}

// Initialize PID file
func (t *Tracee) writePid() error {
pidFile, err := utils.OpenAt(t.outDir, "tracee.pid", syscall.O_WRONLY|syscall.O_CREAT, 0640)
if err != nil {
return errfmt.Errorf("error creating readiness file: %v", err)
}

_, err = pidFile.Write([]byte(strconv.Itoa(os.Getpid()) + "\n"))
if err != nil {
return errfmt.Errorf("error writing to readiness file: %v", err)
}

return nil
}
8 changes: 4 additions & 4 deletions pkg/ebpf/write_capture.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (t *Tracee) processFileWrites(ctx context.Context) {
containerId = "host"
}
pathname := containerId
if err := utils.MkdirAtExist(t.outDir, pathname, 0755); err != nil {
if err := utils.MkdirAtExist(t.OutDir, pathname, 0755); err != nil {
t.handleError(err)
continue
}
Expand Down Expand Up @@ -135,7 +135,7 @@ func (t *Tracee) processFileWrites(ctx context.Context) {

fullname := path.Join(pathname, filename)

f, err := utils.OpenAt(t.outDir, fullname, os.O_CREATE|os.O_WRONLY, 0640)
f, err := utils.OpenAt(t.OutDir, fullname, os.O_CREATE|os.O_WRONLY, 0640)
if err != nil {
t.handleError(err)
continue
Expand Down Expand Up @@ -180,7 +180,7 @@ func (t *Tracee) processFileWrites(ctx context.Context) {
// Rename the file to add hash when last chunk was received
if meta.BinType == bufferdecoder.SendKernelModule && uint32(meta.Size)+uint32(meta.Off) == kernelModuleMeta.Size {
fileHash, _ := t.computeOutFileHash(fullname)
err := utils.RenameAt(t.outDir, fullname, t.outDir, fullname+"."+fileHash)
err := utils.RenameAt(t.OutDir, fullname, t.OutDir, fullname+"."+fileHash)
if err != nil {
t.handleError(err)
continue
Expand All @@ -189,7 +189,7 @@ func (t *Tracee) processFileWrites(ctx context.Context) {
fileHash, _ := t.computeOutFileHash(fullname)
// Delete the random int used to differentiate files
dotIndex := strings.LastIndex(fullname, ".")
err := utils.RenameAt(t.outDir, fullname, t.outDir, fullname[:dotIndex]+"."+fileHash)
err := utils.RenameAt(t.OutDir, fullname, t.OutDir, fullname[:dotIndex]+"."+fileHash)
if err != nil {
t.handleError(err)
continue
Expand Down
9 changes: 9 additions & 0 deletions pkg/utils/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ func OpenAt(dir *os.File, relativePath string, flags int, perm fs.FileMode) (*os
return os.NewFile(uintptr(pidFileFD), path.Join(dir.Name(), relativePath)), nil
}

// RemoveAt is a wrapper function to the `unlinkat` syscall using golang types.
func RemoveAt(dir *os.File, relativePath string, flags int) error {
if err := unix.Unlinkat(int(dir.Fd()), relativePath, flags); err != nil {
return errfmt.WrapError(err)
}

return nil
}

// MkdirAt is a wrapper function to the `mkdirat` syscall using golang types.
func MkdirAt(dir *os.File, relativePath string, perm fs.FileMode) error {
return unix.Mkdirat(int(dir.Fd()), relativePath, uint32(perm))
Expand Down
0