This repository has been archived by the owner on Mar 29, 2024. It is now read-only.
/
api.go
68 lines (57 loc) · 1.6 KB
/
api.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package captain
import (
"errors"
"fmt"
"github.com/safing/portbase/api"
"github.com/safing/portbase/database"
"github.com/safing/portbase/database/query"
"github.com/safing/portbase/modules"
)
const (
apiPathForSPNReInit = "spn/reinit"
)
func registerAPIEndpoints() error {
if err := api.RegisterEndpoint(api.Endpoint{
Path: apiPathForSPNReInit,
Write: api.PermitAdmin,
// BelongsTo: module, // Do not attach to module, as this must run outside of the module.
ActionFunc: handleReInit,
Name: "Re-initialize SPN",
Description: "Stops the SPN, resets all caches and starts it again. The SPN account and settings are not changed.",
}); err != nil {
return err
}
return nil
}
func handleReInit(ar *api.Request) (msg string, err error) {
// Disable module and check
changed := module.Disable()
if !changed {
return "", errors.New("can only re-initialize when the SPN is enabled")
}
// Run module manager.
err = modules.ManageModules()
if err != nil {
return "", fmt.Errorf("failed to stop SPN: %w", err)
}
// Delete SPN cache.
db := database.NewInterface(&database.Options{
Local: true,
Internal: true,
})
deletedRecords, err := db.Purge(ar.Context(), query.New("cache:spn/"))
if err != nil {
return "", fmt.Errorf("failed to delete SPN cache: %w", err)
}
// Enable module.
module.Enable()
// Run module manager.
err = modules.ManageModules()
if err != nil {
return "", fmt.Errorf("failed to start SPN after cache reset: %w", err)
}
return fmt.Sprintf(
"Completed SPN re-initialization and deleted %d cache records in the process.",
deletedRecords,
), nil
}