Merge pull request #1337 from safing/fix/update-trigger

Fix and improve triggering updates from UI
This commit is contained in:
Daniel Hovie 2023-10-06 17:35:49 +02:00 committed by GitHub
commit 26fbbcd08d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 66 additions and 30 deletions

View file

@ -219,7 +219,7 @@ func updateOnlineStatus(status OnlineStatus, portalURL *url.URL, comment string)
// Trigger update check when coming (semi) online. // Trigger update check when coming (semi) online.
if Online() { if Online() {
_ = updates.TriggerUpdate(false) _ = updates.TriggerUpdate(false, false)
} }
} }
} }

View file

@ -1,6 +1,8 @@
package updates package updates
import ( import (
"net/http"
"github.com/safing/portbase/api" "github.com/safing/portbase/api"
) )
@ -10,16 +12,32 @@ const (
func registerAPIEndpoints() error { func registerAPIEndpoints() error {
return api.RegisterEndpoint(api.Endpoint{ return api.RegisterEndpoint(api.Endpoint{
Name: "Check for Updates",
Description: "Checks if new versions are available. If automatic updates are enabled, they are also downloaded and applied.",
Parameters: []api.Parameter{{
Method: http.MethodPost,
Field: "download",
Value: "",
Description: "Force downloading and applying of all updates, regardless of auto-update settings.",
}},
Path: apiPathCheckForUpdates, Path: apiPathCheckForUpdates,
Write: api.PermitUser, Write: api.PermitUser,
BelongsTo: module, BelongsTo: module,
ActionFunc: func(_ *api.Request) (msg string, err error) { ActionFunc: func(r *api.Request) (msg string, err error) {
if err := TriggerUpdate(false); err != nil { // Check if we should also download regardless of settings.
downloadAll := r.URL.Query().Has("download")
// Trigger update task.
err = TriggerUpdate(true, downloadAll)
if err != nil {
return "", err return "", err
} }
return "triggered update check", nil
// Report how we triggered.
if downloadAll {
return "downloading all updates...", nil
}
return "checking for updates...", nil
}, },
Name: "Check for Updates",
Description: "Checks if new versions are available and downloads and applies them, if automatic updates are enabled.",
}) })
} }

View file

@ -24,7 +24,8 @@ var (
softwareUpdatesCurrentlyEnabled bool softwareUpdatesCurrentlyEnabled bool
intelUpdatesCurrentlyEnabled bool intelUpdatesCurrentlyEnabled bool
previousDevMode bool previousDevMode bool
forceUpdate = abool.New() forceCheck = abool.New()
forceDownload = abool.New()
) )
func registerConfig() error { func registerConfig() error {
@ -165,7 +166,7 @@ func updateRegistryConfig(_ context.Context, _ interface{}) error {
if softwareUpdatesCurrentlyEnabled || intelUpdatesCurrentlyEnabled { if softwareUpdatesCurrentlyEnabled || intelUpdatesCurrentlyEnabled {
module.Resolve("") module.Resolve("")
if err := TriggerUpdate(false); err != nil { if err := TriggerUpdate(true, false); err != nil {
log.Warningf("updates: failed to trigger update: %s", err) log.Warningf("updates: failed to trigger update: %s", err)
} }
log.Infof("updates: automatic updates are now enabled") log.Infof("updates: automatic updates are now enabled")

View file

@ -220,17 +220,20 @@ func start() error {
} }
// TriggerUpdate queues the update task to execute ASAP. // TriggerUpdate queues the update task to execute ASAP.
func TriggerUpdate(force bool) error { func TriggerUpdate(forceIndexCheck, downloadAll bool) error {
switch { switch {
case !module.Online(): case !module.Online():
updateASAP = true updateASAP = true
case !force && !enableSoftwareUpdates() && !enableIntelUpdates(): case !forceIndexCheck && !enableSoftwareUpdates() && !enableIntelUpdates():
return fmt.Errorf("automatic updating is disabled") return fmt.Errorf("automatic updating is disabled")
default: default:
if force { if forceIndexCheck {
forceUpdate.Set() forceCheck.Set()
}
if downloadAll {
forceDownload.Set()
} }
updateTask.StartASAP() updateTask.StartASAP()
} }
@ -263,8 +266,12 @@ func checkForUpdates(ctx context.Context) (err error) {
} }
}() }()
forcedUpdate := forceUpdate.SetToIf(true, false) // Get flags.
if !forcedUpdate && !enableSoftwareUpdates() && !enableIntelUpdates() { forceIndexCheck := forceCheck.SetToIf(true, false)
downloadAll := forceDownload.SetToIf(true, false)
// Check again if downloading updates is enabled, or forced.
if !forceIndexCheck && !enableSoftwareUpdates() && !enableIntelUpdates() {
log.Warningf("updates: automatic updates are disabled") log.Warningf("updates: automatic updates are disabled")
return nil return nil
} }
@ -273,13 +280,13 @@ func checkForUpdates(ctx context.Context) (err error) {
// Resolve any error and send success notification. // Resolve any error and send success notification.
if err == nil { if err == nil {
log.Infof("updates: successfully checked for updates") log.Infof("updates: successfully checked for updates")
notifyUpdateSuccess(forcedUpdate) notifyUpdateSuccess(forceIndexCheck)
return return
} }
// Log and notify error. // Log and notify error.
log.Errorf("updates: check failed: %s", err) log.Errorf("updates: check failed: %s", err)
notifyUpdateCheckFailed(forcedUpdate, err) notifyUpdateCheckFailed(forceIndexCheck, err)
}() }()
if err = registry.UpdateIndexes(ctx); err != nil { if err = registry.UpdateIndexes(ctx); err != nil {
@ -287,7 +294,7 @@ func checkForUpdates(ctx context.Context) (err error) {
return //nolint:nakedret // TODO: Would "return err" work with the defer? return //nolint:nakedret // TODO: Would "return err" work with the defer?
} }
err = registry.DownloadUpdates(ctx, forcedUpdate) err = registry.DownloadUpdates(ctx, downloadAll)
if err != nil { if err != nil {
err = fmt.Errorf("failed to download updates: %w", err) err = fmt.Errorf("failed to download updates: %w", err)
return //nolint:nakedret // TODO: Would "return err" work with the defer? return //nolint:nakedret // TODO: Would "return err" work with the defer?

View file

@ -21,7 +21,7 @@ const (
var updateFailedCnt = new(atomic.Int32) var updateFailedCnt = new(atomic.Int32)
func notifyUpdateSuccess(forced bool) { func notifyUpdateSuccess(force bool) {
updateFailedCnt.Store(0) updateFailedCnt.Store(0)
module.Resolve(updateFailed) module.Resolve(updateFailed)
updateState := registry.GetState().Updates updateState := registry.GetState().Updates
@ -35,7 +35,7 @@ func notifyUpdateSuccess(forced bool) {
time.Since(*updateState.LastDownloadAt) < 5*time.Second: time.Since(*updateState.LastDownloadAt) < 5*time.Second:
// Show notification if we downloaded something within the last minute. // Show notification if we downloaded something within the last minute.
flavor = updateSuccessDownloaded flavor = updateSuccessDownloaded
case forced: case force:
// Always show notification if update was manually triggered. // Always show notification if update was manually triggered.
default: default:
// Otherwise, the update was uneventful. Do not show notification. // Otherwise, the update was uneventful. Do not show notification.
@ -48,7 +48,7 @@ func notifyUpdateSuccess(forced bool) {
EventID: updateSuccess, EventID: updateSuccess,
Type: notifications.Info, Type: notifications.Info,
Title: "Portmaster Is Up-To-Date", Title: "Portmaster Is Up-To-Date",
Message: "Portmaster successfully checked for updates. Everything is up to date. Most updates are applied automatically. You will be notified of important updates that need restarting.", Message: "Portmaster successfully checked for updates. Everything is up to date.\n\n" + getUpdatingInfoMsg(),
Expires: time.Now().Add(1 * time.Minute).Unix(), Expires: time.Now().Add(1 * time.Minute).Unix(),
AvailableActions: []*notifications.Action{ AvailableActions: []*notifications.Action{
{ {
@ -64,7 +64,7 @@ func notifyUpdateSuccess(forced bool) {
- %s - %s
Press "Download Now" or check for updates later to download and automatically apply all pending updates. You will be notified of important updates that need restarting.`, Press "Download Now" to download and automatically apply all pending updates. You will be notified of important updates that need restarting.`,
len(updateState.PendingDownload), len(updateState.PendingDownload),
strings.Join(updateState.PendingDownload, "\n- "), strings.Join(updateState.PendingDownload, "\n- "),
) )
@ -84,7 +84,7 @@ Press "Download Now" or check for updates later to download and automatically ap
Text: "Download Now", Text: "Download Now",
Type: notifications.ActionTypeWebhook, Type: notifications.ActionTypeWebhook,
Payload: &notifications.ActionTypeWebhookPayload{ Payload: &notifications.ActionTypeWebhookPayload{
URL: apiPathCheckForUpdates, URL: apiPathCheckForUpdates + "?download",
ResultAction: "display", ResultAction: "display",
}, },
}, },
@ -95,15 +95,14 @@ Press "Download Now" or check for updates later to download and automatically ap
msg := fmt.Sprintf( msg := fmt.Sprintf(
`%d updates were downloaded and applied: `%d updates were downloaded and applied:
- %s`, - %s
%s
`,
len(updateState.LastDownload), len(updateState.LastDownload),
strings.Join(updateState.LastDownload, "\n- "), strings.Join(updateState.LastDownload, "\n- "),
getUpdatingInfoMsg(),
) )
if enableSoftwareUpdates() {
msg += "\n\nYou will be notified of important updates that need restarting."
} else {
msg += "\n\nAutomatic software updates are disabled, and you will be notified when a new software update is ready to be downloaded and applied."
}
notifications.Notify(&notifications.Notification{ notifications.Notify(&notifications.Notification{
EventID: updateSuccess, EventID: updateSuccess,
@ -122,12 +121,23 @@ Press "Download Now" or check for updates later to download and automatically ap
} }
} }
func notifyUpdateCheckFailed(forced bool, err error) { func getUpdatingInfoMsg() string {
switch {
case enableSoftwareUpdates() && enableIntelUpdates():
return "You will be notified of important updates that need restarting."
case enableIntelUpdates():
return "Automatic software updates are disabled, but you will be notified when a new software update is ready to be downloaded and applied."
default:
return "Automatic software updates are disabled. Please check for updates regularly yourself."
}
}
func notifyUpdateCheckFailed(force bool, err error) {
failedCnt := updateFailedCnt.Add(1) failedCnt := updateFailedCnt.Add(1)
lastSuccess := registry.GetState().Updates.LastSuccessAt lastSuccess := registry.GetState().Updates.LastSuccessAt
switch { switch {
case forced: case force:
// Always show notification if update was manually triggered. // Always show notification if update was manually triggered.
case failedCnt < failedUpdateNotifyCountThreshold: case failedCnt < failedUpdateNotifyCountThreshold:
// Not failed often enough for notification. // Not failed often enough for notification.