incusd: Don't needlessly use format string functions

Signed-off-by: Nathan Chase <ntc477@utexas.edu>
This commit is contained in:
Nathan Chase 2025-05-23 01:36:09 -04:00 committed by Stéphane Graber
parent 35fe3e4589
commit bf0b67dda2
No known key found for this signature in database
GPG Key ID: C638974D64792D67
259 changed files with 1490 additions and 1382 deletions

View File

@ -617,7 +617,7 @@ func doApi10Update(d *Daemon, r *http.Request, req api.ServerPut, patch bool) re
}
if curConfig["cluster.https_address"] != newClusterHTTPSAddress {
return fmt.Errorf("Changing cluster.https_address is currently not supported")
return errors.New("Changing cluster.https_address is currently not supported")
}
}

View File

@ -270,11 +270,11 @@ func clusterPut(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.ServerName == "" && req.Enabled {
return response.BadRequest(fmt.Errorf("ServerName is required when enabling clustering"))
return response.BadRequest(errors.New("ServerName is required when enabling clustering"))
}
if req.ServerName != "" && !req.Enabled {
return response.BadRequest(fmt.Errorf("ServerName must be empty when disabling clustering"))
return response.BadRequest(errors.New("ServerName must be empty when disabling clustering"))
}
if req.ServerName != "" && strings.HasPrefix(req.ServerName, targetGroupPrefix) {
@ -393,16 +393,16 @@ func clusterPutJoin(d *Daemon, r *http.Request, req api.ClusterPut) response.Res
// Make sure basic pre-conditions are met.
if len(req.ClusterCertificate) == 0 {
return response.BadRequest(fmt.Errorf("No target cluster member certificate provided"))
return response.BadRequest(errors.New("No target cluster member certificate provided"))
}
if s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is already clustered"))
return response.BadRequest(errors.New("This server is already clustered"))
}
// Validate server address.
if req.ServerAddress == "" {
return response.BadRequest(fmt.Errorf("No server address provided for this member"))
return response.BadRequest(errors.New("No server address provided for this member"))
}
// Check that the provided address is an IP address or DNS, not wildcard and isn't required to specify a port.
@ -890,7 +890,7 @@ func clusterPutDisable(d *Daemon, r *http.Request, req api.ClusterPut) response.
if ok {
f.Flush()
} else {
return fmt.Errorf("http.ResponseWriter is not type http.Flusher")
return errors.New("http.ResponseWriter is not type http.Flusher")
}
return nil
@ -1277,7 +1277,7 @@ func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
expiry, err := internalInstance.GetExpiry(time.Now(), s.GlobalConfig.ClusterJoinTokenExpiry())
@ -1319,7 +1319,7 @@ func clusterNodesPost(d *Daemon, r *http.Request) response.Response {
}
if len(onlineNodeAddresses) < 1 {
return response.InternalError(fmt.Errorf("There are no online cluster members"))
return response.InternalError(errors.New("There are no online cluster members"))
}
// Lock to prevent concurrent requests racing the operationsGetByType function and creating duplicates.
@ -1654,7 +1654,7 @@ func updateClusterNode(s *state.State, gateway *cluster.Gateway, r *http.Request
// Nodes must belong to at least one group.
if len(req.Groups) == 0 {
return response.BadRequest(fmt.Errorf("Cluster members need to belong to at least one group"))
return response.BadRequest(errors.New("Cluster members need to belong to at least one group"))
}
// Convert the roles.
@ -1993,7 +1993,7 @@ func clusterNodeDelete(d *Daemon, r *http.Request) response.Response {
if ok {
f.Flush()
} else {
return fmt.Errorf("http.ResponseWriter is not type http.Flusher")
return errors.New("http.ResponseWriter is not type http.Flusher")
}
return nil
@ -2157,7 +2157,7 @@ func internalClusterPostAccept(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
// Redirect all requests to the leader, which is the one
@ -2173,7 +2173,7 @@ func internalClusterPostAccept(d *Daemon, r *http.Request) response.Response {
logger.Debugf("Redirect member accept request to %s", leader)
if leader == "" {
return response.SmartError(fmt.Errorf("Unable to find leader address"))
return response.SmartError(errors.New("Unable to find leader address"))
}
url := &url.URL{
@ -2416,7 +2416,7 @@ findLeader:
}
if leader == "" {
return fmt.Errorf("No leader address found")
return errors.New("No leader address found")
}
if leader == localClusterAddress {
@ -2456,7 +2456,7 @@ func internalClusterPostAssign(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if len(req.RaftNodes) == 0 {
return response.BadRequest(fmt.Errorf("No raft members provided"))
return response.BadRequest(errors.New("No raft members provided"))
}
nodes := make([]db.RaftNode, len(req.RaftNodes))
@ -2493,7 +2493,7 @@ func internalClusterPostHandover(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Address == "" {
return response.BadRequest(fmt.Errorf("No id provided"))
return response.BadRequest(errors.New("No id provided"))
}
// Redirect all requests to the leader, which is the one with
@ -2506,7 +2506,7 @@ func internalClusterPostHandover(d *Daemon, r *http.Request) response.Response {
}
if leader == "" {
return response.SmartError(fmt.Errorf("No leader address found"))
return response.SmartError(errors.New("No leader address found"))
}
if localClusterAddress != leader {

View File

@ -62,18 +62,18 @@ func evacuateClusterSetState(s *state.State, name string, newState int) error {
}
if node.State == db.ClusterMemberStatePending {
return fmt.Errorf("Cannot evacuate or restore a pending cluster member")
return errors.New("Cannot evacuate or restore a pending cluster member")
}
// Do nothing if the node is already in expected state.
if node.State == newState {
if newState == db.ClusterMemberStateEvacuated {
return fmt.Errorf("Cluster member is already evacuated")
return errors.New("Cluster member is already evacuated")
} else if newState == db.ClusterMemberStateCreated {
return fmt.Errorf("Cluster member is already restored")
return errors.New("Cluster member is already restored")
}
return fmt.Errorf("Cluster member is already in requested state")
return errors.New("Cluster member is already in requested state")
}
// Set node status to requested value.
@ -161,7 +161,7 @@ func evacuateClusterMember(ctx context.Context, s *state.State, op *operations.O
func evacuateInstances(ctx context.Context, opts evacuateOpts) error {
if opts.migrateInstance == nil {
return fmt.Errorf("Missing migration callback function")
return errors.New("Missing migration callback function")
}
// Limit the number of concurrent evacuations to run at the same time
@ -619,7 +619,7 @@ func evacuateClusterSelectTarget(ctx context.Context, s *state.State, inst insta
}
if targetMemberInfo == nil {
return nil, nil, fmt.Errorf("Couldn't find a cluster member for the instance")
return nil, nil, errors.New("Couldn't find a cluster member for the instance")
}
return sourceMemberInfo, targetMemberInfo, nil

View File

@ -77,7 +77,7 @@ func clusterGroupsPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
req := api.ClusterGroupsPost{}
@ -226,7 +226,7 @@ func clusterGroupsGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
recursion := localUtil.IsRecursionRequest(r)
@ -321,7 +321,7 @@ func clusterGroupGet(d *Daemon, r *http.Request) response.Response {
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
var apiGroup *api.ClusterGroup
@ -396,7 +396,7 @@ func clusterGroupPost(d *Daemon, r *http.Request) response.Response {
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
req := api.ClusterGroupPost{}
@ -475,7 +475,7 @@ func clusterGroupPut(d *Daemon, r *http.Request) response.Response {
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
req := api.ClusterGroupPut{}
@ -637,7 +637,7 @@ func clusterGroupPatch(d *Daemon, r *http.Request) response.Response {
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("This server is not clustered"))
return response.BadRequest(errors.New("This server is not clustered"))
}
var clusterGroup *api.ClusterGroup
@ -829,7 +829,7 @@ func clusterGroupDelete(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if name == "default" {
return response.Forbidden(fmt.Errorf("The 'default' cluster group cannot be deleted"))
return response.Forbidden(errors.New("The 'default' cluster group cannot be deleted"))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -839,7 +839,7 @@ func clusterGroupDelete(d *Daemon, r *http.Request) response.Response {
}
if len(members) > 0 {
return fmt.Errorf("Only empty cluster groups can be removed")
return errors.New("Only empty cluster groups can be removed")
}
return dbCluster.DeleteClusterGroup(ctx, tx.Tx(), name)
@ -856,27 +856,27 @@ func clusterGroupDelete(d *Daemon, r *http.Request) response.Response {
func clusterGroupValidateName(name string) error {
if name == "" {
return fmt.Errorf("No name provided")
return errors.New("No name provided")
}
if strings.Contains(name, "/") {
return fmt.Errorf("Cluster group names may not contain slashes")
return errors.New("Cluster group names may not contain slashes")
}
if strings.Contains(name, " ") {
return fmt.Errorf("Cluster group names may not contain spaces")
return errors.New("Cluster group names may not contain spaces")
}
if strings.Contains(name, "_") {
return fmt.Errorf("Cluster group names may not contain underscores")
return errors.New("Cluster group names may not contain underscores")
}
if strings.Contains(name, "'") || strings.Contains(name, `"`) {
return fmt.Errorf("Cluster group names may not contain quotes")
return errors.New("Cluster group names may not contain quotes")
}
if name == "*" {
return fmt.Errorf("Reserved cluster group name")
return errors.New("Reserved cluster group name")
}
if slices.Contains([]string{".", ".."}, name) {
@ -955,11 +955,11 @@ func clusterGroupFill(ctx context.Context, s *state.State, servers []string, req
}
if baseline != "kvm64" || arch != "x86_64" {
return fmt.Errorf("Automatic CPU flags are currently only supported on \"x86_64\" with the \"kvm64\" baseline")
return errors.New("Automatic CPU flags are currently only supported on \"x86_64\" with the \"kvm64\" baseline")
}
if len(servers) == 0 {
return fmt.Errorf("Can't compute automatic CPU flags when no servers are in the cluster group")
return errors.New("Can't compute automatic CPU flags when no servers are in the cluster group")
}
// Fill in the flags.

View File

@ -5,6 +5,7 @@ import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -232,7 +233,7 @@ func internalCreateWarning(d *Daemon, r *http.Request) response.Response {
// Check if the entity exists, and fail if it doesn't.
_, ok := cluster.EntityNames[req.EntityTypeCode]
if req.EntityTypeCode != -1 && !ok {
return response.SmartError(fmt.Errorf("Invalid entity type"))
return response.SmartError(errors.New("Invalid entity type"))
}
err = d.State().DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -279,11 +280,11 @@ func internalWaitReady(d *Daemon, _ *http.Request) response.Response {
// Check that we're not shutting down.
isClosing := d.State().ShutdownCtx.Err() != nil
if isClosing {
return response.Unavailable(fmt.Errorf("Daemon is shutting down"))
return response.Unavailable(errors.New("Daemon is shutting down"))
}
if d.waitReady.Err() == nil {
return response.Unavailable(fmt.Errorf("Daemon not ready yet"))
return response.Unavailable(errors.New("Daemon not ready yet"))
}
return response.EmptySyncResponse
@ -320,7 +321,7 @@ func internalShutdown(d *Daemon, r *http.Request) response.Response {
if ok {
f.Flush()
} else {
return fmt.Errorf("http.ResponseWriter is not type http.Flusher")
return errors.New("http.ResponseWriter is not type http.Flusher")
}
// Send result of d.Stop() to cmdDaemon so that process stops with correct exit code from Stop().
@ -369,7 +370,7 @@ func internalContainerHookLoadFromReference(s *state.State, r *http.Request) (in
}
if inst.Type() != instancetype.Container {
return nil, fmt.Errorf("Instance is not container type")
return nil, errors.New("Instance is not container type")
}
return inst, nil
@ -462,7 +463,7 @@ func internalVirtualMachineOnResize(d *Daemon, r *http.Request) response.Respons
// Get the devices list.
devices := request.QueryParam(r, "devices")
if devices == "" {
return response.BadRequest(fmt.Errorf("Resize hook requires a list of devices"))
return response.BadRequest(errors.New("Resize hook requires a list of devices"))
}
// Load by ID.
@ -507,7 +508,7 @@ func internalSQLGet(d *Daemon, r *http.Request) response.Response {
database := r.FormValue("database")
if !slices.Contains([]string{"local", "global"}, database) {
return response.BadRequest(fmt.Errorf("Invalid database"))
return response.BadRequest(errors.New("Invalid database"))
}
schemaFormValue := r.FormValue("schema")
@ -550,11 +551,11 @@ func internalSQLPost(d *Daemon, r *http.Request) response.Response {
}
if !slices.Contains([]string{"local", "global"}, req.Database) {
return response.BadRequest(fmt.Errorf("Invalid database"))
return response.BadRequest(errors.New("Invalid database"))
}
if req.Query == "" {
return response.BadRequest(fmt.Errorf("No query provided"))
return response.BadRequest(errors.New("No query provided"))
}
var db *sql.DB
@ -672,7 +673,7 @@ func internalSQLExec(tx *sql.Tx, query string, result *internalSQL.SQLResult) er
// It expects the instance volume to be mounted so that the backup.yaml file is readable.
func internalImportFromBackup(ctx context.Context, s *state.State, projectName string, instName string, allowNameOverride bool) error {
if instName == "" {
return fmt.Errorf("The name of the instance is required")
return errors.New("The name of the instance is required")
}
storagePoolsPath := internalUtil.VarPath("storage-pools")
@ -753,7 +754,7 @@ func internalImportFromBackup(ctx context.Context, s *state.State, projectName s
if backupConf.Pool == nil {
// We don't know what kind of storage type the pool is.
return fmt.Errorf("No storage pool struct in the backup file found. The storage pool needs to be recovered manually")
return errors.New("No storage pool struct in the backup file found. The storage pool needs to be recovered manually")
}
// Try to retrieve the storage pool the instance supposedly lives on.
@ -820,7 +821,7 @@ func internalImportFromBackup(ctx context.Context, s *state.State, projectName s
}
if backupConf.Volume == nil {
return fmt.Errorf(`No storage volume struct in the backup file found. The storage volume needs to be recovered manually`)
return errors.New(`No storage volume struct in the backup file found. The storage volume needs to be recovered manually`)
}
var profiles []api.Profile
@ -849,7 +850,7 @@ func internalImportFromBackup(ctx context.Context, s *state.State, projectName s
defer reverter.Fail()
if backupConf.Container == nil {
return fmt.Errorf("No instance config in backup config")
return errors.New("No instance config in backup config")
}
instDBArgs, err := backup.ConfigToInstanceDBArgs(s, backupConf, projectName, true)
@ -1091,7 +1092,7 @@ func internalGC(_ *Daemon, _ *http.Request) response.Response {
func internalRAFTSnapshot(_ *Daemon, _ *http.Request) response.Response {
logger.Warn("Forced RAFT snapshot not supported")
return response.InternalError(fmt.Errorf("Not supported"))
return response.InternalError(errors.New("Not supported"))
}
func internalBGPState(d *Daemon, _ *http.Request) response.Response {

View File

@ -145,7 +145,7 @@ func internalRecoverScan(ctx context.Context, s *state.State, userPools []api.St
// If the pool DB record doesn't exist, and we are clustered, then don't proceed
// any further as we do not support pool DB record recovery when clustered.
if s.ServerClustered {
return response.BadRequest(fmt.Errorf("Storage pool recovery not supported when clustered"))
return response.BadRequest(errors.New("Storage pool recovery not supported when clustered"))
}
// If pool doesn't exist in DB, initialize a temporary pool with the supplied info.
@ -401,7 +401,7 @@ func internalRecoverScan(ctx context.Context, s *state.State, userPools []api.St
if poolVol.Container != nil || poolVol.Bucket != nil {
continue // Skip instance volumes and buckets.
} else if poolVol.Container == nil && poolVol.Volume == nil {
return response.SmartError(fmt.Errorf("Volume is neither instance nor custom volume"))
return response.SmartError(errors.New("Volume is neither instance nor custom volume"))
}
// Import custom volume and any snapshots.
@ -514,7 +514,7 @@ func internalRecoverScan(ctx context.Context, s *state.State, userPools []api.St
// Returns a revert fail function that can be used to undo this function if a subsequent step fails.
func internalRecoverImportInstance(s *state.State, pool storagePools.Pool, projectName string, poolVol *backupConfig.Config, profiles []api.Profile) (instance.Instance, revert.Hook, error) {
if poolVol.Container == nil {
return nil, nil, fmt.Errorf("Pool volume is not an instance volume")
return nil, nil, errors.New("Pool volume is not an instance volume")
}
// Add root device if needed.
@ -534,7 +534,7 @@ func internalRecoverImportInstance(s *state.State, pool storagePools.Pool, proje
}
if dbInst.Type < 0 {
return nil, nil, fmt.Errorf("Invalid instance type")
return nil, nil, errors.New("Invalid instance type")
}
inst, instOp, cleanup, err := instance.CreateInternal(s, *dbInst, nil, false, true)
@ -550,7 +550,7 @@ func internalRecoverImportInstance(s *state.State, pool storagePools.Pool, proje
// internalRecoverImportInstance recreates the database records for an instance snapshot.
func internalRecoverImportInstanceSnapshot(s *state.State, pool storagePools.Pool, projectName string, poolVol *backupConfig.Config, snap *api.InstanceSnapshot, profiles []api.Profile) (revert.Hook, error) {
if poolVol.Container == nil || snap == nil {
return nil, fmt.Errorf("Pool volume is not an instance volume")
return nil, errors.New("Pool volume is not an instance volume")
}
// Add root device if needed.

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@ -727,7 +728,7 @@ func projectChange(ctx context.Context, s *state.State, project *api.Project, re
// Quick checks.
if len(featuresChanged) > 0 {
if project.Name == api.ProjectDefaultName {
return response.BadRequest(fmt.Errorf("You can't change the features of the default project"))
return response.BadRequest(errors.New("You can't change the features of the default project"))
}
// Consider the project empty if it is only used by the default profile.
@ -845,7 +846,7 @@ func projectPost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if name == api.ProjectDefaultName {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be renamed"))
return response.Forbidden(errors.New("The 'default' project cannot be renamed"))
}
// Perform the rename.
@ -872,7 +873,7 @@ func projectPost(d *Daemon, r *http.Request) response.Response {
}
if !empty {
return fmt.Errorf("Only empty projects can be renamed")
return errors.New("Only empty projects can be renamed")
}
id, err = cluster.GetProjectID(ctx, tx.Tx(), name)
@ -945,7 +946,7 @@ func projectDelete(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if name == api.ProjectDefaultName {
return response.Forbidden(fmt.Errorf("The 'default' project cannot be deleted"))
return response.Forbidden(errors.New("The 'default' project cannot be deleted"))
}
var id int64
@ -963,7 +964,7 @@ func projectDelete(d *Daemon, r *http.Request) response.Response {
}
if !empty {
return fmt.Errorf("Only empty projects can be removed.")
return errors.New("Only empty projects can be removed.")
}
} else {
usedBy, err = projectUsedBy(ctx, tx, project)
@ -1225,7 +1226,7 @@ func projectDelete(d *Daemon, r *http.Request) response.Response {
// Check if anything is left.
if count != 0 {
return response.BadRequest(fmt.Errorf("Project couldn't be automatically emptied"))
return response.BadRequest(errors.New("Project couldn't be automatically emptied"))
}
}
@ -1831,7 +1832,7 @@ func projectValidateConfig(s *state.State, config map[string]string) error {
// be bypassed by settings from the default project's profiles that are not checked against this project's
// restrictions when they are configured.
if util.IsTrue(config["restricted"]) && util.IsFalse(config["features.profiles"]) {
return fmt.Errorf("Projects without their own profiles cannot be restricted")
return errors.New("Projects without their own profiles cannot be restricted")
}
return nil
@ -1839,27 +1840,27 @@ func projectValidateConfig(s *state.State, config map[string]string) error {
func projectValidateName(name string) error {
if name == "" {
return fmt.Errorf("No name provided")
return errors.New("No name provided")
}
if strings.Contains(name, "/") {
return fmt.Errorf("Project names may not contain slashes")
return errors.New("Project names may not contain slashes")
}
if strings.Contains(name, " ") {
return fmt.Errorf("Project names may not contain spaces")
return errors.New("Project names may not contain spaces")
}
if strings.Contains(name, "_") {
return fmt.Errorf("Project names may not contain underscores")
return errors.New("Project names may not contain underscores")
}
if strings.Contains(name, "'") || strings.Contains(name, `"`) {
return fmt.Errorf("Project names may not contain quotes")
return errors.New("Project names may not contain quotes")
}
if name == "*" {
return fmt.Errorf("Reserved project name")
return errors.New("Reserved project name")
}
if slices.Contains([]string{".", ".."}, name) {

View File

@ -239,12 +239,12 @@ func backupWriteIndex(sourceInst instance.Instance, pool storagePools.Pool, opti
backupType := backup.InstanceTypeToBackupType(api.InstanceType(sourceInst.Type().String()))
if backupType == backup.TypeUnknown {
return fmt.Errorf("Unrecognised instance type for backup type conversion")
return errors.New("Unrecognised instance type for backup type conversion")
}
// We only write backup files out for actual instances.
if sourceInst.IsSnapshot() {
return fmt.Errorf("Cannot generate backup config for snapshots")
return errors.New("Cannot generate backup config for snapshots")
}
// Immediately return if the instance directory doesn't exist yet.

View File

@ -7,6 +7,7 @@ import (
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net"
"net/http"
@ -548,16 +549,16 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
// Quick check.
if req.Token && req.Certificate != "" {
return response.BadRequest(fmt.Errorf("Can't use certificate if token is requested"))
return response.BadRequest(errors.New("Can't use certificate if token is requested"))
}
if req.Token {
if req.Type != "client" {
return response.BadRequest(fmt.Errorf("Tokens can only be issued for client certificates"))
return response.BadRequest(errors.New("Tokens can only be issued for client certificates"))
}
if localHTTPSAddress == "" {
return response.BadRequest(fmt.Errorf("Can't issue token when server isn't listening on network"))
return response.BadRequest(errors.New("Can't issue token when server isn't listening on network"))
}
}
@ -570,7 +571,7 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
// User isn't an admin and is already trusted, can't add more certs.
if trusted && req.Certificate == "" && !req.Token {
return response.BadRequest(fmt.Errorf("Client is already trusted"))
return response.BadRequest(errors.New("Client is already trusted"))
}
// Handle requests by non-admin users.
@ -603,7 +604,7 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
}
if joinOp == nil {
return response.Forbidden(fmt.Errorf("No matching cluster join operation found"))
return response.Forbidden(errors.New("No matching cluster join operation found"))
}
} else {
// Check if certificate add token supplied as token.
@ -616,7 +617,7 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
}
if joinOp == nil {
return response.Forbidden(fmt.Errorf("No matching certificate add operation found"))
return response.Forbidden(errors.New("No matching certificate add operation found"))
}
// Create a new request from the token data as the user isn't allowed to override anything.
@ -636,7 +637,7 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
}
default:
return response.InternalError(fmt.Errorf("Bad certificate add operation data"))
return response.InternalError(errors.New("Bad certificate add operation data"))
}
} else {
return response.Forbidden(nil)
@ -730,12 +731,12 @@ func certificatesPost(d *Daemon, r *http.Request) response.Response {
// This can happen if the client doesn't send a client certificate or if the server is in
// CA mode. We rely on this check to prevent non-CA trusted client certificates from being
// added when in CA mode.
return response.BadRequest(fmt.Errorf("No client certificate provided"))
return response.BadRequest(errors.New("No client certificate provided"))
}
cert = r.TLS.PeerCertificates[len(r.TLS.PeerCertificates)-1]
} else {
return response.BadRequest(fmt.Errorf("Can't use TLS data on non-TLS link"))
return response.BadRequest(errors.New("Can't use TLS data on non-TLS link"))
}
// Check validity.
@ -1052,17 +1053,17 @@ func doCertificateUpdate(d *Daemon, dbInfo api.Certificate, req api.CertificateP
certProjects := req.Projects
if !userCanEditCertificate {
if r.TLS == nil {
response.Forbidden(fmt.Errorf("Cannot update certificate information"))
response.Forbidden(errors.New("Cannot update certificate information"))
}
// Ensure the user in not trying to change fields other than the certificate.
if dbInfo.Restricted != req.Restricted || dbInfo.Name != req.Name || len(dbInfo.Projects) != len(req.Projects) {
return response.Forbidden(fmt.Errorf("Only the certificate can be changed"))
return response.Forbidden(errors.New("Only the certificate can be changed"))
}
for i := range dbInfo.Projects {
if dbInfo.Projects[i] != req.Projects[i] {
return response.Forbidden(fmt.Errorf("Only the certificate can be changed"))
return response.Forbidden(errors.New("Only the certificate can be changed"))
}
}
@ -1101,7 +1102,7 @@ func doCertificateUpdate(d *Daemon, dbInfo api.Certificate, req api.CertificateP
}
if !trusted {
return response.Forbidden(fmt.Errorf("Certificate cannot be changed"))
return response.Forbidden(errors.New("Certificate cannot be changed"))
}
}
}
@ -1110,7 +1111,7 @@ func doCertificateUpdate(d *Daemon, dbInfo api.Certificate, req api.CertificateP
// Add supplied certificate.
block, _ := pem.Decode([]byte(req.Certificate))
if block == nil {
return response.BadRequest(fmt.Errorf("Invalid PEM encoded certificate"))
return response.BadRequest(errors.New("Invalid PEM encoded certificate"))
}
cert, err := x509.ParseCertificate(block.Bytes)
@ -1209,7 +1210,7 @@ func certificateDelete(d *Daemon, r *http.Request) response.Response {
// Non-admins are able to delete only their own certificate.
if !userCanEditCertificate {
if r.TLS == nil {
response.Forbidden(fmt.Errorf("Cannot delete certificate"))
response.Forbidden(errors.New("Cannot delete certificate"))
}
certBlock, _ := pem.Decode([]byte(certInfo.Certificate))
@ -1234,7 +1235,7 @@ func certificateDelete(d *Daemon, r *http.Request) response.Response {
}
if !trusted {
return response.Forbidden(fmt.Errorf("Certificate cannot be deleted"))
return response.Forbidden(errors.New("Certificate cannot be deleted"))
}
}
@ -1276,22 +1277,22 @@ func certificateDelete(d *Daemon, r *http.Request) response.Response {
func certificateValidate(cert *x509.Certificate) error {
if time.Now().Before(cert.NotBefore) {
return fmt.Errorf("The provided certificate isn't valid yet")
return errors.New("The provided certificate isn't valid yet")
}
if time.Now().After(cert.NotAfter) {
return fmt.Errorf("The provided certificate is expired")
return errors.New("The provided certificate is expired")
}
if cert.PublicKeyAlgorithm == x509.RSA {
pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return fmt.Errorf("Unable to validate the RSA certificate")
return errors.New("Unable to validate the RSA certificate")
}
// Check that we're dealing with at least 2048bit (Size returns a value in bytes).
if pubKey.Size()*8 < 2048 {
return fmt.Errorf("RSA key is too weak (minimum of 2048bit)")
return errors.New("RSA key is too weak (minimum of 2048bit)")
}
}

View File

@ -421,7 +421,7 @@ func (d *Daemon) checkTrustedClient(r *http.Request) error {
return err
}
return fmt.Errorf("Not authorized")
return errors.New("Not authorized")
}
return nil
@ -511,22 +511,22 @@ func (d *Daemon) Authenticate(w http.ResponseWriter, r *http.Request) (bool, str
// DevIncus unix socket credentials on main API.
if r.RemoteAddr == "@dev_incus" {
return false, "", "", fmt.Errorf("Main API query can't come from /dev/incus socket")
return false, "", "", errors.New("Main API query can't come from /dev/incus socket")
}
// Cluster notification with wrong certificate.
if isClusterNotification(r) {
return false, "", "", fmt.Errorf("Cluster notification isn't using trusted server certificate")
return false, "", "", errors.New("Cluster notification isn't using trusted server certificate")
}
// Cluster internal client with wrong certificate.
if isClusterInternal(r) {
return false, "", "", fmt.Errorf("Cluster internal client isn't using trusted server certificate")
return false, "", "", errors.New("Cluster internal client isn't using trusted server certificate")
}
// Bad query, no TLS found.
if r.TLS == nil {
return false, "", "", fmt.Errorf("Bad/missing TLS on network query")
return false, "", "", errors.New("Bad/missing TLS on network query")
}
// Load the certificates.
@ -638,7 +638,7 @@ func (d *Daemon) createCmd(restAPI *mux.Router, version string, c APIEndpoint) {
select {
case <-d.setupChan:
default:
response := response.Unavailable(fmt.Errorf("Daemon is starting up"))
response := response.Unavailable(errors.New("Daemon is starting up"))
_ = response.Render(w)
return
}
@ -747,7 +747,7 @@ func (d *Daemon) createCmd(restAPI *mux.Router, version string, c APIEndpoint) {
}
if errors.Is(d.shutdownCtx.Err(), context.Canceled) && !allowedDuringShutdown() {
_ = response.Unavailable(fmt.Errorf("Shutting down")).Render(w)
_ = response.Unavailable(errors.New("Shutting down")).Render(w)
return
}

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@ -143,7 +144,7 @@ func daemonStorageMount(s *state.State) error {
func daemonStorageSplitVolume(volume string) (string, string, error) {
fields := strings.Split(volume, "/")
if len(fields) != 2 {
return "", "", fmt.Errorf("Invalid syntax for volume, must be <pool>/<volume>")
return "", "", errors.New("Invalid syntax for volume, must be <pool>/<volume>")
}
poolName := fields[0]
@ -195,7 +196,7 @@ func daemonStorageValidate(s *state.State, target string) error {
}
if len(snapshots) != 0 {
return fmt.Errorf("Storage volumes for use by Incus itself cannot have snapshots")
return errors.New("Storage volumes for use by Incus itself cannot have snapshots")
}
pool, err := storagePools.LoadByName(s, poolName)

View File

@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
@ -216,7 +217,7 @@ var devIncusAPIHandler = devIncusHandler{"/1.0", func(d *Daemon, c instance.Inst
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusBadRequest, err.Error()), c.Type() == instancetype.VM)
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusBadRequest, "%s", err.Error()), c.Type() == instancetype.VM)
}
state := api.StatusCodeFromString(req.State)
@ -227,7 +228,7 @@ var devIncusAPIHandler = devIncusHandler{"/1.0", func(d *Daemon, c instance.Inst
err = c.VolatileSet(map[string]string{"volatile.last_state.ready": strconv.FormatBool(state == api.Ready)})
if err != nil {
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusInternalServerError, err.Error()), c.Type() == instancetype.VM)
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusInternalServerError, "%s", err.Error()), c.Type() == instancetype.VM)
}
if state == api.Ready {
@ -237,7 +238,7 @@ var devIncusAPIHandler = devIncusHandler{"/1.0", func(d *Daemon, c instance.Inst
return response.DevIncusResponse(http.StatusOK, "", "raw", c.Type() == instancetype.VM)
}
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusMethodNotAllowed, fmt.Sprintf("method %q not allowed", r.Method)), c.Type() == instancetype.VM)
return response.DevIncusErrorResponse(api.StatusErrorf(http.StatusMethodNotAllowed, "%s", fmt.Sprintf("method %q not allowed", r.Method)), c.Type() == instancetype.VM)
}}
var devIncusDevicesGet = devIncusHandler{"/1.0/devices", func(d *Daemon, c instance.Instance, w http.ResponseWriter, r *http.Request) response.Response {
@ -277,7 +278,7 @@ func hoistReq(f func(*Daemon, instance.Instance, http.ResponseWriter, *http.Requ
conn := ucred.GetConnFromContext(r.Context())
cred, ok := pidMapper.m[conn.(*net.UnixConn)]
if !ok {
http.Error(w, pidNotInContainerErr.Error(), http.StatusInternalServerError)
http.Error(w, errPIDNotInContainer.Error(), http.StatusInternalServerError)
return
}
@ -389,7 +390,7 @@ func (m *ConnPidMapper) ConnStateHandler(conn net.Conn, state http.ConnState) {
}
}
var pidNotInContainerErr = fmt.Errorf("pid not in container?")
var errPIDNotInContainer = errors.New("pid not in container?")
func findContainerForPid(pid int32, s *state.State) (instance.Container, error) {
/*
@ -435,7 +436,7 @@ func findContainerForPid(pid int32, s *state.State) (instance.Container, error)
}
if inst.Type() != instancetype.Container {
return nil, fmt.Errorf("Instance is not container type")
return nil, errors.New("Instance is not container type")
}
return inst.(instance.Container), nil
@ -495,5 +496,5 @@ func findContainerForPid(pid int32, s *state.State) (instance.Container, error)
}
}
return nil, pidNotInContainerErr
return nil, errPIDNotInContainer
}

View File

@ -169,7 +169,7 @@ func TestHttpRequest(t *testing.T) {
t.Fatal(err)
}
if !strings.Contains(string(resp), pidNotInContainerErr.Error()) {
if !strings.Contains(string(resp), errPIDNotInContainer.Error()) {
t.Fatal("resp error not expected: ", string(resp))
}
}

View File

@ -210,26 +210,26 @@ func imgPostInstanceInfo(ctx context.Context, s *state.State, r *http.Request, r
imageType := req.Format
if ctype == "" || name == "" {
return nil, fmt.Errorf("No source provided")
return nil, errors.New("No source provided")
}
if imageType != "" && imageType != "unified" && imageType != "split" {
return nil, fmt.Errorf("Invalid image format")
return nil, errors.New("Invalid image format")
}
switch ctype {
case "snapshot":
if !internalInstance.IsSnapshot(name) {
return nil, fmt.Errorf("Not a snapshot")
return nil, errors.New("Not a snapshot")
}
case "container", "virtual-machine", "instance":
if internalInstance.IsSnapshot(name) {
return nil, fmt.Errorf("This is a snapshot")
return nil, errors.New("This is a snapshot")
}
default:
return nil, fmt.Errorf("Bad type")
return nil, errors.New("Bad type")
}
info.Filename = req.Filename
@ -529,7 +529,7 @@ func imgPostRemoteInfo(ctx context.Context, s *state.State, r *http.Request, req
} else if req.Source.Alias != "" {
hash = req.Source.Alias
} else {
return nil, fmt.Errorf("must specify one of alias or fingerprint for init from image")
return nil, errors.New("must specify one of alias or fingerprint for init from image")
}
info, _, err := ImageDownload(ctx, r, s, op, &ImageDownloadArgs{
@ -604,7 +604,7 @@ func imgPostURLInfo(ctx context.Context, s *state.State, r *http.Request, req ap
var err error
if req.Source.URL == "" {
return nil, fmt.Errorf("Missing URL")
return nil, errors.New("Missing URL")
}
myhttp, err := localUtil.HTTPClient("", s.Proxy)
@ -639,12 +639,12 @@ func imgPostURLInfo(ctx context.Context, s *state.State, r *http.Request, req ap
hash := raw.Header.Get("Incus-Image-Hash")
if hash == "" {
return nil, fmt.Errorf("Missing Incus-Image-Hash header")
return nil, errors.New("Missing Incus-Image-Hash header")
}
url := raw.Header.Get("Incus-Image-URL")
if url == "" {
return nil, fmt.Errorf("Missing Incus-Image-URL header")
return nil, errors.New("Missing Incus-Image-URL header")
}
// Import the image
@ -729,7 +729,7 @@ func getImgPostInfo(ctx context.Context, s *state.State, r *http.Request, buildd
}
if part.FormName() != "metadata" {
return nil, fmt.Errorf("Invalid multipart image")
return nil, errors.New("Invalid multipart image")
}
size, err = io.Copy(io.MultiWriter(imageTarf, hash256), part)
@ -754,7 +754,7 @@ func getImgPostInfo(ctx context.Context, s *state.State, r *http.Request, buildd
info.Type = instancetype.VM.String()
} else {
l.Error("Invalid multipart image")
return nil, fmt.Errorf("Invalid multipart image")
return nil, errors.New("Invalid multipart image")
}
// Create a temporary file for the rootfs tarball
@ -945,7 +945,7 @@ func getImgPostInfo(ctx context.Context, s *state.State, r *http.Request, buildd
return nil, err
}
} else {
return &info, fmt.Errorf("Image with same fingerprint already exists")
return &info, errors.New("Image with same fingerprint already exists")
}
} else {
public, ok := metadata["public"]
@ -971,7 +971,7 @@ func getImgPostInfo(ctx context.Context, s *state.State, r *http.Request, buildd
// database and hence has already a storage volume in at least one storage pool.
func imageCreateInPool(s *state.State, info *api.Image, storagePool string) error {
if storagePool == "" {
return fmt.Errorf("No storage pool specified")
return errors.New("No storage pool specified")
}
pool, err := storagePools.LoadByName(s, storagePool)
@ -1213,7 +1213,7 @@ func imagesPost(d *Daemon, r *http.Request) response.Response {
if !imageUpload && !slices.Contains([]string{"container", "instance", "virtual-machine", "snapshot", "image", "url"}, req.Source.Type) {
cleanup(builddir, post)
return response.InternalError(fmt.Errorf("Invalid images JSON"))
return response.InternalError(errors.New("Invalid images JSON"))
}
/* Forward requests for containers on other nodes */
@ -1401,7 +1401,7 @@ func getImageMetadata(fname string) (*api.ImageMetadata, string, error) {
}
if unpacker == nil {
return nil, "unknown", fmt.Errorf("Unsupported backup compression")
return nil, "unknown", errors.New("Unsupported backup compression")
}
// Open the tarball
@ -1476,7 +1476,7 @@ func getImageMetadata(fname string) (*api.ImageMetadata, string, error) {
}
if !hasMeta {
return nil, "unknown", fmt.Errorf("Metadata tarball is missing metadata.yaml")
return nil, "unknown", errors.New("Metadata tarball is missing metadata.yaml")
}
_, err = osarch.ArchitectureID(result.Architecture)
@ -1485,7 +1485,7 @@ func getImageMetadata(fname string) (*api.ImageMetadata, string, error) {
}
if result.CreationDate == 0 {
return nil, "unknown", fmt.Errorf("Missing creation date")
return nil, "unknown", errors.New("Missing creation date")
}
return &result, imageType, nil
@ -1792,7 +1792,7 @@ func imagesGet(d *Daemon, r *http.Request) response.Response {
// ProjectParam returns default if not set
if allProjects && projectName != api.ProjectDefaultName {
return response.BadRequest(fmt.Errorf("Cannot specify a project when requesting all projects"))
return response.BadRequest(errors.New("Cannot specify a project when requesting all projects"))
}
s := d.State()
@ -3461,7 +3461,7 @@ func imageAliasesPost(d *Daemon, r *http.Request) response.Response {
}
if req.Name == "" || req.Target == "" {
return response.BadRequest(fmt.Errorf("name and target are required"))
return response.BadRequest(errors.New("name and target are required"))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -3877,7 +3877,7 @@ func imageAliasPut(d *Daemon, r *http.Request) response.Response {
}
if req.Target == "" {
return response.BadRequest(fmt.Errorf("The target field is required"))
return response.BadRequest(errors.New("The target field is required"))
}
var imgAlias api.ImageAliasesEntry

View File

@ -2,7 +2,7 @@ package main
import (
"context"
"fmt"
"errors"
"net/http"
"net/url"
@ -64,7 +64,7 @@ func instanceAccess(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -129,7 +130,7 @@ func instanceBackupsGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(cname) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -217,7 +218,7 @@ func instanceBackupsPost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -302,7 +303,7 @@ func instanceBackupsPost(d *Daemon, r *http.Request) response.Response {
// Validate the name.
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
fullName := name + internalInstance.SnapshotDelimiter + req.Name
@ -390,7 +391,7 @@ func instanceBackupGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
backupName, err := url.PathUnescape(mux.Vars(r)["backupName"])
@ -459,7 +460,7 @@ func instanceBackupPost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
backupName, err := url.PathUnescape(mux.Vars(r)["backupName"])
@ -485,7 +486,7 @@ func instanceBackupPost(d *Daemon, r *http.Request) response.Response {
// Validate the name
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
oldName := name + internalInstance.SnapshotDelimiter + backupName
@ -553,7 +554,7 @@ func instanceBackupDelete(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
backupName, err := url.PathUnescape(mux.Vars(r)["backupName"])
@ -630,7 +631,7 @@ func instanceBackupExportGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
backupName, err := url.PathUnescape(mux.Vars(r)["backupName"])

View File

@ -97,7 +97,7 @@ func (s *consoleWs) connect(_ *operations.Operation, r *http.Request, w http.Res
func (s *consoleWs) connectConsole(r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
return errors.New("missing secret")
}
for fd, fdSecret := range s.fds {
@ -138,7 +138,7 @@ func (s *consoleWs) connectConsole(r *http.Request, w http.ResponseWriter) error
func (s *consoleWs) connectVGA(r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
return errors.New("missing secret")
}
for fd, fdSecret := range s.fds {
@ -452,7 +452,7 @@ func instanceConsolePost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
post := api.InstanceConsolePost{}
@ -502,15 +502,15 @@ func instanceConsolePost(d *Daemon, r *http.Request) response.Response {
}
if post.Type == instance.ConsoleTypeVGA && inst.Type() != instancetype.VM {
return response.BadRequest(fmt.Errorf("VGA console is only supported by virtual machines"))
return response.BadRequest(errors.New("VGA console is only supported by virtual machines"))
}
if !inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance is not running"))
return response.BadRequest(errors.New("Instance is not running"))
}
if inst.IsFrozen() {
return response.BadRequest(fmt.Errorf("Instance is frozen"))
return response.BadRequest(errors.New("Instance is frozen"))
}
// Find any running 'ConsoleShow' operation for the instance.
@ -525,12 +525,12 @@ func instanceConsolePost(d *Daemon, r *http.Request) response.Response {
r := op.Resources()
apiUrls := r["instances"]
if len(apiUrls) < 1 {
return response.SmartError(fmt.Errorf("Operation does not have an instance URL defined"))
return response.SmartError(errors.New("Operation does not have an instance URL defined"))
}
urlPrefix, instanceName := path.Split(apiUrls[0].URL.Path)
if urlPrefix == "" || instanceName == "" {
return response.SmartError(fmt.Errorf("Instance URL has incorrect format"))
return response.SmartError(errors.New("Instance URL has incorrect format"))
}
if instanceName != inst.Name() {
@ -538,7 +538,7 @@ func instanceConsolePost(d *Daemon, r *http.Request) response.Response {
}
if !post.Force {
return response.SmartError(fmt.Errorf("This console is already connected. Force is required to take it over."))
return response.SmartError(errors.New("This console is already connected. Force is required to take it over."))
}
_, err = op.Cancel()
@ -638,7 +638,7 @@ func instanceConsoleLogGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Forward the request if the container is remote.
@ -673,7 +673,7 @@ func instanceConsoleLogGet(d *Daemon, r *http.Request) response.Response {
if inst.Type() == instancetype.Container {
c, ok := inst.(instance.Container)
if !ok {
return response.SmartError(fmt.Errorf("Failed to cast inst to Container"))
return response.SmartError(errors.New("Failed to cast inst to Container"))
}
// Query the container's console ringbuffer.
@ -707,7 +707,7 @@ func instanceConsoleLogGet(d *Daemon, r *http.Request) response.Response {
} else if inst.Type() == instancetype.VM {
v, ok := inst.(instance.VM)
if !ok {
return response.SmartError(fmt.Errorf("Failed to cast inst to VM"))
return response.SmartError(errors.New("Failed to cast inst to VM"))
}
var headers map[string]string
@ -785,7 +785,7 @@ func instanceConsoleLogGet(d *Daemon, r *http.Request) response.Response {
// $ref: "#/responses/InternalServerError"
func instanceConsoleLogDelete(d *Daemon, r *http.Request) response.Response {
if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) {
return response.BadRequest(fmt.Errorf("Clearing the console buffer requires liblxc >= 3.0"))
return response.BadRequest(errors.New("Clearing the console buffer requires liblxc >= 3.0"))
}
name, err := url.PathUnescape(mux.Vars(r)["name"])
@ -794,7 +794,7 @@ func instanceConsoleLogDelete(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
projectName := request.ProjectParam(r)
@ -805,12 +805,12 @@ func instanceConsoleLogDelete(d *Daemon, r *http.Request) response.Response {
}
if inst.Type() != instancetype.Container {
return response.SmartError(fmt.Errorf("Instance is not container type"))
return response.SmartError(errors.New("Instance is not container type"))
}
c, ok := inst.(instance.Container)
if !ok {
return response.SmartError(fmt.Errorf("Instance is not container type"))
return response.SmartError(errors.New("Instance is not container type"))
}
truncateConsoleLogFile := func(path string) error {
@ -822,11 +822,11 @@ func instanceConsoleLogDelete(d *Daemon, r *http.Request) response.Response {
}
if !st.Mode().IsRegular() {
return fmt.Errorf("The console log is not a regular file")
return errors.New("The console log is not a regular file")
}
if path == "" {
return fmt.Errorf("Container does not keep a console logfile")
return errors.New("Container does not keep a console logfile")
}
return os.Truncate(path, 0)

View File

@ -1,7 +1,7 @@
package main
import (
"fmt"
"errors"
"io"
"net/http"
"net/url"
@ -63,7 +63,7 @@ func instanceDebugMemoryGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -83,16 +83,16 @@ func instanceDebugMemoryGet(d *Daemon, r *http.Request) response.Response {
}
if inst.Type() != instancetype.VM {
return response.BadRequest(fmt.Errorf("Memory dumps are only supported for virtual machines"))
return response.BadRequest(errors.New("Memory dumps are only supported for virtual machines"))
}
if !inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance must be running to dump memory"))
return response.BadRequest(errors.New("Instance must be running to dump memory"))
}
v, ok := inst.(instance.VM)
if !ok {
return response.InternalError(fmt.Errorf("Failed to cast inst to VM"))
return response.InternalError(errors.New("Failed to cast inst to VM"))
}
// Wrap up the request.

View File

@ -1,7 +1,7 @@
package main
import (
"fmt"
"errors"
"net/http"
"net/url"
@ -56,7 +56,7 @@ func instanceDelete(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -75,7 +75,7 @@ func instanceDelete(d *Daemon, r *http.Request) response.Response {
}
if inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance is running"))
return response.BadRequest(errors.New("Instance is running"))
}
run := func(op *operations.Operation) error {

View File

@ -82,7 +82,7 @@ func (s *execWs) metadata() any {
func (s *execWs) connect(_ *operations.Operation, r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
return errors.New("missing secret")
}
for fd, fdSecret := range s.fds {
@ -147,9 +147,9 @@ func (s *execWs) connect(_ *operations.Operation, r *http.Request, w http.Respon
s.waitRequiredConnected.Cancel() // All required connections now connected.
return nil
} else if !found {
return fmt.Errorf("Unknown websocket number")
return errors.New("Unknown websocket number")
} else {
return fmt.Errorf("Websocket number already connected")
return errors.New("Websocket number already connected")
}
}
}
@ -180,7 +180,7 @@ func (s *execWs) do(op *operations.Operation) error {
case <-s.waitRequiredConnected.Done():
break
case <-time.After(time.Second * 5):
return fmt.Errorf("Timed out waiting for websockets to connect")
return errors.New("Timed out waiting for websockets to connect")
}
var err error
@ -555,7 +555,7 @@ func instanceExecPost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
post := api.InstanceExecPost{}
@ -605,11 +605,11 @@ func instanceExecPost(d *Daemon, r *http.Request) response.Response {
}
if !inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance is not running"))
return response.BadRequest(errors.New("Instance is not running"))
}
if inst.IsFrozen() {
return response.BadRequest(fmt.Errorf("Instance is frozen"))
return response.BadRequest(errors.New("Instance is frozen"))
}
// Process environment.

View File

@ -2,6 +2,7 @@ package main
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
@ -37,7 +38,7 @@ func instanceFileHandler(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Redirect to correct server if needed.
@ -59,7 +60,7 @@ func instanceFileHandler(d *Daemon, r *http.Request) response.Response {
// Parse and cleanup the path.
path := r.FormValue("path")
if path == "" {
return response.BadRequest(fmt.Errorf("Missing path argument"))
return response.BadRequest(errors.New("Missing path argument"))
}
if !strings.HasPrefix(path, "/") {

View File

@ -1,7 +1,7 @@
package main
import (
"fmt"
"errors"
"net"
"net/http"
"net/url"
@ -108,7 +108,7 @@ func instanceGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Parse the recursion field

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"net/http"
"net/url"
@ -119,7 +120,7 @@ func instanceLogsGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -198,7 +199,7 @@ func instanceLogGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Ensure instance exists.
@ -277,7 +278,7 @@ func instanceLogDelete(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Ensure instance exists.
@ -311,7 +312,7 @@ func instanceLogDelete(d *Daemon, r *http.Request) response.Response {
}
if !strings.HasSuffix(file, ".log") || file == "lxc.log" || file == "qemu.log" {
return response.BadRequest(fmt.Errorf("Only log files excluding qemu.log and lxc.log may be deleted"))
return response.BadRequest(errors.New("Only log files excluding qemu.log and lxc.log may be deleted"))
}
err = os.Remove(internalUtil.LogPath(project.Instance(projectName, name), file))
@ -384,7 +385,7 @@ func instanceExecOutputsGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Ensure instance exists.
@ -484,7 +485,7 @@ func instanceExecOutputGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Ensure instance exists.
@ -579,7 +580,7 @@ func instanceExecOutputDelete(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Ensure instance exists.

View File

@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -76,7 +77,7 @@ func instanceMetadataGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -183,7 +184,7 @@ func instanceMetadataPatch(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to an instance on a different node.
@ -298,7 +299,7 @@ func instanceMetadataPut(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to an instance on a different node.
@ -417,7 +418,7 @@ func instanceMetadataTemplatesGet(d *Daemon, r *http.Request) response.Response
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -564,7 +565,7 @@ func instanceMetadataTemplatesPost(d *Daemon, r *http.Request) response.Response
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -599,7 +600,7 @@ func instanceMetadataTemplatesPost(d *Daemon, r *http.Request) response.Response
// Look at the request
templateName := r.FormValue("path")
if templateName == "" {
return response.BadRequest(fmt.Errorf("missing path argument"))
return response.BadRequest(errors.New("missing path argument"))
}
if !util.PathExists(filepath.Join(c.Path(), "templates")) {
@ -678,7 +679,7 @@ func instanceMetadataTemplatesDelete(d *Daemon, r *http.Request) response.Respon
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -713,7 +714,7 @@ func instanceMetadataTemplatesDelete(d *Daemon, r *http.Request) response.Respon
// Look at the request
templateName := r.FormValue("path")
if templateName == "" {
return response.BadRequest(fmt.Errorf("missing path argument"))
return response.BadRequest(errors.New("missing path argument"))
}
templatePath, err := getContainerTemplatePath(c, templateName)
@ -739,7 +740,7 @@ func instanceMetadataTemplatesDelete(d *Daemon, r *http.Request) response.Respon
// Return the full path of a container template.
func getContainerTemplatePath(c instance.Instance, filename string) (string, error) {
if strings.Contains(filename, "/") {
return "", fmt.Errorf("Invalid template filename")
return "", errors.New("Invalid template filename")
}
return filepath.Join(c.Path(), "templates", filename), nil

View File

@ -4,7 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"errors"
"io"
"net/http"
"net/url"
@ -71,7 +71,7 @@ func instancePatch(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -123,7 +123,7 @@ func instancePatch(d *Daemon, r *http.Request) response.Response {
}
if req.Restore != "" {
return response.BadRequest(fmt.Errorf("Can't call PATCH in restore mode"))
return response.BadRequest(errors.New("Can't call PATCH in restore mode"))
}
// Check if architecture was passed

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
@ -89,11 +90,11 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
if target != "" && !s.ServerClustered {
return response.BadRequest(fmt.Errorf("Target only allowed when clustered"))
return response.BadRequest(errors.New("Target only allowed when clustered"))
}
// Check if the server the instance is running on is currently online.
@ -125,7 +126,7 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
// More checks.
if target == "" && sourceMemberInfo != nil && sourceMemberInfo.IsOffline(s.GlobalConfig.OfflineThreshold()) {
return response.BadRequest(fmt.Errorf("Can't perform action as server is currently offline"))
return response.BadRequest(errors.New("Can't perform action as server is currently offline"))
}
// Handle request forwarding.
@ -221,7 +222,7 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
// Start handling migrations.
if inst.IsSnapshot() {
return response.BadRequest(fmt.Errorf("Instance snapshots cannot be moved on their own"))
return response.BadRequest(errors.New("Instance snapshots cannot be moved on their own"))
}
// Checks for running instances.
@ -229,32 +230,32 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
if req.Pool != "" || req.Project != "" || target != "" {
// Stateless migrations need the instance stopped.
if !req.Live {
return response.BadRequest(fmt.Errorf("Instance must be stopped to be moved statelessly"))
return response.BadRequest(errors.New("Instance must be stopped to be moved statelessly"))
}
// Storage pool changes require a target flag.
if req.Pool != "" {
if inst.Type() != instancetype.VM {
return response.BadRequest(fmt.Errorf("Live storage pool changes aren't supported for containers"))
return response.BadRequest(errors.New("Live storage pool changes aren't supported for containers"))
}
if !s.ServerClustered {
return response.BadRequest(fmt.Errorf("Live storage pool changes aren't supported on standalone systems"))
return response.BadRequest(errors.New("Live storage pool changes aren't supported on standalone systems"))
}
if target == "" {
return response.BadRequest(fmt.Errorf("Live storage pool changes require the VM be moved to another cluster member"))
return response.BadRequest(errors.New("Live storage pool changes require the VM be moved to another cluster member"))
}
}
// Project changes require a stopped instance.
if req.Project != "" {
return response.BadRequest(fmt.Errorf("Instance must be stopped to be moved across projects"))
return response.BadRequest(errors.New("Instance must be stopped to be moved across projects"))
}
// Name changes require a stopped instance.
if req.Name != "" {
return response.BadRequest(fmt.Errorf("Instance must be stopped to change their names"))
return response.BadRequest(errors.New("Instance must be stopped to change their names"))
}
}
} else {
@ -264,7 +265,7 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
// Check for offline sources.
if sourceMemberInfo != nil && sourceMemberInfo.IsOffline(s.GlobalConfig.OfflineThreshold()) && (req.Pool != "" || req.Project != "" || req.Name != "") {
return response.BadRequest(fmt.Errorf("Instance server is currently offline"))
return response.BadRequest(errors.New("Instance server is currently offline"))
}
// When in a cluster, default to keeping current location.
@ -437,14 +438,14 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
}
if len(filteredCandidateMembers) == 0 {
return response.InternalError(fmt.Errorf("Couldn't find a cluster member for the instance"))
return response.InternalError(errors.New("Couldn't find a cluster member for the instance"))
}
targetMemberInfo = &filteredCandidateMembers[0]
}
if targetMemberInfo.IsOffline(s.GlobalConfig.OfflineThreshold()) {
return response.BadRequest(fmt.Errorf("Target cluster member is offline"))
return response.BadRequest(errors.New("Target cluster member is offline"))
}
}
@ -457,7 +458,7 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
// Check that we're not requested to move to the same location we're currently on.
if target != "" && targetMemberInfo.Name == inst.Location() {
return response.BadRequest(fmt.Errorf("Requested target server is the same as current server"))
return response.BadRequest(errors.New("Requested target server is the same as current server"))
}
// If the instance needs to move, make sure it doesn't have backups.
@ -474,7 +475,7 @@ func instancePost(d *Daemon, r *http.Request) response.Response {
}
if len(backups) > 0 {
return response.BadRequest(fmt.Errorf("Instances with backups cannot be moved"))
return response.BadRequest(errors.New("Instances with backups cannot be moved"))
}
}
@ -547,7 +548,7 @@ func migrateInstance(ctx context.Context, s *state.State, inst instance.Instance
// Check that we're not requested to move to the same storage pool we're currently use.
if req.Pool != "" && req.Pool == sourcePool.Name() {
return fmt.Errorf("Requested storage pool is the same as current pool")
return errors.New("Requested storage pool is the same as current pool")
}
// Get the DB volume type for the instance.

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -74,7 +75,7 @@ func instancePut(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -67,7 +68,7 @@ func instanceRebuildPost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -126,7 +127,7 @@ func instanceRebuildPost(d *Daemon, r *http.Request) response.Response {
}
if inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance must be stopped to be rebuilt"))
return response.BadRequest(errors.New("Instance must be stopped to be rebuilt"))
}
run := func(op *operations.Operation) error {
@ -142,7 +143,7 @@ func instanceRebuildPost(d *Daemon, r *http.Request) response.Response {
}
if sourceImage == nil {
return fmt.Errorf("Image not provided for instance rebuild")
return errors.New("Image not provided for instance rebuild")
}
return instanceRebuildFromImage(context.TODO(), s, r, inst, sourceImage, op)

View File

@ -1,7 +1,7 @@
package main
import (
"fmt"
"errors"
"net"
"net/http"
"net/url"
@ -47,7 +47,7 @@ func instanceSFTPHandler(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(instName) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
if r.Header.Get("Upgrade") != "sftp" {

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -131,7 +132,7 @@ func instanceSnapshotsGet(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(cname) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -242,7 +243,7 @@ func instanceSnapshotsPost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -689,7 +690,7 @@ func snapshotPost(s *state.State, r *http.Request, snapInst instance.Instance) r
return operations.OperationResponse(op)
} else if !migration {
if reqNew.Name == "" {
return response.BadRequest(fmt.Errorf("A new name for the instance must be provided"))
return response.BadRequest(errors.New("A new name for the instance must be provided"))
}
}

View File

@ -2,6 +2,7 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
@ -75,7 +76,7 @@ func instanceState(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -144,7 +145,7 @@ func instanceStatePut(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
return response.BadRequest(errors.New("Invalid instance name"))
}
// Handle requests targeted to a container on a different node
@ -168,7 +169,7 @@ func instanceStatePut(d *Daemon, r *http.Request) response.Response {
// Check if the cluster member is evacuated.
if s.ServerClustered && req.Action != "stop" && s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
return response.Forbidden(errors.New("Cluster member is evacuated"))
}
// Don't mess with instances while in setup mode.

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"net"
"testing"
@ -306,7 +307,7 @@ func (suite *containerTestSuite) TestContainer_AddRoutedNicValidation() {
},
Name: "testFoo",
}, true)
suite.Req.NoError(err, fmt.Errorf("Adding multiple routed with gateway mode ['none'] should succeed. "))
suite.Req.NoError(err, errors.New("Adding multiple routed with gateway mode ['none'] should succeed. "))
eth0["ipv6.gateway"] = "auto"
eth1["ipv6.gateway"] = ""
@ -321,7 +322,7 @@ func (suite *containerTestSuite) TestContainer_AddRoutedNicValidation() {
Name: "testFoo",
}, true)
suite.Req.Error(err,
fmt.Errorf("Adding multiple routed nic devices with any gateway mmode ['auto',''] should throw error. "))
errors.New("Adding multiple routed nic devices with any gateway mmode ['auto',''] should throw error. "))
err = c.Update(db.InstanceArgs{
Type: instancetype.Container,
@ -334,7 +335,7 @@ func (suite *containerTestSuite) TestContainer_AddRoutedNicValidation() {
Name: "testFoo",
}, true)
suite.Req.NoError(err,
fmt.Errorf("Adding multiple nic devices with unicque nictype ['routed'] should throw error. "))
errors.New("Adding multiple nic devices with unicque nictype ['routed'] should throw error. "))
}
func (suite *containerTestSuite) TestContainer_IsPrivileged_Unprivileged() {

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
@ -218,7 +219,7 @@ func instancesGet(d *Daemon, r *http.Request) response.Response {
allProjects := util.IsTrue(r.FormValue("all-projects"))
if allProjects && projectName != "" {
return response.BadRequest(fmt.Errorf("Cannot specify a project when requesting all projects"))
return response.BadRequest(errors.New("Cannot specify a project when requesting all projects"))
} else if !allProjects && projectName == "" {
projectName = api.ProjectDefaultName
}
@ -312,7 +313,7 @@ func instancesGet(d *Daemon, r *http.Request) response.Response {
// Mark instances on unavailable projectInstanceToNodeName as down.
if mustLoadObjects && memberAddress == "0.0.0.0" {
for _, inst := range instances {
resultErrListAppend(inst, fmt.Errorf("unavailable"))
resultErrListAppend(inst, errors.New("unavailable"))
}
continue

View File

@ -94,7 +94,7 @@ func ensureDownloadedImageFitWithinBudget(ctx context.Context, s *state.State, r
func createFromImage(s *state.State, r *http.Request, p api.Project, profiles []api.Profile, img *api.Image, imgAlias string, req *api.InstancesPost) response.Response {
if s.ServerClustered && s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
return response.Forbidden(errors.New("Cluster member is evacuated"))
}
dbType, err := instancetype.New(string(req.Type))
@ -127,7 +127,7 @@ func createFromImage(s *state.State, r *http.Request, p api.Project, profiles []
return err
}
} else {
return fmt.Errorf("Image not provided for instance creation")
return errors.New("Image not provided for instance creation")
}
args.Architecture, err = osarch.ArchitectureID(img.Architecture)
@ -157,7 +157,7 @@ func createFromImage(s *state.State, r *http.Request, p api.Project, profiles []
func createFromNone(s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.ServerClustered && s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
return response.Forbidden(errors.New("Cluster member is evacuated"))
}
dbType, err := instancetype.New(string(req.Type))
@ -210,7 +210,7 @@ func createFromNone(s *state.State, r *http.Request, projectName string, profile
func createFromMigration(ctx context.Context, s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.ServerClustered && r != nil && r.Context().Value(request.CtxProtocol) != "cluster" && s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
return response.Forbidden(errors.New("Cluster member is evacuated"))
}
// Validate migration mode.
@ -254,7 +254,7 @@ func createFromMigration(ctx context.Context, s *state.State, r *http.Request, p
}
if storagePool == "" {
return response.BadRequest(fmt.Errorf("Can't find a storage pool for the instance to use"))
return response.BadRequest(errors.New("Can't find a storage pool for the instance to use"))
}
if localRootDiskDeviceKey == "" && storagePoolProfile == "" {
@ -301,7 +301,7 @@ func createFromMigration(ctx context.Context, s *state.State, r *http.Request, p
if response.IsNotFoundError(err) {
if clusterMoveSourceName != "" {
// Cluster move doesn't allow renaming as part of migration so fail here.
return response.SmartError(fmt.Errorf("Cluster move doesn't allow renaming"))
return response.SmartError(errors.New("Cluster move doesn't allow renaming"))
}
req.Source.Refresh = false
@ -484,11 +484,11 @@ func createFromMigration(ctx context.Context, s *state.State, r *http.Request, p
func createFromCopy(ctx context.Context, s *state.State, r *http.Request, projectName string, profiles []api.Profile, req *api.InstancesPost) response.Response {
if s.ServerClustered && s.DB.Cluster.LocalNodeIsEvacuated() {
return response.Forbidden(fmt.Errorf("Cluster member is evacuated"))
return response.Forbidden(errors.New("Cluster member is evacuated"))
}
if req.Source.Source == "" {
return response.BadRequest(fmt.Errorf("Must specify a source instance"))
return response.BadRequest(errors.New("Must specify a source instance"))
}
sourceProject := req.Source.Project
@ -595,7 +595,7 @@ func createFromCopy(ctx context.Context, s *state.State, r *http.Request, projec
}
if dbType != instancetype.Any && dbType != source.Type() {
return response.BadRequest(fmt.Errorf("Instance type should not be specified or should match source type"))
return response.BadRequest(errors.New("Instance type should not be specified or should match source type"))
}
args := db.InstanceArgs{
@ -710,7 +710,7 @@ func createFromBackup(s *state.State, r *http.Request, projectName string, data
// Detect broken legacy backups.
if bInfo.Config == nil {
return response.BadRequest(fmt.Errorf("Backup file is missing required information"))
return response.BadRequest(errors.New("Backup file is missing required information"))
}
// Check project permissions.
@ -983,7 +983,7 @@ func instancesPost(d *Daemon, r *http.Request) response.Response {
target := request.QueryParam(r, "target")
if !s.ServerClustered && target != "" {
return response.BadRequest(fmt.Errorf("Target only allowed when clustered"))
return response.BadRequest(errors.New("Target only allowed when clustered"))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -1130,7 +1130,7 @@ func instancesPost(d *Daemon, r *http.Request) response.Response {
}
if i > 100 {
return fmt.Errorf("Couldn't generate a new unique name after 100 tries")
return errors.New("Couldn't generate a new unique name after 100 tries")
}
}
@ -1226,7 +1226,7 @@ func instancesPost(d *Daemon, r *http.Request) response.Response {
}
if targetMemberInfo == nil {
return response.InternalError(fmt.Errorf("Couldn't find a cluster member for the instance"))
return response.InternalError(errors.New("Couldn't find a cluster member for the instance"))
}
}
@ -1332,7 +1332,7 @@ func instanceFindStoragePool(ctx context.Context, s *state.State, projectName st
})
if err != nil {
if response.IsNotFoundError(err) {
return "", "", "", nil, response.BadRequest(fmt.Errorf("This instance does not have any storage pools configured"))
return "", "", "", nil, response.BadRequest(errors.New("This instance does not have any storage pools configured"))
}
return "", "", "", nil, response.SmartError(err)
@ -1365,7 +1365,7 @@ func clusterCopyContainerInternal(ctx context.Context, s *state.State, r *http.R
}
if nodeAddress == "" {
return response.BadRequest(fmt.Errorf("The source instance is currently offline"))
return response.BadRequest(errors.New("The source instance is currently offline"))
}
// Connect to the container source

View File

@ -3,7 +3,7 @@ package main
import (
"context"
"database/sql"
"fmt"
"errors"
"os"
sqlite3 "github.com/mattn/go-sqlite3"
@ -50,7 +50,7 @@ func (c *cmdActivateifneeded) command() *cobra.Command {
func (c *cmdActivateifneeded) run(_ *cobra.Command, _ []string) error {
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
// Don't start a full daemon, we just need database access

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"net/url"
"os"
@ -41,7 +42,7 @@ func (c *cmdCallhook) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
path := args[0]
@ -63,7 +64,7 @@ func (c *cmdCallhook) run(cmd *cobra.Command, args []string) error {
// Only root should run this.
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
// Connect to daemon.
@ -117,14 +118,14 @@ func (c *cmdCallhook) run(cmd *cobra.Command, args []string) error {
break
case <-time.After(30 * time.Second):
return fmt.Errorf("Hook didn't finish within 30s")
return errors.New("Hook didn't finish within 30s")
}
// If the container is rebooting, we purposefully tell LXC that this hook failed so that
// it won't reboot the container, which lets us start it again in the OnStop function.
// Other hook types can return without error safely.
if hook == "stop" && target == "reboot" {
return fmt.Errorf("Reboot must be handled by Incus")
return errors.New("Reboot must be handled by Incus")
}
return nil

View File

@ -3,6 +3,7 @@ package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
@ -146,7 +147,7 @@ func (c *cmdClusterEdit) run(_ *cobra.Command, _ []string) error {
// Make sure that the daemon is not running.
_, err := incus.ConnectIncusUnix("", nil)
if err == nil {
return fmt.Errorf("The daemon is running, please stop it first.")
return errors.New("The daemon is running, please stop it first.")
}
database, err := db.OpenNode(filepath.Join(sys.DefaultOS().VarDir, "database"), nil)
@ -163,7 +164,7 @@ func (c *cmdClusterEdit) run(_ *cobra.Command, _ []string) error {
clusterAddress := config.ClusterAddress()
if clusterAddress == "" {
return fmt.Errorf(`Can't edit cluster configuration as server isn't clustered (missing "cluster.https_address" config)`)
return errors.New(`Can't edit cluster configuration as server isn't clustered (missing "cluster.https_address" config)`)
}
nodes, err = tx.GetRaftNodes(ctx)
@ -256,11 +257,11 @@ func (c *cmdClusterEdit) run(_ *cobra.Command, _ []string) error {
func validateNewConfig(oldNodes []db.RaftNode, newNodes []db.RaftNode) error {
if len(oldNodes) > len(newNodes) {
return fmt.Errorf("Removing cluster members is not supported")
return errors.New("Removing cluster members is not supported")
}
if len(oldNodes) < len(newNodes) {
return fmt.Errorf("Adding cluster members is not supported")
return errors.New("Adding cluster members is not supported")
}
numNewVoters := 0
@ -269,12 +270,12 @@ func validateNewConfig(oldNodes []db.RaftNode, newNodes []db.RaftNode) error {
// IDs should not be reordered among cluster members.
if oldNode.ID != newNode.ID {
return fmt.Errorf("Changing cluster member ID is not supported")
return errors.New("Changing cluster member ID is not supported")
}
// If the name field could not be populated, just ignore the new value.
if oldNode.Name != "" && newNode.Name != "" && oldNode.Name != newNode.Name {
return fmt.Errorf("Changing cluster member name is not supported")
return errors.New("Changing cluster member name is not supported")
}
if oldNode.Role == db.RaftSpare && newNode.Role == db.RaftVoter {
@ -419,7 +420,7 @@ func (c *cmdClusterRecoverFromQuorumLoss) run(_ *cobra.Command, _ []string) erro
// Make sure that the daemon is not running.
_, err := incus.ConnectIncusUnix("", nil)
if err == nil {
return fmt.Errorf("The daemon is running, please stop it first.")
return errors.New("The daemon is running, please stop it first.")
}
// Prompt for confirmation unless --quiet was passed.
@ -462,7 +463,7 @@ Do you want to proceed? (yes/no): `)
input = strings.TrimSuffix(input, "\n")
if !slices.Contains([]string{"yes"}, strings.ToLower(input)) {
return fmt.Errorf("Recover operation aborted")
return errors.New("Recover operation aborted")
}
return nil
@ -488,7 +489,7 @@ func (c *cmdClusterRemoveRaftNode) command() *cobra.Command {
func (c *cmdClusterRemoveRaftNode) run(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
_ = cmd.Help()
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
address := internalUtil.CanonicalNetworkAddress(args[0], ports.HTTPSDefaultPort)
@ -526,7 +527,7 @@ Do you want to proceed? (yes/no): `)
input = strings.TrimSuffix(input, "\n")
if !slices.Contains([]string{"yes"}, strings.ToLower(input)) {
return fmt.Errorf("Remove raft node operation aborted")
return errors.New("Remove raft node operation aborted")
}
return nil
@ -551,7 +552,7 @@ func textEditor(inPath string, inContent []byte) ([]byte, error) {
}
}
if editor == "" {
return []byte{}, fmt.Errorf("No text editor found, please set the EDITOR environment variable")
return []byte{}, errors.New("No text editor found, please set the EDITOR environment variable")
}
}
}

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
@ -44,7 +45,7 @@ func (c *cmdDaemon) run(cmd *cobra.Command, args []string) error {
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
neededPrograms := []string{"ip", "rsync", "setfattr", "tar", "unsquashfs", "xz"}

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
"strconv"
@ -39,12 +40,12 @@ func (c *cmdForkconsole) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
name := args[0]

View File

@ -84,7 +84,7 @@ void forkcoresched(void)
import "C"
import (
"fmt"
"errors"
"github.com/spf13/cobra"
@ -114,5 +114,5 @@ func (c *cmdForkcoresched) command() *cobra.Command {
}
func (c *cmdForkcoresched) run(_ *cobra.Command, _ []string) error {
return fmt.Errorf("This command should have been intercepted in cgo")
return errors.New("This command should have been intercepted in cgo")
}

View File

@ -328,7 +328,7 @@ void forkexec(void)
import "C"
import (
"fmt"
"errors"
"github.com/spf13/cobra"
@ -358,5 +358,5 @@ func (c *cmdForkexec) command() *cobra.Command {
}
func (c *cmdForkexec) run(_ *cobra.Command, _ []string) error {
return fmt.Errorf("This command should have been intercepted in cgo")
return errors.New("This command should have been intercepted in cgo")
}

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
"regexp"
@ -45,7 +46,7 @@ func (c *cmdForklimits) run(cmd *cobra.Command, _ []string) error {
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
type limit struct {
@ -71,7 +72,7 @@ func (c *cmdForklimits) run(cmd *cobra.Command, _ []string) error {
fdNum, err := strconv.Atoi(fdParts[1])
if err != nil {
_ = cmd.Help()
return fmt.Errorf("Invalid file descriptor number")
return errors.New("Invalid file descriptor number")
}
fds = append(fds, uintptr(fdNum))
@ -83,7 +84,7 @@ func (c *cmdForklimits) run(cmd *cobra.Command, _ []string) error {
break // No more passing of arguments needed.
} else {
_ = cmd.Help()
return fmt.Errorf("Unrecognised argument")
return errors.New("Unrecognised argument")
}
}
@ -128,7 +129,7 @@ func (c *cmdForklimits) run(cmd *cobra.Command, _ []string) error {
if len(cmdParts) == 0 {
_ = cmd.Help()
return fmt.Errorf("Missing required command argument")
return errors.New("Missing required command argument")
}
// Clear the cloexec flag on the file descriptors we are passing through.

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
"strconv"
@ -39,12 +40,12 @@ func (c *cmdForkmigrate) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
name := args[0]

View File

@ -629,7 +629,7 @@ void forkmount(void)
import "C"
import (
"fmt"
"errors"
"github.com/spf13/cobra"
@ -687,5 +687,5 @@ func (c *cmdForkmount) command() *cobra.Command {
}
func (c *cmdForkmount) run(_ *cobra.Command, _ []string) error {
return fmt.Errorf("This command should have been intercepted in cgo")
return errors.New("This command should have been intercepted in cgo")
}

View File

@ -213,6 +213,7 @@ import "C"
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@ -396,7 +397,7 @@ func (c *cmdForknet) dhcpRunV4(errorChannel chan error, iface string, hostname s
if lease.Offer.YourIPAddr == nil || lease.Offer.YourIPAddr.Equal(net.IPv4zero) || lease.Offer.SubnetMask() == nil || len(lease.Offer.Router()) != 1 {
logger.Error("Giving up on DHCPv4, lease didn't contain required fields")
errorChannel <- fmt.Errorf("Giving up on DHCPv4, lease didn't contain required fields")
errorChannel <- errors.New("Giving up on DHCPv4, lease didn't contain required fields")
return
}
@ -567,7 +568,7 @@ func (c *cmdForknet) dhcpRunV6(errorChannel chan error, iface string, hostname s
ia := reply.Options.OneIANA()
if ia == nil {
logger.Error("Giving up on DHCPv6 renewal, reply missing IANA")
errorChannel <- fmt.Errorf("Giving up on DHCPv6 renewal, reply missing IANA")
errorChannel <- errors.New("Giving up on DHCPv6 renewal, reply missing IANA")
return
}
@ -702,15 +703,15 @@ func (c *cmdForknet) runDetach(_ *cobra.Command, args []string) error {
hostName := args[3]
if daemonPID == "" {
return fmt.Errorf("Daemon PID argument is required")
return errors.New("Daemon PID argument is required")
}
if ifName == "" {
return fmt.Errorf("ifname argument is required")
return errors.New("ifname argument is required")
}
if hostName == "" {
return fmt.Errorf("hostname argument is required")
return errors.New("hostname argument is required")
}
// Check if the interface exists.

View File

@ -419,7 +419,7 @@ type lStruct struct {
func (c *cmdForkproxy) run(cmd *cobra.Command, args []string) error {
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
// Quick checks.
@ -430,12 +430,12 @@ func (c *cmdForkproxy) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Check where we are in initialization
if C.whoami != C.FORKPROXY_PARENT && C.whoami != C.FORKPROXY_CHILD {
return fmt.Errorf("Failed to call forkproxy constructor")
return errors.New("Failed to call forkproxy constructor")
}
listenAddr := args[2]
@ -451,7 +451,7 @@ func (c *cmdForkproxy) run(cmd *cobra.Command, args []string) error {
}
if (lAddr.ConnType == "udp" || lAddr.ConnType == "tcp") && cAddr.ConnType == "udp" || cAddr.ConnType == "tcp" {
err := fmt.Errorf("Invalid port range")
err := errors.New("Invalid port range")
if len(lAddr.Ports) > 1 && len(cAddr.Ports) > 1 && (len(cAddr.Ports) != len(lAddr.Ports)) {
fmt.Println(err)
return err
@ -638,7 +638,7 @@ func (c *cmdForkproxy) run(cmd *cobra.Command, args []string) error {
epFd := C.epoll_create1(C.EPOLL_CLOEXEC)
if epFd < 0 {
return fmt.Errorf("Failed to create new epoll instance")
return errors.New("Failed to create new epoll instance")
}
// Wait for SIGTERM and close the listener in order to exit the loop below
@ -673,7 +673,7 @@ func (c *cmdForkproxy) run(cmd *cobra.Command, args []string) error {
*(*C.int)(unsafe.Pointer(&ev.data)) = C.int(f.Fd())
ret := C.epoll_ctl(epFd, C.EPOLL_CTL_ADD, C.int(f.Fd()), &ev)
if ret < 0 {
return fmt.Errorf("Error: Failed to add listener fd to epoll instance")
return errors.New("Error: Failed to add listener fd to epoll instance")
}
}
@ -789,7 +789,7 @@ func proxyCopy(dst net.Conn, src net.Conn) error {
udpSessionsLock.Unlock()
if us == nil {
return fmt.Errorf("Connection expired")
return errors.New("Connection expired")
}
us.timerLock.Lock()
@ -916,7 +916,7 @@ func unixRelayer(src *net.UnixConn, dst *net.UnixConn, ch chan error) {
}
if sData != tData || sOob != tOob {
ch <- fmt.Errorf("Lost oob data during transfer")
ch <- errors.New("Lost oob data during transfer")
return
}
@ -1003,7 +1003,7 @@ func tryListenUDP(protocol string, addr string) (*os.File, error) {
}
if UDPConn == nil {
return nil, fmt.Errorf("Failed to setup UDP listener")
return nil, errors.New("Failed to setup UDP listener")
}
file, err := UDPConn.File()
@ -1028,7 +1028,7 @@ func getListenerFile(protocol string, addr string) (*os.File, error) {
case *net.UnixListener:
file, err = l.File()
default:
return nil, fmt.Errorf("Could not get listener file: invalid listener type")
return nil, errors.New("Could not get listener file: invalid listener type")
}
if err != nil {

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
@ -43,12 +44,12 @@ func (c *cmdForkstart) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
name := args[0]
@ -57,7 +58,7 @@ func (c *cmdForkstart) run(cmd *cobra.Command, args []string) error {
err := linux.CloseRange(uint32(os.Stderr.Fd())+1, ^uint32(0), linux.CLOSE_RANGE_CLOEXEC)
if err != nil {
return fmt.Errorf("Aborting attach to prevent leaking file descriptors into container")
return errors.New("Aborting attach to prevent leaking file descriptors into container")
}
d, err := liblxc.NewContainer(name, lxcpath)

View File

@ -551,7 +551,7 @@ void forksyscall(void)
import "C"
import (
"fmt"
"errors"
"github.com/spf13/cobra"
@ -581,5 +581,5 @@ func (c *cmdForksyscall) command() *cobra.Command {
}
func (c *cmdForksyscall) run(_ *cobra.Command, _ []string) error {
return fmt.Errorf("This command should have been intercepted in cgo")
return errors.New("This command should have been intercepted in cgo")
}

View File

@ -215,7 +215,7 @@ void forkuevent(void)
import "C"
import (
"fmt"
"errors"
"github.com/spf13/cobra"
)
@ -250,5 +250,5 @@ func (c *cmdForkuevent) command() *cobra.Command {
}
func (c *cmdForkuevent) run(_ *cobra.Command, _ []string) error {
return fmt.Errorf("This command should have been intercepted in cgo")
return errors.New("This command should have been intercepted in cgo")
}

View File

@ -2,7 +2,7 @@ package main
import (
"bufio"
"fmt"
"errors"
"os"
"os/exec"
"path/filepath"
@ -43,12 +43,12 @@ func (c *cmdForkZFS) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
// Mark mount tree as private

View File

@ -1,7 +1,7 @@
package main
import (
"fmt"
"errors"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
@ -35,7 +35,7 @@ func (c *cmdManpage) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Generate the manpages

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
@ -40,12 +41,12 @@ func (c *cmdMigratedumpsuccess) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
clientArgs := incus.ConnectionArgs{
@ -79,5 +80,5 @@ func (c *cmdMigratedumpsuccess) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf(op.Err)
return errors.New(op.Err)
}

View File

@ -1,6 +1,7 @@
package main
import (
"errors"
"fmt"
"io"
"net"
@ -46,12 +47,12 @@ func (c *cmdNetcat) run(cmd *cobra.Command, args []string) error {
return nil
}
return fmt.Errorf("Missing required arguments")
return errors.New("Missing required arguments")
}
// Only root should run this
if os.Geteuid() != 0 {
return fmt.Errorf("This must be run as root")
return errors.New("This must be run as root")
}
logPath := internalUtil.LogPath(args[1], "netcat.log")

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"net/url"
@ -102,7 +103,7 @@ func (s *migrationSourceWs) do(migrateOp *operations.Operation) error {
stateConnFunc := func(ctx context.Context) (io.ReadWriteCloser, error) {
conn := s.conns[api.SecretNameState]
if conn == nil {
return nil, fmt.Errorf("Migration source control connection not initialized")
return nil, errors.New("Migration source control connection not initialized")
}
wsConn, err := conn.WebsocketIO(ctx)
@ -116,7 +117,7 @@ func (s *migrationSourceWs) do(migrateOp *operations.Operation) error {
filesystemConnFunc := func(ctx context.Context) (io.ReadWriteCloser, error) {
conn := s.conns[api.SecretNameFilesystem]
if conn == nil {
return nil, fmt.Errorf("Migration source filesystem connection not initialized")
return nil, errors.New("Migration source filesystem connection not initialized")
}
wsConn, err := conn.WebsocketIO(ctx)
@ -236,7 +237,7 @@ func (c *migrationSink) do(instOp *operationlock.InstanceOperation) error {
stateConnFunc := func(ctx context.Context) (io.ReadWriteCloser, error) {
conn := c.conns[api.SecretNameState]
if conn == nil {
return nil, fmt.Errorf("Migration target control connection not initialized")
return nil, errors.New("Migration target control connection not initialized")
}
wsConn, err := conn.WebsocketIO(ctx)
@ -250,7 +251,7 @@ func (c *migrationSink) do(instOp *operationlock.InstanceOperation) error {
filesystemConnFunc := func(ctx context.Context) (io.ReadWriteCloser, error) {
conn := c.conns[api.SecretNameFilesystem]
if conn == nil {
return nil, fmt.Errorf("Migration target filesystem connection not initialized")
return nil, errors.New("Migration target filesystem connection not initialized")
}
wsConn, err := conn.WebsocketIO(ctx)

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
"io"
"net/url"
@ -141,7 +142,7 @@ func (s *migrationSourceWs) DoStorage(state *state.State, projectName string, po
// The same applies for clusterMove and storageMove, which are set to the most optimized defaults.
poolMigrationTypes = pool.MigrationTypes(storageDrivers.ContentType(srcConfig.Volume.ContentType), false, !s.volumeOnly, true, false)
if len(poolMigrationTypes) == 0 {
return fmt.Errorf("No source migration types available")
return errors.New("No source migration types available")
}
// Convert the pool's migration type options to an offer header to target.
@ -241,7 +242,7 @@ func (s *migrationSourceWs) DoStorage(state *state.State, projectName string, po
if !msg.GetSuccess() {
logger.Errorf("Failed to send storage volume")
return fmt.Errorf(msg.GetMessage())
return errors.New(msg.GetMessage())
}
logger.Debugf("Migration source finished transferring storage volume")
@ -521,7 +522,7 @@ func (c *migrationSink) DoStorage(state *state.State, projectName string, poolNa
if !msg.GetSuccess() {
c.disconnect()
return fmt.Errorf(msg.GetMessage())
return errors.New(msg.GetMessage())
}
// The source can only tell us it failed (e.g. if

View File

@ -4,6 +4,7 @@ import (
"context"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
@ -28,7 +29,7 @@ func setupWebsocketDialer(certificate string) (*websocket.Dialer, error) {
if certificate != "" {
certBlock, _ := pem.Decode([]byte(certificate))
if certBlock == nil {
return nil, fmt.Errorf("Failed PEM decoding certificate")
return nil, errors.New("Failed PEM decoding certificate")
}
cert, err = x509.ParseCertificate(certBlock.Bytes)
@ -83,7 +84,7 @@ func (c *migrationConn) AcceptIncoming(r *http.Request, w http.ResponseWriter) e
defer c.mu.Unlock()
if c.disconnected {
return fmt.Errorf("Connection already disconnected")
return errors.New("Connection already disconnected")
}
if c.conn != nil {
@ -119,7 +120,7 @@ func (c *migrationConn) WebSocket(ctx context.Context) (*websocket.Conn, error)
if c.disconnected {
c.mu.Unlock()
return nil, fmt.Errorf("Connection already disconnected")
return nil, errors.New("Connection already disconnected")
}
if c.conn != nil {

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -315,7 +316,7 @@ func networkACLsPost(d *Daemon, r *http.Request) response.Response {
_, err = acl.LoadByName(s, projectName, req.Name)
if err == nil {
return response.BadRequest(fmt.Errorf("The network ACL already exists"))
return response.BadRequest(errors.New("The network ACL already exists"))
}
err = acl.Create(s, projectName, &req)

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -298,7 +299,7 @@ func networkAddressSetsPost(d *Daemon, r *http.Request) response.Response {
_, err = addressset.LoadByName(s, projectName, req.Name)
if err == nil {
return response.BadRequest(fmt.Errorf("The network address set already exists"))
return response.BadRequest(errors.New("The network address set already exists"))
}
err = addressset.Create(s, projectName, &req)

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -365,7 +366,7 @@ func networkIntegrationDelete(d *Daemon, r *http.Request) response.Response {
}
if len(usedBy) > 0 {
return fmt.Errorf("Network integration is currently in use")
return errors.New("Network integration is currently in use")
}
err = dbCluster.DeleteNetworkIntegration(ctx, tx.Tx(), integrationName)
@ -804,7 +805,7 @@ func networkIntegrationValidate(integrationType string, inUse bool, oldConfig ma
}
if oldConfig != nil && oldConfig["ovn.transit.pattern"] != config["ovn.transit.pattern"] && inUse {
return fmt.Errorf("The OVN transit switch pattern cannot be changed while the integration is in use")
return errors.New("The OVN transit switch pattern cannot be changed while the integration is in use")
}
return nil

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -301,7 +302,7 @@ func networkZonesPost(d *Daemon, r *http.Request) response.Response {
// Create the zone.
err = zone.Exists(s, req.Name)
if err == nil {
return response.BadRequest(fmt.Errorf("The network zone already exists"))
return response.BadRequest(errors.New("The network zone already exists"))
}
err = zone.Create(s, projectName, &req)

View File

@ -364,11 +364,11 @@ func networksPost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if req.Name == "none" {
return response.BadRequest(fmt.Errorf("Network name 'none' is not valid"))
return response.BadRequest(errors.New("Network name 'none' is not valid"))
}
// Check if project allows access to network.
@ -400,7 +400,7 @@ func networksPost(d *Daemon, r *http.Request) response.Response {
netTypeInfo := netType.Info()
if projectName != api.ProjectDefaultName && !netTypeInfo.Projects {
return response.BadRequest(fmt.Errorf("Network type does not support non-default projects"))
return response.BadRequest(errors.New("Network type does not support non-default projects"))
}
// Check if project has limits.network and if so check we are allowed to create another network.
@ -425,7 +425,7 @@ func networksPost(d *Daemon, r *http.Request) response.Response {
// If it does then this create request will either be for adding a target node to an existing
// pending network or it will fail anyway as it is a duplicate.
if !slices.Contains(networks, req.Name) && len(networks) >= networksLimit {
return response.BadRequest(fmt.Errorf("Networks limit has been reached for project"))
return response.BadRequest(errors.New("Networks limit has been reached for project"))
}
}
@ -657,7 +657,7 @@ func networksPostCluster(ctx context.Context, s *state.State, projectName string
if netInfo != nil {
// Check network isn't already created.
if netInfo.Status == api.NetworkStatusCreated {
return fmt.Errorf("The network is already created")
return errors.New("The network is already created")
}
// Check the requested network type matches the type created when adding the local member config.
@ -672,7 +672,7 @@ func networksPostCluster(ctx context.Context, s *state.State, projectName string
// Check if any global config exists already, if so we should not create global config again.
if netInfo != nil && networkPartiallyCreated(netInfo) {
if len(req.Config) > 0 {
return fmt.Errorf("Network already partially created. Please do not specify any global config when re-running create")
return errors.New("Network already partially created. Please do not specify any global config when re-running create")
}
logger.Debug("Skipping global network create as global config already partially created", logger.Ctx{"project": projectName, "network": req.Name})
@ -708,7 +708,7 @@ func networksPostCluster(ctx context.Context, s *state.State, projectName string
})
if err != nil {
if response.IsNotFoundError(err) {
return fmt.Errorf("Network not pending on any node (use --target <node> first)")
return errors.New("Network not pending on any node (use --target <node> first)")
}
return err
@ -1102,7 +1102,7 @@ func networkDelete(d *Daemon, r *http.Request) response.Response {
}
if inUse {
return response.BadRequest(fmt.Errorf("The network is currently in use"))
return response.BadRequest(errors.New("The network is currently in use"))
}
}
@ -1198,7 +1198,7 @@ func networkPost(d *Daemon, r *http.Request) response.Response {
// network is not yet renamed in the db when the notified node
// runs network.Start).
if s.ServerClustered {
return response.BadRequest(fmt.Errorf("Renaming clustered network not supported"))
return response.BadRequest(errors.New("Renaming clustered network not supported"))
}
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
@ -1231,12 +1231,12 @@ func networkPost(d *Daemon, r *http.Request) response.Response {
}
if n.Status() != api.NetworkStatusCreated {
return response.BadRequest(fmt.Errorf("Cannot rename network when not in created state"))
return response.BadRequest(errors.New("Cannot rename network when not in created state"))
}
// Ensure new name is supplied.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("New network name not provided"))
return response.BadRequest(errors.New("New network name not provided"))
}
err = n.ValidateName(req.Name)
@ -1251,7 +1251,7 @@ func networkPost(d *Daemon, r *http.Request) response.Response {
}
if inUse {
return response.BadRequest(fmt.Errorf("Network is currently in use"))
return response.BadRequest(errors.New("Network is currently in use"))
}
var networks []string
@ -1360,7 +1360,7 @@ func networkPut(d *Daemon, r *http.Request) response.Response {
targetNode := request.QueryParam(r, "target")
if targetNode == "" && n.Status() != api.NetworkStatusCreated {
return response.BadRequest(fmt.Errorf("Cannot update network global config when not in created state"))
return response.BadRequest(errors.New("Cannot update network global config when not in created state"))
}
// Duplicate config for etag modification and generation.

View File

@ -204,7 +204,7 @@ func operationGet(d *Daemon, r *http.Request) response.Response {
}
if len(ops) > 1 {
return fmt.Errorf("More than one operation matches")
return errors.New("More than one operation matches")
}
operation := ops[0]
@ -312,7 +312,7 @@ func operationDelete(d *Daemon, r *http.Request) response.Response {
}
if len(ops) > 1 {
return fmt.Errorf("More than one operation matches")
return errors.New("More than one operation matches")
}
operation := ops[0]
@ -364,7 +364,7 @@ func operationCancel(s *state.State, r *http.Request, projectName string, op *ap
}
if len(ops) > 1 {
return fmt.Errorf("More than one operation matches")
return errors.New("More than one operation matches")
}
operation := ops[0]
@ -999,7 +999,7 @@ func operationWaitGet(d *Daemon, r *http.Request) response.Response {
}
if len(ops) > 1 {
return fmt.Errorf("More than one operation matches")
return errors.New("More than one operation matches")
}
operation := ops[0]
@ -1119,7 +1119,7 @@ func operationWebsocketGet(d *Daemon, r *http.Request) response.Response {
// Then check if the query is from an operation on another node, and, if so, forward it
secret := r.FormValue("secret")
if secret == "" {
return response.BadRequest(fmt.Errorf("Missing websocket secret"))
return response.BadRequest(errors.New("Missing websocket secret"))
}
var address string
@ -1135,7 +1135,7 @@ func operationWebsocketGet(d *Daemon, r *http.Request) response.Response {
}
if len(ops) > 1 {
return fmt.Errorf("More than one operation matches")
return errors.New("More than one operation matches")
}
operation := ops[0]

View File

@ -342,11 +342,11 @@ func profilesPost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Profile names may not contain slashes"))
return response.BadRequest(errors.New("Profile names may not contain slashes"))
}
if slices.Contains([]string{".", ".."}, req.Name) {
@ -373,7 +373,7 @@ func profilesPost(d *Daemon, r *http.Request) response.Response {
current, _ := dbCluster.GetProfile(ctx, tx.Tx(), p.Name, req.Name)
if current != nil {
return fmt.Errorf("The profile already exists")
return errors.New("The profile already exists")
}
profile := dbCluster.Profile{
@ -809,11 +809,11 @@ func profilePost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Profile names may not contain slashes"))
return response.BadRequest(errors.New("Profile names may not contain slashes"))
}
if slices.Contains([]string{".", ".."}, req.Name) {
@ -904,7 +904,7 @@ func profileDelete(d *Daemon, r *http.Request) response.Response {
}
if len(usedBy) > 0 {
return fmt.Errorf("Profile is currently in use")
return errors.New("Profile is currently in use")
}
return dbCluster.DeleteProfile(ctx, tx.Tx(), p.Name, name)

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"fmt"
internalInstance "github.com/lxc/incus/v6/internal/instance"
@ -69,7 +70,7 @@ func doProfileUpdate(ctx context.Context, s *state.State, p api.Project, profile
// Found the profile.
if inst.Profiles[i].Name == profileName {
// If it's the current profile, then we can't modify that root device.
return fmt.Errorf("At least one instance relies on this profile's root disk device")
return errors.New("At least one instance relies on this profile's root disk device")
}
// If it's not, then move on to the next instance.

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -363,7 +364,7 @@ func storagePoolBucketGet(d *Daemon, r *http.Request) response.Response {
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -1094,7 +1095,7 @@ func storagePoolBucketKeyGet(d *Daemon, r *http.Request) response.Response {
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -176,7 +177,7 @@ func storagePoolBucketBackupsGet(d *Daemon, r *http.Request) response.Response {
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -265,7 +266,7 @@ func storagePoolBucketBackupsPost(d *Daemon, r *http.Request) response.Response
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -356,7 +357,7 @@ func storagePoolBucketBackupsPost(d *Daemon, r *http.Request) response.Response
// Validate the name.
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
fullName := bucketName + internalInstance.SnapshotDelimiter + req.Name
@ -460,7 +461,7 @@ func storagePoolBucketBackupGet(d *Daemon, r *http.Request) response.Response {
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -544,7 +545,7 @@ func storagePoolBucketBackupPost(d *Daemon, r *http.Request) response.Response {
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -565,7 +566,7 @@ func storagePoolBucketBackupPost(d *Daemon, r *http.Request) response.Response {
// Validate the name
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
oldName := bucketName + internalInstance.SnapshotDelimiter + backupName
@ -655,7 +656,7 @@ func storagePoolBucketBackupDelete(d *Daemon, r *http.Request) response.Response
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])
@ -749,7 +750,7 @@ func storagePoolBucketBackupExportGet(d *Daemon, r *http.Request) response.Respo
}
if !pool.Driver().Info().Buckets {
return response.BadRequest(fmt.Errorf("Storage pool does not support buckets"))
return response.BadRequest(errors.New("Storage pool does not support buckets"))
}
bucketName, err := url.PathUnescape(mux.Vars(r)["bucketName"])

View File

@ -314,15 +314,15 @@ func storagePoolsPost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Storage pool names may not contain slashes"))
return response.BadRequest(errors.New("Storage pool names may not contain slashes"))
}
if req.Driver == "" {
return response.BadRequest(fmt.Errorf("No driver provided"))
return response.BadRequest(errors.New("No driver provided"))
}
if req.Config == nil {
@ -497,7 +497,7 @@ func storagePoolsPostCluster(ctx context.Context, s *state.State, pool *api.Stor
if pool != nil {
// Check pool isn't already created.
if pool.Status == api.StoragePoolStatusCreated {
return fmt.Errorf("The storage pool is already created")
return errors.New("The storage pool is already created")
}
// Check the requested pool type matches the type created when adding the local member config.
@ -521,7 +521,7 @@ func storagePoolsPostCluster(ctx context.Context, s *state.State, pool *api.Stor
// Check if any global config exists already, if so we should not create global config again.
if pool != nil && storagePoolPartiallyCreated(pool) {
if len(req.Config) > 0 {
return fmt.Errorf("Storage pool already partially created. Please do not specify any global config when re-running create")
return errors.New("Storage pool already partially created. Please do not specify any global config when re-running create")
}
logger.Debug("Skipping global storage pool create as global config already partially created", logger.Ctx{"pool": req.Name})
@ -545,7 +545,7 @@ func storagePoolsPostCluster(ctx context.Context, s *state.State, pool *api.Stor
})
if err != nil {
if response.IsNotFoundError(err) {
return fmt.Errorf("Pool not pending on any node (use --target <node> first)")
return errors.New("Pool not pending on any node (use --target <node> first)")
}
return err
@ -803,7 +803,7 @@ func storagePoolPut(d *Daemon, r *http.Request) response.Response {
targetNode := request.QueryParam(r, "target")
if targetNode == "" && pool.Status() != api.StoragePoolStatusCreated {
return response.BadRequest(fmt.Errorf("Cannot update storage pool global config when not in created state"))
return response.BadRequest(errors.New("Cannot update storage pool global config when not in created state"))
}
// Duplicate config for etag modification and generation.
@ -1031,7 +1031,7 @@ func storagePoolDelete(d *Daemon, r *http.Request) response.Response {
}
if inUse {
return response.BadRequest(fmt.Errorf("The storage pool is currently in use"))
return response.BadRequest(errors.New("The storage pool is currently in use"))
}
// Get the cluster notifier

View File

@ -6,6 +6,7 @@ import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
@ -666,11 +667,11 @@ func storagePoolVolumesPost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Storage volume names may not contain slashes"))
return response.BadRequest(errors.New("Storage volume names may not contain slashes"))
}
// Backward compatibility.
@ -723,7 +724,7 @@ func storagePoolVolumesPost(d *Daemon, r *http.Request) response.Response {
if err != nil {
return response.SmartError(err)
} else if dbVolume != nil && !req.Source.Refresh {
return response.Conflict(fmt.Errorf("Volume by that name already exists"))
return response.Conflict(errors.New("Volume by that name already exists"))
}
target := request.QueryParam(r, "target")
@ -748,7 +749,7 @@ func storagePoolVolumesPost(d *Daemon, r *http.Request) response.Response {
}
if nodeAddress == "" {
return response.BadRequest(fmt.Errorf("The source is currently offline"))
return response.BadRequest(errors.New("The source is currently offline"))
}
return clusterCopyCustomVolumeInternal(s, r, nodeAddress, projectName, poolName, &req)
@ -832,7 +833,7 @@ func doCustomVolumeRefresh(s *state.State, r *http.Request, requestProjectName s
defer reverter.Fail()
if req.Source.Name == "" {
return fmt.Errorf("No source volume name supplied")
return errors.New("No source volume name supplied")
}
err = pool.RefreshCustomVolume(projectName, srcProjectName, req.Name, req.Description, req.Config, req.Source.Pool, req.Source.Name, !req.Source.VolumeOnly, req.Source.RefreshExcludeOlder, op)
@ -918,7 +919,7 @@ func doVolumeMigration(s *state.State, r *http.Request, requestProjectName strin
if req.Source.Certificate != "" {
certBlock, _ := pem.Decode([]byte(req.Source.Certificate))
if certBlock == nil {
return response.InternalError(fmt.Errorf("Invalid certificate"))
return response.InternalError(errors.New("Invalid certificate"))
}
cert, err = x509.ParseCertificate(certBlock.Bytes)
@ -1045,7 +1046,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(volumeName) {
return response.BadRequest(fmt.Errorf("Invalid volume name"))
return response.BadRequest(errors.New("Invalid volume name"))
}
// Get the name of the storage pool the volume is supposed to be attached to.
@ -1064,12 +1065,12 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
// Check requested new volume name is not a snapshot volume.
if internalInstance.IsSnapshot(req.Name) {
return response.BadRequest(fmt.Errorf("Storage volume names may not contain slashes"))
return response.BadRequest(errors.New("Storage volume names may not contain slashes"))
}
// We currently only allow to create storage volumes of type storagePoolVolumeTypeCustom.
@ -1095,11 +1096,11 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
// and this means that the volume would effectively be moved into the default project, and so we
// require the user explicitly indicates this by targeting it directly.
if targetProjectName != req.Project {
return response.BadRequest(fmt.Errorf("Target project does not have features.storage.volumes enabled"))
return response.BadRequest(errors.New("Target project does not have features.storage.volumes enabled"))
}
if projectName == targetProjectName {
return response.BadRequest(fmt.Errorf("Project and target project are the same"))
return response.BadRequest(errors.New("Project and target project are the same"))
}
// Check if user has access to effective storage target project
@ -1192,7 +1193,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
})
if err != nil {
if s.ServerClustered && targetIsSet && volumeNotFound {
return response.NotFound(fmt.Errorf("Storage volume not found on this cluster member"))
return response.NotFound(errors.New("Storage volume not found on this cluster member"))
}
return response.SmartError(err)
@ -1243,7 +1244,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
}
if targetMemberInfo.IsOffline(s.GlobalConfig.OfflineThreshold()) {
return response.BadRequest(fmt.Errorf("Target cluster member is offline"))
return response.BadRequest(errors.New("Target cluster member is offline"))
}
run := func(op *operations.Operation) error {
@ -1315,7 +1316,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
return response.InternalError(err)
}
return response.Conflict(fmt.Errorf("Volume by that name already exists"))
return response.Conflict(errors.New("Volume by that name already exists"))
}
// Check if the daemon itself is using it.
@ -1325,7 +1326,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
}
if used {
return response.SmartError(fmt.Errorf("Volume is used by Incus itself and cannot be renamed"))
return response.SmartError(errors.New("Volume is used by Incus itself and cannot be renamed"))
}
var dbVolume *db.StorageVolume
@ -1352,7 +1353,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
})
if err != nil {
if s.ServerClustered && targetIsSet && volumeNotFound {
return response.NotFound(fmt.Errorf("Storage volume not found on this cluster member"))
return response.NotFound(errors.New("Storage volume not found on this cluster member"))
}
return response.SmartError(err)
@ -1366,7 +1367,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
}
if inst.IsRunning() {
return fmt.Errorf("Volume is still in use by running instances")
return errors.New("Volume is still in use by running instances")
}
return nil
@ -1386,7 +1387,7 @@ func storagePoolVolumePost(d *Daemon, r *http.Request) response.Response {
func migrateStorageVolume(s *state.State, r *http.Request, sourceVolumeName string, sourcePoolName string, targetNode string, projectName string, req api.StorageVolumePost, op *operations.Operation) error {
if targetNode == req.Source.Location {
return fmt.Errorf("Target must be different than storage volumes' current location")
return errors.New("Target must be different than storage volumes' current location")
}
var err error
@ -1430,7 +1431,7 @@ func storageVolumePostClusteringMigrate(s *state.State, r *http.Request, srcPool
// Make sure that the source member is online if we end up being called from another member after a
// redirection due to the source member being offline.
if srcMemberOffline {
return nil, fmt.Errorf("The cluster member hosting the storage volume is offline")
return nil, errors.New("The cluster member hosting the storage volume is offline")
}
run := func(op *operations.Operation) error {
@ -1929,7 +1930,7 @@ func storagePoolVolumePut(d *Daemon, r *http.Request) response.Response {
return response.SmartError(err)
}
} else {
return response.SmartError(fmt.Errorf("Invalid volume type"))
return response.SmartError(errors.New("Invalid volume type"))
}
return response.EmptySyncResponse
@ -1989,7 +1990,7 @@ func storagePoolVolumePatch(d *Daemon, r *http.Request) response.Response {
}
if internalInstance.IsSnapshot(volumeName) {
return response.BadRequest(fmt.Errorf("Invalid volume name"))
return response.BadRequest(errors.New("Invalid volume name"))
}
// Get the name of the storage pool the volume is supposed to be attached to.
@ -2195,7 +2196,7 @@ func storagePoolVolumeDelete(d *Daemon, r *http.Request) response.Response {
if len(volumeUsedBy) > 0 {
if len(volumeUsedBy) != 1 || volumeType != db.StoragePoolVolumeTypeImage || !isImageURL(volumeUsedBy[0], dbVolume.Name) {
return response.BadRequest(fmt.Errorf("The storage volume is still in use"))
return response.BadRequest(errors.New("The storage volume is still in use"))
}
}
@ -2224,7 +2225,7 @@ func createStoragePoolVolumeFromISO(s *state.State, r *http.Request, requestProj
defer reverter.Fail()
if volName == "" {
return response.BadRequest(fmt.Errorf("Missing volume name"))
return response.BadRequest(errors.New("Missing volume name"))
}
// Create isos directory if needed.

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -425,7 +426,7 @@ func storagePoolVolumeTypeCustomBackupsPost(d *Daemon, r *http.Request) response
// Validate the name.
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
fullName := volumeName + internalInstance.SnapshotDelimiter + req.Name
@ -670,7 +671,7 @@ func storagePoolVolumeTypeCustomBackupPost(d *Daemon, r *http.Request) response.
// Validate the name
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Backup names may not contain slashes"))
return response.BadRequest(errors.New("Backup names may not contain slashes"))
}
oldName := volumeName + internalInstance.SnapshotDelimiter + backupName

View File

@ -3,6 +3,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -174,7 +175,7 @@ func storagePoolVolumeSnapshotsTypePost(d *Daemon, r *http.Request) response.Res
}
if used {
return response.BadRequest(fmt.Errorf("Volumes used by Incus itself cannot have snapshots"))
return response.BadRequest(errors.New("Volumes used by Incus itself cannot have snapshots"))
}
// Retrieve the storage pool (and check if the storage pool exists).
@ -598,11 +599,11 @@ func storagePoolVolumeSnapshotTypePost(d *Daemon, r *http.Request) response.Resp
// Quick checks.
if req.Name == "" {
return response.BadRequest(fmt.Errorf("No name provided"))
return response.BadRequest(errors.New("No name provided"))
}
if strings.Contains(req.Name, "/") {
return response.BadRequest(fmt.Errorf("Storage volume names may not contain slashes"))
return response.BadRequest(errors.New("Storage volume names may not contain slashes"))
}
// This is a migration request so send back requested secrets.

View File

@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@ -372,7 +373,7 @@ func warningPut(d *Daemon, r *http.Request) response.Response {
}
if status != warningtype.StatusAcknowledged && status != warningtype.StatusNew {
return response.Forbidden(fmt.Errorf(`Status may only be set to "acknowledge" or "new"`))
return response.Forbidden(errors.New(`Status may only be set to "acknowledge" or "new"`))
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -508,7 +509,7 @@ func getWarningEntityURL(ctx context.Context, tx *sql.Tx, warning *cluster.Warni
_, ok := cluster.EntityNames[warning.EntityTypeCode]
if !ok {
return "", fmt.Errorf("Unknown entity type")
return "", errors.New("Unknown entity type")
}
var url string

View File

@ -4,6 +4,7 @@ import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"os"
"path/filepath"
@ -127,7 +128,7 @@ func UpdateCertificate(s *state.State, challengeType string, clustered bool, dom
env = append(env, environment...)
if provider == "" {
return nil, fmt.Errorf("DNS-01 challenge type requires acme.dns.provider configuration key to be set")
return nil, errors.New("DNS-01 challenge type requires acme.dns.provider configuration key to be set")
}
args = append(args, "--dns", provider)

View File

@ -189,7 +189,7 @@ func deleteProfile(sysOS *sys.OS, fullName string, name string) error {
}
if aaCacheDir == "" {
return fmt.Errorf("Couldn't identify AppArmor cache directory")
return errors.New("Couldn't identify AppArmor cache directory")
}
err := unloadProfile(sysOS, fullName, name)
@ -217,7 +217,7 @@ func parserSupports(sysOS *sys.OS, feature string) (bool, error) {
}
if aaVersion == nil {
return false, fmt.Errorf("Couldn't identify AppArmor version")
return false, errors.New("Couldn't identify AppArmor version")
}
if feature == "unix" {

View File

@ -2,6 +2,7 @@ package auth
import (
"context"
"errors"
"fmt"
"net/http"
@ -22,7 +23,7 @@ const (
)
// ErrUnknownDriver is the "Unknown driver" error.
var ErrUnknownDriver = fmt.Errorf("Unknown driver")
var ErrUnknownDriver = errors.New("Unknown driver")
var authorizers = map[string]func() authorizer{
DriverTLS: func() authorizer { return &TLS{} },

View File

@ -1,6 +1,7 @@
package auth
import (
"errors"
"fmt"
"net/http"
"net/url"
@ -228,7 +229,7 @@ func ObjectFromRequest(r *http.Request, objectType ObjectType, expandProject fun
// If using projects API we want to pass in the mux var, not the query parameter.
if objectType == ObjectTypeProject && strings.HasPrefix(r.URL.Path, fmt.Sprintf("/%s/projects", version.APIVersion)) {
if len(muxValues) == 0 {
return "", fmt.Errorf("Missing project name path variable")
return "", errors.New("Missing project name path variable")
}
return ObjectProject(muxValues[0]), nil

View File

@ -2,6 +2,7 @@ package auth
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
@ -19,7 +20,7 @@ type commonAuthorizer struct {
func (c *commonAuthorizer) init(driverName string, l logger.Logger) error {
if l == nil {
return fmt.Errorf("Cannot initialize authorizer: nil logger provided")
return errors.New("Cannot initialize authorizer: nil logger provided")
}
l = l.AddContext(logger.Ctx{"driver": driverName})
@ -75,29 +76,29 @@ func (r *requestDetails) actualDetails() *common.RequestDetails {
func (c *commonAuthorizer) requestDetails(r *http.Request) (*requestDetails, error) {
if r == nil {
return nil, fmt.Errorf("Cannot inspect nil request")
return nil, errors.New("Cannot inspect nil request")
} else if r.URL == nil {
return nil, fmt.Errorf("Request URL is not set")
return nil, errors.New("Request URL is not set")
}
val := r.Context().Value(request.CtxUsername)
if val == nil {
return nil, fmt.Errorf("Username not present in request context")
return nil, errors.New("Username not present in request context")
}
username, ok := val.(string)
if !ok {
return nil, fmt.Errorf("Request context username has incorrect type")
return nil, errors.New("Request context username has incorrect type")
}
val = r.Context().Value(request.CtxProtocol)
if val == nil {
return nil, fmt.Errorf("Protocol not present in request context")
return nil, errors.New("Protocol not present in request context")
}
protocol, ok := val.(string)
if !ok {
return nil, fmt.Errorf("Request context protocol has incorrect type")
return nil, errors.New("Request context protocol has incorrect type")
}
var forwardedUsername string
@ -105,7 +106,7 @@ func (c *commonAuthorizer) requestDetails(r *http.Request) (*requestDetails, err
if val != nil {
forwardedUsername, ok = val.(string)
if !ok {
return nil, fmt.Errorf("Request context forwarded username has incorrect type")
return nil, errors.New("Request context forwarded username has incorrect type")
}
}
@ -114,7 +115,7 @@ func (c *commonAuthorizer) requestDetails(r *http.Request) (*requestDetails, err
if val != nil {
forwardedProtocol, ok = val.(string)
if !ok {
return nil, fmt.Errorf("Request context forwarded username has incorrect type")
return nil, errors.New("Request context forwarded username has incorrect type")
}
}

View File

@ -39,12 +39,12 @@ type FGA struct {
func (f *FGA) configure(opts Opts) error {
if opts.config == nil {
return fmt.Errorf("Missing OpenFGA config")
return errors.New("Missing OpenFGA config")
}
val, ok := opts.config["openfga.api.token"]
if !ok || val == nil {
return fmt.Errorf("Missing OpenFGA API token")
return errors.New("Missing OpenFGA API token")
}
f.apiToken, ok = val.(string)
@ -54,7 +54,7 @@ func (f *FGA) configure(opts Opts) error {
val, ok = opts.config["openfga.api.url"]
if !ok || val == nil {
return fmt.Errorf("Missing OpenFGA API URL")
return errors.New("Missing OpenFGA API URL")
}
f.apiURL, ok = val.(string)
@ -64,7 +64,7 @@ func (f *FGA) configure(opts Opts) error {
val, ok = opts.config["openfga.store.id"]
if !ok || val == nil {
return fmt.Errorf("Missing OpenFGA store ID")
return errors.New("Missing OpenFGA store ID")
}
f.storeID, ok = val.(string)
@ -1201,7 +1201,7 @@ func (f *FGA) GetInstanceAccess(ctx context.Context, projectName string, instanc
var fgaNotFoundErr openfga.FgaApiNotFoundError
ok := errors.As(err, &fgaNotFoundErr)
if ok && fgaNotFoundErr.ResponseCode() == openfga.NOTFOUNDERRORCODE_UNDEFINED_ENDPOINT {
return nil, fmt.Errorf("OpenFGA server doesn't support listing users")
return nil, errors.New("OpenFGA server doesn't support listing users")
}
return nil, fmt.Errorf("Failed to list objects with relation %q: %w: %T", relation, err, err)
@ -1257,7 +1257,7 @@ func (f *FGA) GetProjectAccess(ctx context.Context, projectName string) (*api.Ac
var fgaNotFoundErr openfga.FgaApiNotFoundError
ok := errors.As(err, &fgaNotFoundErr)
if ok && fgaNotFoundErr.ResponseCode() == openfga.NOTFOUNDERRORCODE_UNDEFINED_ENDPOINT {
return nil, fmt.Errorf("OpenFGA server doesn't support listing users")
return nil, errors.New("OpenFGA server doesn't support listing users")
}
return nil, fmt.Errorf("Failed to list objects with relation %q: %w: %T", relation, err, err)

View File

@ -2,6 +2,7 @@ package oidc
import (
"context"
"errors"
"fmt"
"net/http"
"slices"
@ -57,7 +58,7 @@ func (o *Verifier) Auth(ctx context.Context, w http.ResponseWriter, r *http.Requ
// Both returned errors contain information which are needed for the client to authenticate.
parts := strings.Split(auth, "Bearer ")
if len(parts) != 2 {
return "", &AuthError{fmt.Errorf("Bad authorization token, expected a Bearer token")}
return "", &AuthError{errors.New("Bad authorization token, expected a Bearer token")}
}
token = parts[1]
@ -293,7 +294,7 @@ func (o *Verifier) VerifyAccessToken(ctx context.Context, token string) (*oidc.A
// Check that the token includes the configured audience.
audience := claims.GetAudience()
if o.audience != "" && !slices.Contains(audience, o.audience) {
return nil, fmt.Errorf("Provided OIDC token doesn't allow the configured audience")
return nil, errors.New("Provided OIDC token doesn't allow the configured audience")
}
return claims, nil

View File

@ -2,7 +2,7 @@ package backup
import (
"context"
"fmt"
"errors"
"os"
"path/filepath"
@ -170,7 +170,7 @@ func UpdateInstanceConfig(c *db.Cluster, b Info, mountPath string) error {
}
if !rootDiskDeviceFound {
return fmt.Errorf("No root device could be found")
return errors.New("No root device could be found")
}
// Write updated backup.yaml file.

View File

@ -3,7 +3,7 @@ package backup
import (
"archive/tar"
"context"
"fmt"
"errors"
"io"
"github.com/lxc/incus/v6/internal/server/sys"
@ -23,7 +23,7 @@ func TarReader(r io.ReadSeeker, sysOS *sys.OS, outputPath string) (*tar.Reader,
}
if unpacker == nil {
return nil, nil, fmt.Errorf("Unsupported backup compression")
return nil, nil, errors.New("Unsupported backup compression")
}
tr, cancelFunc, err := archive.CompressedTarReader(context.Background(), r, unpacker, outputPath)

View File

@ -1,14 +1,14 @@
package bgp
import (
"fmt"
"errors"
)
// ErrPrefixNotFound is returned when a user provided prefix couldn't be found.
var ErrPrefixNotFound = fmt.Errorf("Prefix not found")
var ErrPrefixNotFound = errors.New("Prefix not found")
// ErrPeerNotFound is returned when a user provided peer couldn't be found.
var ErrPeerNotFound = fmt.Errorf("Peer not found")
var ErrPeerNotFound = errors.New("Peer not found")
// ErrBadRouterID is returned when an invalid router-id is provided.
var ErrBadRouterID = fmt.Errorf("Invalid router-id (must be IPv4 address")
var ErrBadRouterID = errors.New("Invalid router-id (must be IPv4 address")

View File

@ -2,6 +2,7 @@ package bgp
import (
"context"
"errors"
"fmt"
"maps"
"net"
@ -70,7 +71,7 @@ func (s *Server) start(address string, asn uint32, routerID net.IP) error {
// Check if already running
if s.bgp != nil {
return fmt.Errorf("BGP listener is already running")
return errors.New("BGP listener is already running")
}
// Spawn the BGP goroutines.

View File

@ -1,7 +1,7 @@
package certificate
import (
"fmt"
"errors"
"github.com/lxc/incus/v6/shared/api"
)
@ -29,5 +29,5 @@ func FromAPIType(apiType string) (Type, error) {
return TypeMetrics, nil
}
return -1, fmt.Errorf("Invalid certificate type")
return -1, errors.New("Invalid certificate type")
}

View File

@ -1002,7 +1002,7 @@ func (cg *CGroup) GetOOMKills() (int64, error) {
}
}
return -1, fmt.Errorf("Failed getting oom_kill")
return -1, errors.New("Failed getting oom_kill")
}
// GetIOStats returns disk stats.

View File

@ -1,11 +1,11 @@
package cgroup
import (
"fmt"
"errors"
)
// ErrControllerMissing indicates that the requested controller isn't setup on the system.
var ErrControllerMissing = fmt.Errorf("Cgroup controller is missing")
var ErrControllerMissing = errors.New("Cgroup controller is missing")
// ErrUnknownVersion indicates that a version other than those supported was detected during init.
var ErrUnknownVersion = fmt.Errorf("Unknown cgroup version")
var ErrUnknownVersion = errors.New("Unknown cgroup version")

View File

@ -1,13 +1,13 @@
package cgroup
import (
"fmt"
"errors"
)
// New setups a new CGroup abstraction using the provided read/writer.
func New(rw ReadWriter) (*CGroup, error) {
if rw == nil {
return nil, fmt.Errorf("A CGroup read/writer is required")
return nil, errors.New("A CGroup read/writer is required")
}
cg := CGroup{}

View File

@ -2,6 +2,7 @@ package config
import (
"context"
"errors"
"fmt"
"maps"
"strconv"
@ -1055,7 +1056,7 @@ func offlineThresholdValidator(value string) error {
// which is the lower bound granularity of the offline check.
threshold, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Offline threshold is not a number")
return errors.New("Offline threshold is not a number")
}
if threshold <= minThreshold {
@ -1068,11 +1069,11 @@ func offlineThresholdValidator(value string) error {
func imageMinimalReplicaValidator(value string) error {
count, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Minimal image replica count is not a number")
return errors.New("Minimal image replica count is not a number")
}
if count < 1 && count != -1 {
return fmt.Errorf("Invalid value for image replica count")
return errors.New("Invalid value for image replica count")
}
return nil
@ -1081,11 +1082,11 @@ func imageMinimalReplicaValidator(value string) error {
func maxVotersValidator(value string) error {
n, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Value is not a number")
return errors.New("Value is not a number")
}
if n < 3 || n%2 != 1 {
return fmt.Errorf("Value must be an odd number equal to or higher than 3")
return errors.New("Value must be an odd number equal to or higher than 3")
}
return nil
@ -1094,11 +1095,11 @@ func maxVotersValidator(value string) error {
func maxStandByValidator(value string) error {
n, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Value is not a number")
return errors.New("Value is not a number")
}
if n < 0 || n > 5 {
return fmt.Errorf("Value must be between 0 and 5")
return errors.New("Value must be between 0 and 5")
}
return nil
@ -1107,11 +1108,11 @@ func maxStandByValidator(value string) error {
func rebalanceThresholdValidator(value string) error {
n, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("Value is not a number")
return errors.New("Value is not a number")
}
if n < 10 || n > 100 {
return fmt.Errorf("Value must be between 10 and 100")
return errors.New("Value must be between 10 and 100")
}
return nil

View File

@ -2,7 +2,7 @@ package cluster
import (
"context"
"fmt"
"errors"
"slices"
"sync"
"time"
@ -149,7 +149,7 @@ func EventListenerWait(ctx context.Context, address string) error {
if listenersUnavailable[address] {
listenersLock.Unlock()
return fmt.Errorf("Server isn't ready yet")
return errors.New("Server isn't ready yet")
}
listenAddresses := []string{address}
@ -185,7 +185,7 @@ func EventListenerWait(ctx context.Context, address string) error {
return nil
case <-ctx.Done():
if ctx.Err() != nil {
return fmt.Errorf("Missing event connection with target cluster member")
return errors.New("Missing event connection with target cluster member")
}
return nil

View File

@ -6,6 +6,7 @@ import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@ -497,7 +498,7 @@ func (g *Gateway) TransferLeadership() error {
}
if id == 0 {
return fmt.Errorf("No online voter found")
return errors.New("No online voter found")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@ -615,7 +616,7 @@ func (g *Gateway) Reset(networkCert *localtls.CertInfo) error {
}
// ErrNodeIsNotClustered indicates the node is not clustered.
var ErrNodeIsNotClustered error = fmt.Errorf("Server is not clustered")
var ErrNodeIsNotClustered error = errors.New("Server is not clustered")
// LeaderAddress returns the address of the current raft leader.
func (g *Gateway) LeaderAddress() (string, error) {
@ -692,7 +693,7 @@ func (g *Gateway) LeaderAddress() (string, error) {
// This should never happen because the raft_nodes table should
// be never empty for a clustered node, but check it for good
// measure.
return "", fmt.Errorf("No raft node known")
return "", errors.New("No raft node known")
}
transport, cleanup := tlsTransport(config)
@ -745,7 +746,7 @@ func (g *Gateway) LeaderAddress() (string, error) {
return leader, nil
}
return "", fmt.Errorf("RAFT cluster is unavailable")
return "", errors.New("RAFT cluster is unavailable")
}
// NetworkUpdateCert sets a new network certificate for the gateway
@ -772,7 +773,7 @@ func (g *Gateway) init(bootstrap bool) error {
dir := filepath.Join(g.db.Dir(), "global")
if util.PathExists(filepath.Join(dir, "logs.db")) {
return fmt.Errorf("Unsupported upgrade path, please first upgrade to LXD 4.0")
return errors.New("Unsupported upgrade path, please first upgrade to LXD 4.0")
}
// If the resulting raft instance is not nil, it means that this node
@ -908,7 +909,7 @@ func (g *Gateway) isLeader() (bool, error) {
}
// ErrNotLeader signals that a node not the leader.
var ErrNotLeader = fmt.Errorf("Not leader")
var ErrNotLeader = errors.New("Not leader")
// Return information about the cluster members that a currently part of the raft
// cluster, as configured in the raft log. It returns an error if this node is
@ -1091,7 +1092,7 @@ func dqliteNetworkDial(ctx context.Context, name string, addr string, g *Gateway
g.upgradeTriggered = true
}
}
return nil, fmt.Errorf("Upgrade needed")
return nil, errors.New("Upgrade needed")
}
if response.StatusCode != http.StatusSwitchingProtocols {
@ -1099,7 +1100,7 @@ func dqliteNetworkDial(ctx context.Context, name string, addr string, g *Gateway
}
if response.Header.Get("Upgrade") != "dqlite" {
return nil, fmt.Errorf("Missing or unexpected Upgrade header in response")
return nil, errors.New("Missing or unexpected Upgrade header in response")
}
reverter.Success()

View File

@ -470,7 +470,7 @@ func (g *Gateway) heartbeat(ctx context.Context, mode heartbeatMode) {
err = query.Retry(ctx, func(ctx context.Context) error {
// Durating cluster member fluctuations/upgrades the cluster can become unavailable so check here.
if g.Cluster == nil {
return fmt.Errorf("Cluster unavailable")
return errors.New("Cluster unavailable")
}
return g.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
@ -570,7 +570,7 @@ func HeartbeatNode(taskCtx context.Context, address string, networkCert *localtl
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("Heartbeat request failed with status: %w", api.StatusErrorf(response.StatusCode, response.Status))
return fmt.Errorf("Heartbeat request failed with status: %w", api.StatusErrorf(response.StatusCode, "%s", response.Status))
}
return nil

View File

@ -4,6 +4,7 @@ import (
"context"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"os"
"path/filepath"
@ -26,10 +27,10 @@ import (
"github.com/lxc/incus/v6/shared/util"
)
// clusterBusyError is returned by dqlite if attempting attempting to join a cluster at the same time as a role-change.
// errClusterBusy is returned by dqlite if attempting attempting to join a cluster at the same time as a role-change.
// This error tells us we can retry and probably join the cluster or fail due to something else.
// The error code here is SQLITE_BUSY.
var clusterBusyError = fmt.Errorf("A configuration change is already in progress (5)")
var errClusterBusy = errors.New("A configuration change is already in progress (5)")
// Bootstrap turns a non-clustered server into the first (and leader)
// member of a new cluster.
@ -39,7 +40,7 @@ var clusterBusyError = fmt.Errorf("A configuration change is already in progress
func Bootstrap(state *state.State, gateway *Gateway, serverName string) error {
// Check parameters
if serverName == "" {
return fmt.Errorf("Server name must not be empty")
return errors.New("Server name must not be empty")
}
err := membershipCheckNoLeftoverClusterCert(state.OS.VarDir)
@ -231,11 +232,11 @@ func EnsureServerCertificateTrusted(serverName string, serverCert *localtls.Cert
func Accept(state *state.State, gateway *Gateway, name, address string, schema, api, arch int) ([]db.RaftNode, error) {
// Check parameters
if name == "" {
return nil, fmt.Errorf("Member name must not be empty")
return nil, errors.New("Member name must not be empty")
}
if address == "" {
return nil, fmt.Errorf("Member address must not be empty")
return nil, errors.New("Member address must not be empty")
}
// Insert the new node into the nodes table.
@ -316,7 +317,7 @@ func Accept(state *state.State, gateway *Gateway, name, address string, schema,
func Join(state *state.State, gateway *Gateway, networkCert *localtls.CertInfo, serverCert *localtls.CertInfo, name string, raftNodes []db.RaftNode) error {
// Check parameters
if name == "" {
return fmt.Errorf("Member name must not be empty")
return errors.New("Member name must not be empty")
}
var localClusterAddress string
@ -447,7 +448,7 @@ func Join(state *state.State, gateway *Gateway, networkCert *localtls.CertInfo,
return fmt.Errorf("Failed to join cluster: %w", ctx.Err())
default:
err = client.Add(ctx, info.NodeInfo)
if err != nil && err.Error() == clusterBusyError.Error() {
if err != nil && err.Error() == errClusterBusy.Error() {
// If the cluster is busy with a role change, sleep a second and then keep trying to join.
time.Sleep(1 * time.Second)
continue
@ -727,7 +728,7 @@ func Assign(state *state.State, gateway *Gateway, nodes []db.RaftNode) error {
// Ensure we actually have an address.
if address == "" {
return fmt.Errorf("Cluster member is not exposed on the network")
return errors.New("Cluster member is not exposed on the network")
}
// Figure out our node identity.
@ -740,7 +741,7 @@ func Assign(state *state.State, gateway *Gateway, nodes []db.RaftNode) error {
// Ensure that our address was actually included in the given list of raft nodes.
if info == nil {
return fmt.Errorf("This member is not included in the given list of database nodes")
return errors.New("This member is not included in the given list of database nodes")
}
// Replace our local list of raft nodes with the given one (which
@ -865,7 +866,7 @@ assign:
}
}
if !notified {
return fmt.Errorf("Timeout waiting for configuration change notification")
return errors.New("Timeout waiting for configuration change notification")
}
}
@ -1133,15 +1134,15 @@ func membershipCheckNodeStateForBootstrapOrJoin(ctx context.Context, tx *db.Node
// Ensure that we're not in an inconsistent situation, where no cluster address is set, but still there
// are entries in the raft_nodes table.
if !hasClusterAddress && hasRaftNodes {
return fmt.Errorf("Inconsistent state: found leftover entries in raft_nodes")
return errors.New("Inconsistent state: found leftover entries in raft_nodes")
}
if !hasClusterAddress {
return fmt.Errorf("No cluster.https_address config is set on this member")
return errors.New("No cluster.https_address config is set on this member")
}
if hasRaftNodes {
return fmt.Errorf("The member is already part of a cluster")
return errors.New("The member is already part of a cluster")
}
return nil
@ -1156,7 +1157,7 @@ func membershipCheckClusterStateForBootstrapOrJoin(ctx context.Context, tx *db.C
}
if len(members) != 1 {
return fmt.Errorf("Inconsistent state: Found leftover entries in cluster members")
return errors.New("Inconsistent state: Found leftover entries in cluster members")
}
return nil
@ -1170,7 +1171,7 @@ func membershipCheckClusterStateForAccept(ctx context.Context, tx *db.ClusterTx,
}
if len(members) == 1 && members[0].Address == "0.0.0.0" {
return fmt.Errorf("Clustering isn't enabled")
return errors.New("Clustering isn't enabled")
}
for _, member := range members {
@ -1203,7 +1204,7 @@ func membershipCheckClusterStateForLeave(ctx context.Context, tx *db.ClusterTx,
}
if message != "" {
return fmt.Errorf(message)
return errors.New(message)
}
// Check that it's not the last member.
@ -1213,7 +1214,7 @@ func membershipCheckClusterStateForLeave(ctx context.Context, tx *db.ClusterTx,
}
if len(members) == 1 {
return fmt.Errorf("Member is the only member in the cluster")
return errors.New("Member is the only member in the cluster")
}
return nil
@ -1224,7 +1225,7 @@ func membershipCheckNoLeftoverClusterCert(dir string) error {
// Ensure that there's no leftover cluster certificate.
for _, basename := range []string{"cluster.crt", "cluster.key", "cluster.ca"} {
if util.PathExists(filepath.Join(dir, basename)) {
return fmt.Errorf("Inconsistent state: found leftover cluster certificate")
return errors.New("Inconsistent state: found leftover cluster certificate")
}
}

View File

@ -2,6 +2,7 @@ package cluster
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@ -53,13 +54,13 @@ func Recover(database *db.Node) error {
// If we're not a database node, return an error.
if info == nil {
return fmt.Errorf("This server has no database role")
return errors.New("This server has no database role")
}
// If this is a standalone node not exposed to the network, return an
// error.
if info.Address == "" {
return fmt.Errorf("This server is not clustered")
return errors.New("This server is not clustered")
}
dir := filepath.Join(database.Dir(), "global")
@ -141,7 +142,7 @@ func Reconfigure(database *db.Node, raftNodes []db.RaftNode) error {
}
if info == nil {
return fmt.Errorf("This cluster member has no raft role")
return errors.New("This cluster member has no raft role")
}
localAddress := info.Address

View File

@ -3,6 +3,7 @@ package cluster
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"time"
@ -16,11 +17,11 @@ import (
// Return a TLS configuration suitable for establishing intra-member network connections using the server cert.
func tlsClientConfig(networkCert *localtls.CertInfo, serverCert *localtls.CertInfo) (*tls.Config, error) {
if networkCert == nil {
return nil, fmt.Errorf("Invalid networkCert")
return nil, errors.New("Invalid networkCert")
}
if serverCert == nil {
return nil, fmt.Errorf("Invalid serverCert")
return nil, errors.New("Invalid serverCert")
}
keypair := serverCert.KeyPair()

View File

@ -76,7 +76,7 @@ func MaybeUpdate(state *state.State) error {
}
if state.DB.Cluster == nil {
return fmt.Errorf("Failed checking cluster update, state not initialized yet")
return errors.New("Failed checking cluster update, state not initialized yet")
}
err = state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {

View File

@ -1,6 +1,7 @@
package config
import (
"errors"
"fmt"
"reflect"
"sort"
@ -206,7 +207,7 @@ func (m *Map) set(name string, value string, initial bool) (bool, error) {
for _, r := range strings.TrimPrefix(name, "user.") {
// Only allow letters, digits, and punctuation characters.
if !unicode.In(r, unicode.Letter, unicode.Digit, unicode.Punct) {
return false, fmt.Errorf("Invalid key name")
return false, errors.New("Invalid key name")
}
}
@ -236,7 +237,7 @@ func (m *Map) set(name string, value string, initial bool) (bool, error) {
key, ok := m.schema[name]
if !ok {
return false, fmt.Errorf("unknown key")
return false, errors.New("unknown key")
}
// When unsetting a config key, the value argument will be empty.

View File

@ -1,7 +1,7 @@
package config_test
import (
"fmt"
"errors"
"strings"
"testing"
@ -313,7 +313,7 @@ func TestMap_GettersPanic(t *testing.T) {
// A Key setter that always fail.
func failingSetter(string) (string, error) {
return "", fmt.Errorf("boom")
return "", errors.New("boom")
}
// A Key setter that uppercases the value.

View File

@ -1,6 +1,7 @@
package config
import (
"errors"
"fmt"
"slices"
"sort"
@ -101,13 +102,13 @@ func (v *Key) validate(value string) error {
case String:
case Bool:
if !slices.Contains(booleans, strings.ToLower(value)) {
return fmt.Errorf("invalid boolean")
return errors.New("invalid boolean")
}
case Int64:
_, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return fmt.Errorf("invalid integer")
return errors.New("invalid integer")
}
default:

View File

@ -1,7 +1,7 @@
package config
import (
"fmt"
"errors"
"testing"
"github.com/stretchr/testify/assert"
@ -33,7 +33,7 @@ var validateCases = []struct {
// Validator that returns an error if the value is not the empty string.
func isNotEmptyString(value string) error {
if value == "" {
return fmt.Errorf("empty value not valid")
return errors.New("empty value not valid")
}
return nil
@ -57,7 +57,7 @@ var validateErrorCases = []struct {
}{
{Key{Type: Int64}, "1.2", "invalid integer"},
{Key{Type: Bool}, "yyy", "invalid boolean"},
{Key{Validator: func(string) error { return fmt.Errorf("ugh") }}, "", "ugh"},
{Key{Validator: func(string) error { return errors.New("ugh") }}, "", "ugh"},
{Key{Deprecated: "don't use this"}, "foo", "deprecated: don't use this"},
}

View File

@ -4,6 +4,7 @@ package db
import (
"context"
"errors"
"fmt"
"github.com/lxc/incus/v6/internal/server/db/cluster"
@ -54,7 +55,7 @@ WHERE cluster_groups.name = ? ORDER BY cluster_groups.name
sql = `SELECT cluster_groups.name FROM cluster_groups ORDER BY cluster_groups.name`
args = []any{}
} else {
return nil, fmt.Errorf("No statement exists for the given Filter")
return nil, errors.New("No statement exists for the given Filter")
}
names, err := query.SelectStrings(ctx, c.tx, sql, args...)

View File

@ -5,6 +5,7 @@ package cluster
import (
"context"
"database/sql"
"errors"
"fmt"
"net/http"
@ -114,7 +115,7 @@ ORDER BY certificates.fingerprint
}
if len(fingerprints) > 1 {
return nil, fmt.Errorf("More than one certificate matches")
return nil, errors.New("More than one certificate matches")
}
if len(fingerprints) == 0 {

Some files were not shown because too many files have changed in this diff Show More