safing-portmaster/cmds/portmaster-start/update.go
Daniel Hååvi 80664d1a27
Restructure modules ()
* 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

158 lines
3.7 KiB
Go

package main
import (
"context"
"fmt"
"log"
"os"
"github.com/spf13/cobra"
portlog "github.com/safing/portmaster/base/log"
"github.com/safing/portmaster/base/updater"
"github.com/safing/portmaster/service/updates/helper"
)
var (
reset bool
intelOnly bool
)
func init() {
rootCmd.AddCommand(updateCmd)
rootCmd.AddCommand(purgeCmd)
flags := updateCmd.Flags()
flags.BoolVar(&reset, "reset", false, "Delete all resources and re-download the basic set")
flags.BoolVar(&intelOnly, "intel-only", false, "Only make downloading intel updates mandatory")
}
var (
updateCmd = &cobra.Command{
Use: "update",
Short: "Run a manual update process",
RunE: func(cmd *cobra.Command, args []string) error {
return downloadUpdates()
},
}
purgeCmd = &cobra.Command{
Use: "purge",
Short: "Remove old resource versions that are superseded by at least three versions",
RunE: func(cmd *cobra.Command, args []string) error {
return purge()
},
}
)
func indexRequired(cmd *cobra.Command) bool {
switch cmd {
case updateCmd, purgeCmd:
return true
default:
return false
}
}
func downloadUpdates() error {
// Check if only intel data is mandatory.
if intelOnly {
helper.IntelOnly()
}
// Set registry state notify callback.
registry.StateNotifyFunc = logProgress
// Set required updates.
registry.MandatoryUpdates = helper.MandatoryUpdates()
registry.AutoUnpack = helper.AutoUnpackUpdates()
if reset {
// Delete storage.
err := os.RemoveAll(registry.StorageDir().Path)
if err != nil {
return fmt.Errorf("failed to reset update dir: %w", err)
}
err = registry.StorageDir().Ensure()
if err != nil {
return fmt.Errorf("failed to create update dir: %w", err)
}
// Reset registry resources.
registry.ResetResources()
}
// Update all indexes.
err := registry.UpdateIndexes(context.TODO())
if err != nil {
return err
}
// Check if updates are available.
if len(registry.GetState().Updates.PendingDownload) == 0 {
log.Println("all resources are up to date")
return nil
}
// Download all required updates.
err = registry.DownloadUpdates(context.TODO(), true)
if err != nil {
return err
}
// Select versions and unpack the selected.
registry.SelectVersions()
err = registry.UnpackResources()
if err != nil {
return fmt.Errorf("failed to unpack resources: %w", err)
}
if !intelOnly {
// Fix chrome-sandbox permissions
if err := helper.EnsureChromeSandboxPermissions(registry); err != nil {
return fmt.Errorf("failed to fix electron permissions: %w", err)
}
}
return nil
}
func logProgress(state *updater.RegistryState) {
switch state.ID {
case updater.StateChecking:
if state.Updates.LastCheckAt == nil {
log.Println("checking for new versions")
}
case updater.StateDownloading:
if state.Details == nil {
log.Printf("downloading %d updates\n", len(state.Updates.PendingDownload))
} else if downloadDetails, ok := state.Details.(*updater.StateDownloadingDetails); ok {
if downloadDetails.FinishedUpTo < len(downloadDetails.Resources) {
log.Printf(
"[%d/%d] downloading %s",
downloadDetails.FinishedUpTo+1,
len(downloadDetails.Resources),
downloadDetails.Resources[downloadDetails.FinishedUpTo],
)
} else if state.Updates.LastDownloadAt == nil {
log.Println("finalizing downloads")
}
}
}
}
func purge() error {
portlog.SetLogLevel(portlog.TraceLevel)
// logging is configured as a persistent pre-run method inherited from
// the root command but since we don't use run.Run() we need to start
// logging ourself.
err := portlog.Start()
if err != nil {
fmt.Printf("failed to start logging: %s\n", err)
}
defer portlog.Shutdown()
registry.Purge(3)
return nil
}