safing-portmaster/spn/docks/op_sync_state.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

151 lines
3.8 KiB
Go

package docks
import (
"context"
"time"
"github.com/safing/portmaster/service/mgr"
"github.com/safing/portmaster/spn/conf"
"github.com/safing/portmaster/spn/terminal"
"github.com/safing/structures/container"
"github.com/safing/structures/dsd"
)
// SyncStateOpType is the type ID of the sync state operation.
const SyncStateOpType = "sync/state"
// SyncStateOp is used to sync the crane state.
type SyncStateOp struct {
terminal.OneOffOperationBase
}
// SyncStateMessage holds the sync data.
type SyncStateMessage struct {
Stopping bool
RequestStopping bool
}
// Type returns the type ID.
func (op *SyncStateOp) Type() string {
return SyncStateOpType
}
func init() {
terminal.RegisterOpType(terminal.OperationFactory{
Type: SyncStateOpType,
Requires: terminal.IsCraneController,
Start: runSyncStateOp,
})
}
// startSyncStateOp starts a worker that runs the sync state operation.
func (crane *Crane) startSyncStateOp() {
module.mgr.Go("sync crane state", func(wc *mgr.WorkerCtx) error {
tErr := crane.Controller.SyncState(wc.Ctx())
if tErr != nil {
return tErr
}
return nil
})
}
// SyncState runs a sync state operation.
func (controller *CraneControllerTerminal) SyncState(ctx context.Context) *terminal.Error {
// Check if we are a public Hub, whether we own the crane and whether the lane is public too.
if !conf.PublicHub() || !controller.Crane.Public() {
return nil
}
// Create and init.
op := &SyncStateOp{}
op.Init()
// Get optimization states.
requestStopping := false
func() {
controller.Crane.NetState.lock.Lock()
defer controller.Crane.NetState.lock.Unlock()
requestStopping = controller.Crane.NetState.stoppingRequested
}()
// Create sync message.
msg := &SyncStateMessage{
Stopping: controller.Crane.stopping.IsSet(),
RequestStopping: requestStopping,
}
data, err := dsd.Dump(msg, dsd.CBOR)
if err != nil {
return terminal.ErrInternalError.With("%w", err)
}
// Send message.
tErr := controller.StartOperation(op, container.New(data), 30*time.Second)
if tErr != nil {
return tErr
}
// Wait for reply
select {
case tErr = <-op.Result:
if tErr.IsError() {
return tErr
}
return nil
case <-ctx.Done():
return nil
case <-time.After(1 * time.Minute):
return terminal.ErrTimeout.With("timed out while waiting for sync crane result")
}
}
func runSyncStateOp(t terminal.Terminal, opID uint32, data *container.Container) (terminal.Operation, *terminal.Error) {
// Check if we are a on a crane controller.
var ok bool
var controller *CraneControllerTerminal
if controller, ok = t.(*CraneControllerTerminal); !ok {
return nil, terminal.ErrIncorrectUsage.With("can only be used with a crane controller")
}
// Check if we are a public Hub and whether the lane is public too.
if !conf.PublicHub() || !controller.Crane.Public() {
return nil, terminal.ErrPermissionDenied.With("only public lanes can sync crane status")
}
// Load message.
syncState := &SyncStateMessage{}
_, err := dsd.Load(data.CompileData(), syncState)
if err != nil {
return nil, terminal.ErrMalformedData.With("failed to load sync state message: %w", err)
}
// Apply optimization state.
controller.Crane.NetState.lock.Lock()
defer controller.Crane.NetState.lock.Unlock()
controller.Crane.NetState.stoppingRequestedByPeer = syncState.RequestStopping
// Apply crane state only when we don't own the crane.
if !controller.Crane.IsMine() {
// Apply sync state.
var changed bool
if syncState.Stopping {
if controller.Crane.stopping.SetToIf(false, true) {
controller.Crane.NetState.markedStoppingAt = time.Now()
changed = true
}
} else {
if controller.Crane.stopping.SetToIf(true, false) {
controller.Crane.NetState.markedStoppingAt = time.Time{}
changed = true
}
}
// Notify of change.
if changed {
controller.Crane.NotifyUpdate()
}
}
return nil, nil
}