Skip to content

Commit

Permalink
Merge pull request #12451 from markylaing/request-parsing
Browse files Browse the repository at this point in the history
Refactors `projectParam` for use outside of `lxd` directory
  • Loading branch information
tomponline authored Oct 24, 2023
2 parents bab0a18 + d9eebaa commit 7d8f0b3
Show file tree
Hide file tree
Showing 83 changed files with 422 additions and 412 deletions.
32 changes: 0 additions & 32 deletions lxd/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/canonical/lxd/lxd/cluster/request"
"github.com/canonical/lxd/lxd/db"
"github.com/canonical/lxd/lxd/instance"
"github.com/canonical/lxd/lxd/project"
lxdRequest "github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
storagePools "github.com/canonical/lxd/lxd/storage"
Expand Down Expand Up @@ -410,37 +409,6 @@ func isClusterNotification(r *http.Request) bool {
return r.Header.Get("User-Agent") == request.UserAgentNotifier
}

// projectParam returns the project query parameter from the given request or "default" if parameter is not set.
func projectParam(request *http.Request) string {
projectParam := queryParam(request, "project")
if projectParam == "" {
projectParam = project.Default
}

return projectParam
}

// Extract the given query parameter directly from the URL, never from an
// encoded body.
func queryParam(request *http.Request, key string) string {
var values url.Values
var err error

if request.URL != nil {
values, err = url.ParseQuery(request.URL.RawQuery)
if err != nil {
logger.Warnf("Failed to parse query string %q: %v", request.URL.RawQuery, err)
return ""
}
}

if values == nil {
values = make(url.Values)
}

return values.Get(key)
}

type uiHttpDir struct {
http.FileSystem
}
Expand Down
5 changes: 2 additions & 3 deletions lxd/api_1.0.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
instanceDrivers "github.com/canonical/lxd/lxd/instance/drivers"
"github.com/canonical/lxd/lxd/lifecycle"
"github.com/canonical/lxd/lxd/node"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/lxd/revert"
Expand Down Expand Up @@ -291,7 +290,7 @@ func api10Get(d *Daemon, r *http.Request) response.Response {

projectName := r.FormValue("project")
if projectName == "" {
projectName = project.Default
projectName = api.ProjectDefaultName
}

env := api.ServerEnvironment{
Expand Down Expand Up @@ -794,7 +793,7 @@ func doApi10Update(d *Daemon, r *http.Request, req api.ServerPut, patch bool) re

revert.Success()

s.Events.SendLifecycle(project.Default, lifecycle.ConfigUpdated.Event(request.CreateRequestor(r), nil))
s.Events.SendLifecycle(api.ProjectDefaultName, lifecycle.ConfigUpdated.Event(request.CreateRequestor(r), nil))

return response.EmptySyncResponse
}
Expand Down
35 changes: 17 additions & 18 deletions lxd/api_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"github.com/canonical/lxd/lxd/lifecycle"
"github.com/canonical/lxd/lxd/node"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/lxd/revert"
Expand Down Expand Up @@ -381,7 +380,7 @@ func clusterPutBootstrap(d *Daemon, r *http.Request, req api.ClusterPut) respons
return err
}

s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterEnabled.Event(req.ServerName, op.Requestor(), nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterEnabled.Event(req.ServerName, op.Requestor(), nil))

return nil
}
Expand Down Expand Up @@ -816,7 +815,7 @@ func clusterPutJoin(d *Daemon, r *http.Request, req api.ClusterPut) response.Res
// Update the cert cache again to add client and metric certs to the cache.
s.UpdateCertificateCache()

s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterMemberAdded.Event(req.ServerName, op.Requestor(), nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberAdded.Event(req.ServerName, op.Requestor(), nil))

revert.Success()
return nil
Expand Down Expand Up @@ -875,7 +874,7 @@ func clusterPutDisable(d *Daemon, r *http.Request, req api.ClusterPut) response.
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterDisabled.Event(req.ServerName, requestor, nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterDisabled.Event(req.ServerName, requestor, nil))

// Stop database cluster connection.
d.gateway.Kill()
Expand Down Expand Up @@ -977,7 +976,7 @@ func clusterInitMember(d lxd.InstanceServer, client lxd.InstanceServer, memberCo
}

