chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:08:39 +08:00
commit a0df89c693
5252 changed files with 523444 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
package system
import (
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/dataservices"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/api/internal/upgrade"
"github.com/portainer/portainer/api/platform"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/gorilla/mux"
)
// Handler is the HTTP handler used to handle status operations.
type Handler struct {
*mux.Router
status *portainer.Status
dataStore dataservices.DataStore
upgradeService upgrade.Service
platformService platform.Service
}
// NewHandler creates a handler to manage status operations.
func NewHandler(bouncer security.BouncerService,
status *portainer.Status,
dataStore dataservices.DataStore,
platformService platform.Service,
upgradeService upgrade.Service) *Handler {
h := &Handler{
Router: mux.NewRouter(),
dataStore: dataStore,
status: status,
upgradeService: upgradeService,
platformService: platformService,
}
router := h.PathPrefix("/system").Subrouter()
adminRouter := router.PathPrefix("/").Subrouter()
adminRouter.Use(bouncer.AdminAccess)
adminRouter.Handle("/upgrade", httperror.LoggerHandler(h.systemUpgrade)).Methods(http.MethodPost)
authenticatedRouter := router.PathPrefix("/").Subrouter()
authenticatedRouter.Use(bouncer.AuthenticatedAccess)
authenticatedRouter.Handle("/version", httperror.LoggerHandler(h.version)).Methods(http.MethodGet)
authenticatedRouter.Handle("/nodes", httperror.LoggerHandler(h.systemNodesCount)).Methods(http.MethodGet)
authenticatedRouter.Handle("/info", httperror.LoggerHandler(h.systemInfo)).Methods(http.MethodGet)
publicRouter := router.PathPrefix("/").Subrouter()
publicRouter.Use(bouncer.PublicAccess)
publicRouter.Handle("/status", httperror.LoggerHandler(h.systemStatus)).Methods(http.MethodGet)
// Deprecated /status endpoint, will be removed in the future.
h.Handle("/status",
bouncer.PublicAccess(httperror.LoggerHandler(h.statusInspectDeprecated))).Methods(http.MethodGet)
return h
}
+44
View File
@@ -0,0 +1,44 @@
package system
import (
"net/http"
portainer "github.com/portainer/portainer/api"
statusutil "github.com/portainer/portainer/api/internal/nodes"
"github.com/portainer/portainer/api/internal/snapshot"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/response"
)
type nodesCountResponse struct {
Nodes int `json:"nodes"`
}
// @id systemNodesCount
// @summary Retrieve the count of nodes
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags system
// @produce json
// @success 200 {object} nodesCountResponse "Success"
// @failure 500 "Server error"
// @router /system/nodes [get]
func (handler *Handler) systemNodesCount(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
endpoints, err := handler.dataStore.Endpoint().Endpoints()
if err != nil {
return httperror.InternalServerError("Failed to get environment list", err)
}
var nodes int
for _, endpoint := range endpoints {
if err := snapshot.FillSnapshotData(handler.dataStore, &endpoint, false); err != nil {
return httperror.InternalServerError("Unable to add snapshot data", err)
}
nodes += statusutil.NodesCount([]portainer.Endpoint{endpoint})
}
return response.JSON(w, &nodesCountResponse{Nodes: nodes})
}
+46
View File
@@ -0,0 +1,46 @@
package system
import (
"net/http"
portainer "github.com/portainer/portainer/api"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/rs/zerolog/log"
)
type status struct {
*portainer.Status
}
// @id systemStatus
// @summary Check Portainer status
// @description Retrieve Portainer status
// @description **Access policy**: public
// @tags system
// @produce json
// @success 200 {object} status "Success"
// @router /system/status [get]
func (handler *Handler) systemStatus(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
return response.JSON(w, &status{
Status: handler.status,
})
}
// swagger docs for deprecated route:
// @id StatusInspect
// @summary Check Portainer status
// @deprecated
// @description Deprecated: use the `/system/status` endpoint instead.
// @description Retrieve Portainer status
// @description **Access policy**: public
// @tags status
// @produce json
// @success 200 {object} status "Success"
// @router /status [get]
func (handler *Handler) statusInspectDeprecated(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
log.Warn().Msg("The /status endpoint is deprecated and will be removed in a future version of Portainer. Please use the /system/status endpoint instead.")
return handler.systemStatus(w, r)
}
+63
View File
@@ -0,0 +1,63 @@
package system
import (
"net/http"
"github.com/pkg/errors"
"github.com/portainer/portainer/api/internal/endpointutils"
plf "github.com/portainer/portainer/api/platform"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/response"
)
type systemInfoResponse struct {
Platform plf.ContainerPlatform `json:"platform"`
EdgeAgents int `json:"edgeAgents"`
Agents int `json:"agents"`
}
// @id systemInfo
// @summary Retrieve system info
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags system
// @produce json
// @success 200 {object} systemInfoResponse "Success"
// @failure 500 "Server error"
// @router /system/info [get]
func (handler *Handler) systemInfo(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
environments, err := handler.dataStore.Endpoint().Endpoints()
if err != nil {
return httperror.InternalServerError("Failed to get environment list", err)
}
agents := 0
edgeAgents := 0
for _, environment := range environments {
if endpointutils.IsAgentEndpoint(&environment) {
agents++
}
if endpointutils.IsEdgeEndpoint(&environment) {
edgeAgents++
}
}
platform, err := handler.platformService.GetPlatform()
if err != nil {
if !errors.Is(err, plf.ErrNoLocalEnvironment) {
return httperror.InternalServerError("Failed to get platform", err)
}
// If no local environment is detected, we assume the platform is Docker
// UI will stop showing the upgrade banner
platform = plf.PlatformDocker
}
return response.JSON(w, &systemInfoResponse{
EdgeAgents: edgeAgents,
Agents: agents,
Platform: platform,
})
}
+65
View File
@@ -0,0 +1,65 @@
package system
import (
"net/http"
"regexp"
ceplf "github.com/portainer/portainer/api/platform"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/pkg/errors"
)
type systemUpgradePayload struct {
License string
}
var re = regexp.MustCompile(`^\d-.+`)
func (payload *systemUpgradePayload) Validate(r *http.Request) error {
if payload.License == "" {
return errors.New("license is missing")
}
if !re.MatchString(payload.License) {
return errors.New("license is invalid")
}
return nil
}
// @id systemUpgrade
// @summary Upgrade Portainer to BE
// @description Upgrade Portainer to BE
// @description **Access policy**: administrator
// @tags system
// @produce json
// @success 204 {object} status "Success"
// @router /system/upgrade [post]
func (handler *Handler) systemUpgrade(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
payload, err := request.GetPayload[systemUpgradePayload](r)
if err != nil {
return httperror.BadRequest("Invalid request payload", err)
}
environment, err := handler.platformService.GetLocalEnvironment()
if err != nil {
if errors.Is(err, ceplf.ErrNoLocalEnvironment) {
return httperror.NotFound("The system upgrade feature is disabled because no local environment was detected.", err)
}
return httperror.InternalServerError("Failed to get local environment", err)
}
platform, err := handler.platformService.GetPlatform()
if err != nil {
return httperror.InternalServerError("Failed to get platform", err)
}
if err := handler.upgradeService.Upgrade(platform, environment, payload.License); err != nil {
return httperror.InternalServerError("Failed to upgrade Portainer", err)
}
return response.Empty(w)
}
+113
View File
@@ -0,0 +1,113 @@
package system
import (
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/http/client"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/pkg/build"
libclient "github.com/portainer/portainer/pkg/libhttp/client"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/Masterminds/semver/v3"
"github.com/rs/zerolog/log"
"github.com/segmentio/encoding/json"
)
type versionResponse struct {
// Whether portainer has an update available
UpdateAvailable bool `json:"UpdateAvailable" example:"false"`
// The latest version available
LatestVersion string `json:"LatestVersion" example:"2.0.0"`
ServerVersion string
VersionSupport string `json:"VersionSupport" example:"STS/LTS"`
ServerEdition string `json:"ServerEdition" example:"CE/EE"`
DatabaseVersion string
Build build.BuildInfo
Dependencies build.DependenciesInfo
Runtime build.RuntimeInfo
}
// @id systemVersion
// @summary Check for portainer updates
// @description Check if portainer has an update available
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags system
// @produce json
// @success 200 {object} versionResponse "Success"
// @router /system/version [get]
func (handler *Handler) version(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
isAdmin, err := security.IsAdmin(r)
if err != nil {
return httperror.Forbidden("Permission denied to access Portainer", err)
}
result := &versionResponse{
ServerVersion: portainer.APIVersion,
VersionSupport: portainer.APIVersionSupport,
DatabaseVersion: portainer.APIVersion,
ServerEdition: portainer.Edition.GetEditionLabel(),
Build: build.GetBuildInfo(),
Dependencies: build.GetDependenciesInfo(),
}
if isAdmin {
result.Runtime = build.GetRuntimeInfo()
}
latestVersion := GetLatestVersion()
if HasNewerVersion(portainer.APIVersion, latestVersion) {
result.UpdateAvailable = true
result.LatestVersion = latestVersion
}
return response.JSON(w, &result)
}
func GetLatestVersion() string {
if err := libclient.ExternalRequestDisabled(portainer.VersionCheckURL); err != nil {
log.Debug().Err(err).Msg("External request disabled: Version check")
return ""
}
motd, err := client.Get(portainer.VersionCheckURL, 5)
if err != nil {
log.Debug().Err(err).Msg("couldn't fetch latest Portainer release version")
return ""
}
var data struct {
TagName string `json:"tag_name"`
}
if err := json.Unmarshal(motd, &data); err != nil {
log.Debug().Err(err).Msg("couldn't parse latest Portainer version")
return ""
}
return data.TagName
}
func HasNewerVersion(currentVersion, latestVersion string) bool {
currentVersionSemver, err := semver.NewVersion(currentVersion)
if err != nil {
log.Debug().Str("version", currentVersion).Msg("current Portainer version isn't a semver")
return false
}
latestVersionSemver, err := semver.NewVersion(latestVersion)
if err != nil {
log.Debug().Str("version", latestVersion).Msg("latest Portainer version isn't a semver")
return false
}
return currentVersionSemver.LessThan(latestVersionSemver)
}
+68
View File
@@ -0,0 +1,68 @@
package system
import (
"io"
"net/http"
"net/http/httptest"
"testing"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/apikey"
"github.com/portainer/portainer/api/database/models"
"github.com/portainer/portainer/api/datastore"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/api/internal/testhelpers"
"github.com/portainer/portainer/api/jwt"
"github.com/segmentio/encoding/json"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_getSystemVersion(t *testing.T) {
t.Parallel()
is := assert.New(t)
_, store := datastore.MustNewTestStore(t, true, true)
// create version data
version := &models.Version{SchemaVersion: "2.20.0", Edition: 1}
err := store.Version().UpdateVersion(version)
require.NoError(t, err, "error creating version data")
// create admin and standard user(s)
adminUser := &portainer.User{ID: 1, Username: "admin", Role: portainer.AdministratorRole}
err = store.User().Create(adminUser)
require.NoError(t, err, "error creating admin user")
// setup services
jwtService, err := jwt.NewService("1h", store)
require.NoError(t, err, "Error initiating jwt service")
apiKeyService := apikey.NewAPIKeyService(store.APIKeyRepository(), store.User())
requestBouncer := security.NewRequestBouncer(t.Context(), store, jwtService, apiKeyService)
h := NewHandler(requestBouncer, &portainer.Status{}, store, nil, nil)
// generate standard and admin user tokens
jwt, _, _ := jwtService.GenerateToken(&portainer.TokenData{ID: adminUser.ID, Username: adminUser.Username, Role: adminUser.Role})
t.Run("Display Edition", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/system/version", nil)
testhelpers.AddTestSecurityCookie(req, jwt)
rr := httptest.NewRecorder()
h.ServeHTTP(rr, req)
is.Equal(http.StatusOK, rr.Code)
body, err := io.ReadAll(rr.Body)
require.NoError(t, err, "ReadAll should not return error")
var resp versionResponse
err = json.Unmarshal(body, &resp)
require.NoError(t, err, "response should be list json")
is.Equal("CE", resp.ServerEdition, "Edition is not expected")
})
}