safing-portmaster/cmds/portmaster-start/logs.go
Daniel Hååvi 80664d1a27
Restructure modules (#1572)
* Move portbase into monorepo

* Add new simple module mgr

* [WIP] Switch to new simple module mgr

* Add StateMgr and more worker variants

* [WIP] Switch more modules

* [WIP] Switch more modules

* [WIP] swtich more modules

* [WIP] switch all SPN modules

* [WIP] switch all service modules

* [WIP] Convert all workers to the new module system

* [WIP] add new task system to module manager

* [WIP] Add second take for scheduling workers

* [WIP] Add FIXME for bugs in new scheduler

* [WIP] Add minor improvements to scheduler

* [WIP] Add new worker scheduler

* [WIP] Fix more bug related to new module system

* [WIP] Fix start handing of the new module system

* [WIP] Improve startup process

* [WIP] Fix minor issues

* [WIP] Fix missing subsystem in settings

* [WIP] Initialize managers in constructor

* [WIP] Move module event initialization to constrictors

* [WIP] Fix setting for enabling and disabling the SPN module

* [WIP] Move API registeration into module construction

* [WIP] Update states mgr for all modules

* [WIP] Add CmdLine operation support

* Add state helper methods to module group and instance

* Add notification and module status handling to status package

* Fix starting issues

* Remove pilot widget and update security lock to new status data

* Remove debug logs

* Improve http server shutdown

* Add workaround for cleanly shutting down firewall+netquery

* Improve logging

* Add syncing states with notifications for new module system

* Improve starting, stopping, shutdown; resolve FIXMEs/TODOs

* [WIP] Fix most unit tests

* Review new module system and fix minor issues

* Push shutdown and restart events again via API

* Set sleep mode via interface

* Update example/template module

* [WIP] Fix spn/cabin unit test

* Remove deprecated UI elements

* Make log output more similar for the logging transition phase

* Switch spn hub and observer cmds to new module system

* Fix log sources

* Make worker mgr less error prone

* Fix tests and minor issues

* Fix observation hub

* Improve shutdown and restart handling

* Split up big connection.go source file

* Move varint and dsd packages to structures repo

* Improve expansion test

* Fix linter warnings

* Fix interception module on windows

* Fix linter errors

---------

Co-authored-by: Vladimir Stoilov <vladimir@safing.io>
2024-08-09 18:15:48 +03:00

127 lines
3.4 KiB
Go

package main
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"time"
"github.com/spf13/cobra"
"github.com/safing/portmaster/base/database/record"
"github.com/safing/portmaster/base/info"
"github.com/safing/structures/container"
"github.com/safing/structures/dsd"
)
func initializeLogFile(logFilePath string, identifier string, version string) *os.File {
logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE, 0o0440) //nolint:gosec // As desired.
if err != nil {
log.Printf("failed to create log file %s: %s\n", logFilePath, err)
return nil
}
// create header, so that the portmaster can view log files as a database
meta := record.Meta{}
meta.Update()
meta.SetAbsoluteExpiry(time.Now().Add(720 * time.Hour).Unix()) // one month
// manually marshal
// version
c := container.New([]byte{1})
// meta
metaSection, err := dsd.Dump(meta, dsd.JSON)
if err != nil {
log.Printf("failed to serialize header for log file %s: %s\n", logFilePath, err)
finalizeLogFile(logFile)
return nil
}
c.AppendAsBlock(metaSection)
// log file data type (string) and newline for better manual viewing
c.Append([]byte("S\n"))
c.Append([]byte(fmt.Sprintf("executing %s version %s on %s %s\n", identifier, version, runtime.GOOS, runtime.GOARCH)))
_, err = logFile.Write(c.CompileData())
if err != nil {
log.Printf("failed to write header for log file %s: %s\n", logFilePath, err)
finalizeLogFile(logFile)
return nil
}
return logFile
}
func finalizeLogFile(logFile *os.File) {
logFilePath := logFile.Name()
err := logFile.Close()
if err != nil {
log.Printf("failed to close log file %s: %s\n", logFilePath, err)
}
// check file size
stat, err := os.Stat(logFilePath)
if err != nil {
return
}
// delete if file is smaller than
if stat.Size() >= 200 { // header + info is about 150 bytes
return
}
if err := os.Remove(logFilePath); err != nil {
log.Printf("failed to delete empty log file %s: %s\n", logFilePath, err)
}
}
func getLogFile(options *Options, version, ext string) *os.File {
// check logging dir
logFileBasePath := filepath.Join(logsRoot.Path, options.ShortIdentifier)
err := logsRoot.EnsureAbsPath(logFileBasePath)
if err != nil {
log.Printf("failed to check/create log file folder %s: %s\n", logFileBasePath, err)
}
// open log file
logFilePath := filepath.Join(logFileBasePath, fmt.Sprintf("%s%s", time.Now().UTC().Format("2006-01-02-15-04-05"), ext))
return initializeLogFile(logFilePath, options.Identifier, version)
}
func getPmStartLogFile(ext string) *os.File {
return getLogFile(&Options{
ShortIdentifier: "start",
Identifier: "start/portmaster-start",
}, info.Version(), ext)
}
//nolint:unused // false positive on linux, currently used by windows only. TODO: move to a _windows file.
func logControlError(cErr error) {
// check if error present
if cErr == nil {
return
}
errorFile := getPmStartLogFile(".error.log")
if errorFile == nil {
return
}
defer func() {
_ = errorFile.Close()
}()
fmt.Fprintln(errorFile, cErr.Error())
}
//nolint:deadcode,unused // false positive on linux, currently used by windows only. TODO: move to a _windows file.
func runAndLogControlError(wrappedFunc func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
err := wrappedFunc(cmd, args)
if err != nil {
logControlError(err)
}
return err
}
}