for _, p := range projects {
if shared.IsFalseOrEmpty(p.Config["features.networks"]) && p.Name != project.Default {
if shared.IsFalseOrEmpty(p.Config["features.networks"]) && p.Name != api.ProjectDefaultName {
// Skip non-default projects that can't have their own networks so we don't try
// and add the same default project networks twice.
continue
Expand Down Expand Up @@ -1016,7 +1015,7 @@ func clusterInitMember(d lxd.InstanceServer, client lxd.InstanceServer, memberCo

// Apply the node-specific config supplied by the user for networks in the default project.
// At this time project specific networks don't have node specific config options.
if p.Name == project.Default {
if p.Name == api.ProjectDefaultName {
for _, config := range memberConfig {
if config.Entity != "network" {
continue
Expand Down Expand Up @@ -1339,7 +1338,7 @@ func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
// Remove any existing join tokens for the requested cluster member, this way we only ever have one active
// join token for each potential new member, and it has the most recent active members list for joining.
// This also ensures any historically unused (but potentially published) join tokens are removed.
ops, err := operationsGetByType(s, r, project.Default, operationtype.ClusterJoinToken)
ops, err := operationsGetByType(s, r, api.ProjectDefaultName, operationtype.ClusterJoinToken)
if err != nil {
return response.InternalError(fmt.Errorf("Failed getting cluster join token operations: %w", err))
}
Expand All @@ -1357,7 +1356,7 @@ func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
if opServerName == req.ServerName {
// Join token operation matches requested server name, so lets cancel it.
logger.Warn("Cancelling duplicate join token operation", logger.Ctx{"operation": op.ID, "serverName": opServerName})
err = operationCancel(s, r, project.Default, op)
err = operationCancel(s, r, api.ProjectDefaultName, op)
if err != nil {
return response.InternalError(fmt.Errorf("Failed to cancel operation %q: %w", op.ID, err))
}
Expand Down Expand Up @@ -1390,12 +1389,12 @@ func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
resources := map[string][]api.URL{}
resources["cluster"] = []api.URL{}

op, err := operations.OperationCreate(s, project.Default, operations.OperationClassToken, operationtype.ClusterJoinToken, resources, meta, nil, nil, nil, r)
op, err := operations.OperationCreate(s, api.ProjectDefaultName, operations.OperationClassToken, operationtype.ClusterJoinToken, resources, meta, nil, nil, nil, r)
if err != nil {
return response.InternalError(err)
}

s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterTokenCreated.Event("members", op.Requestor(), nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterTokenCreated.Event("members", op.Requestor(), nil))

return operations.OperationResponse(op)
}
Expand Down Expand Up @@ -1741,7 +1740,7 @@ func updateClusterNode(s *state.State, gateway *cluster.Gateway, r *http.Request
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterMemberUpdated.Event(name, requestor, nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberUpdated.Event(name, requestor, nil))

return response.EmptySyncResponse
}
Expand Down Expand Up @@ -1876,7 +1875,7 @@ func clusterNodePost(d *Daemon, r *http.Request) response.Response {
d.globalConfigMu.Unlock()

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterMemberRenamed.Event(req.ServerName, requestor, logger.Ctx{"old_name": memberName}))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberRenamed.Event(req.ServerName, requestor, logger.Ctx{"old_name": memberName}))

return response.EmptySyncResponse
}
Expand Down Expand Up @@ -2134,7 +2133,7 @@ func clusterNodeDelete(d *Daemon, r *http.Request) response.Response {
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterMemberRemoved.Event(name, requestor, nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterMemberRemoved.Event(name, requestor, nil))

return response.EmptySyncResponse
}
Expand Down Expand Up @@ -2197,7 +2196,7 @@ func clusterCertificatePut(d *Daemon, r *http.Request) response.Response {
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectParam(r), lifecycle.ClusterCertificateUpdated.Event("certificate", requestor, nil))
s.Events.SendLifecycle(request.ProjectParam(r), lifecycle.ClusterCertificateUpdated.Event("certificate", requestor, nil))

return response.EmptySyncResponse
}
Expand Down Expand Up @@ -3630,7 +3629,7 @@ func clusterGroupsPost(d *Daemon, r *http.Request) response.Response {

requestor := request.CreateRequestor(r)
lc := lifecycle.ClusterGroupCreated.Event(req.Name, requestor, nil)
s.Events.SendLifecycle(project.Default, lc)
s.Events.SendLifecycle(api.ProjectDefaultName, lc)

return response.SyncResponseLocation(true, nil, lc.Source)
}
Expand Down Expand Up @@ -3939,7 +3938,7 @@ func clusterGroupPost(d *Daemon, r *http.Request) response.Response {

requestor := request.CreateRequestor(r)
lc := lifecycle.ClusterGroupRenamed.Event(req.Name, requestor, logger.Ctx{"old_name": name})
s.Events.SendLifecycle(project.Default, lc)
s.Events.SendLifecycle(api.ProjectDefaultName, lc)

return response.SyncResponseLocation(true, nil, lc.Source)
}
Expand Down Expand Up @@ -4064,7 +4063,7 @@ func clusterGroupPut(d *Daemon, r *http.Request) response.Response {
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(project.Default, lifecycle.ClusterGroupUpdated.Event(name, requestor, logger.Ctx{"description": req.Description, "members": req.Members}))
s.Events.SendLifecycle(api.ProjectDefaultName, lifecycle.ClusterGroupUpdated.Event(name, requestor, logger.Ctx{"description": req.Description, "members": req.Members}))

return response.EmptySyncResponse
}
Expand Down Expand Up @@ -4243,7 +4242,7 @@ func clusterGroupPatch(d *Daemon, r *http.Request) response.Response {
}

requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(project.Default, lifecycle.ClusterGroupUpdated.Event(name, requestor, logger.Ctx{"description": req.Description, "members": req.Members}))
s.Events.SendLifecycle(api.ProjectDefaultName, lifecycle.ClusterGroupUpdated.Event(name, requestor, logger.Ctx{"description": req.Description, "members": req.Members}))

return response.EmptySyncResponse
}
Expand Down
11 changes: 6 additions & 5 deletions lxd/api_internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/canonical/lxd/lxd/instance"
"github.com/canonical/lxd/lxd/instance/instancetype"
"github.com/canonical/lxd/lxd/project"
"github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/lxd/revert"
"github.com/canonical/lxd/lxd/state"
Expand Down Expand Up @@ -232,7 +233,7 @@ func internalWaitReady(d *Daemon, r *http.Request) response.Response {
}

func internalShutdown(d *Daemon, r *http.Request) response.Response {
force := queryParam(r, "force")
force := request.QueryParam(r, "force")
logger.Info("Asked to shutdown by API", logger.Ctx{"force": force})

if d.State().ShutdownCtx.Err() != nil {
Expand Down Expand Up @@ -284,7 +285,7 @@ func internalContainerHookLoadFromReference(s *state.State, r *http.Request) (in
return nil, err
}

projectName := projectParam(r)
projectName := request.ProjectParam(r)

instanceID, err := strconv.Atoi(instanceRef)
if err == nil {
Expand Down Expand Up @@ -344,12 +345,12 @@ func internalContainerOnStopNS(d *Daemon, r *http.Request) response.Response {
return response.SmartError(err)
}

target := queryParam(r, "target")
target := request.QueryParam(r, "target")
if target == "" {
target = "unknown"
}

netns := queryParam(r, "netns")
netns := request.QueryParam(r, "netns")

args := map[string]string{
"target": target,
Expand All @@ -374,7 +375,7 @@ func internalContainerOnStop(d *Daemon, r *http.Request) response.Response {
return response.SmartError(err)
}

target := queryParam(r, "target")
target := request.QueryParam(r, "target")
if target == "" {
target = "unknown"
}
Expand Down
3 changes: 2 additions & 1 deletion lxd/api_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
instanceDrivers "github.com/canonical/lxd/lxd/instance/drivers"
"github.com/canonical/lxd/lxd/locking"
"github.com/canonical/lxd/lxd/metrics"
"github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
Expand Down Expand Up @@ -82,7 +83,7 @@ func allowMetrics(d *Daemon, r *http.Request) response.Response {
func metricsGet(d *Daemon, r *http.Request) response.Response {
s := d.State()

projectName := queryParam(r, "project")
projectName := request.QueryParam(r, "project")
compress := strings.Contains(r.Header.Get("Accept-Encoding"), "gzip")

// Forward if requested.
Expand Down
12 changes: 6 additions & 6 deletions lxd/api_project.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ func projectCreateDefaultProfile(tx *db.ClusterTx, project string) error {
// Create a default profile
profile := cluster.Profile{}
profile.Project = project
profile.Name = projecthelpers.Default
profile.Name = api.ProjectDefaultName
profile.Description = fmt.Sprintf("Default LXD profile for project %s", project)

_, err := cluster.CreateProfile(context.TODO(), tx.Tx(), profile)
Expand Down Expand Up @@ -678,7 +678,7 @@ func projectChange(s *state.State, project *api.Project, req api.ProjectPut) res

// Quick checks.
if len(featuresChanged) > 0 {
if project.Name == projecthelpers.Default {
if project.Name == api.ProjectDefaultName {
return response.BadRequest(fmt.Errorf("You can't change the features of the default project"))
}

Expand Down Expand Up @@ -729,7 +729,7 @@ func projectChange(s *state.State, project *api.Project, req api.ProjectPut) res
}
} else {
// Delete the project-specific default profile.
err = cluster.DeleteProfile(ctx, tx.Tx(), project.Name, projecthelpers.Default)
err = cluster.DeleteProfile(ctx, tx.Tx(), project.Name, api.ProjectDefaultName)
if err != nil {
return fmt.Errorf("Delete project default profile: %w", err)
}
Expand Down Expand Up @@ -797,7 +797,7 @@ func projectPost(d *Daemon, r *http.Request) response.Response {
}

// Quick checks.
if name == projecthelpers.Default {
if name == api.ProjectDefaultName {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be renamed"))
}

Expand Down Expand Up @@ -890,7 +890,7 @@ func projectDelete(d *Daemon, r *http.Request) response.Response {
}

// Quick checks.
if name == projecthelpers.Default {
if name == api.ProjectDefaultName {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be deleted"))
}

Expand Down Expand Up @@ -1513,7 +1513,7 @@ func projectValidateRestrictedSubnets(s *state.State, value string) error {
}

// Check uplink exists and load config to compare subnets.
_, uplink, _, err := s.DB.Cluster.GetNetworkInAnyState(projecthelpers.Default, uplinkName)
_, uplink, _, err := s.DB.Cluster.GetNetworkInAnyState(api.ProjectDefaultName, uplinkName)
if err != nil {
return fmt.Errorf("Invalid uplink network %q: %w", uplinkName, err)
}
Expand Down
Loading

0 comments on commit 7d8f0b3

Please sign in to comment.