AB#2033 Remove redundant "failed" in error wrapping

Remove "failed" from wrapped errors
Where appropriate rephrase "unable to/could not" to "failed" in root
errors
Start error log messages with "Failed"
This commit is contained in:
Christoph Meyer 2022-06-09 14:04:30 +00:00 committed by cm
parent 0c9ca50be8
commit 9441e46e4b
56 changed files with 204 additions and 204 deletions

View File

@ -107,7 +107,7 @@ func (c *Client) updateAppCredentials(ctx context.Context, objectID string) (str
keyID := uuid.New().String()
clientSecret, err := generateClientSecret()
if err != nil {
return "", fmt.Errorf("generating client secret failed: %w", err)
return "", fmt.Errorf("generating client secret: %w", err)
}
updateParameters := graphrbac.PasswordCredentialsUpdateParameters{
Value: &[]graphrbac.PasswordCredential{

View File

@ -69,7 +69,7 @@ func (c *ServiceAccountCreator) createServiceAccountGCP(ctx context.Context, cl
stat state.ConstellationState, config *config.Config,
) (string, state.ConstellationState, error) {
if err := cl.SetState(stat); err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to set state while creating service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("setting state while creating service account: %w", err)
}
input := gcpcl.ServiceAccountInput{
@ -77,12 +77,12 @@ func (c *ServiceAccountCreator) createServiceAccountGCP(ctx context.Context, cl
}
serviceAccount, err := cl.CreateServiceAccount(ctx, input)
if err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to create service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("creating service account: %w", err)
}
stat, err = cl.GetState()
if err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to get state after creating service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("getting state after creating service account: %w", err)
}
return serviceAccount, stat, nil
}
@ -91,16 +91,16 @@ func (c *ServiceAccountCreator) createServiceAccountAzure(ctx context.Context, c
stat state.ConstellationState, config *config.Config,
) (string, state.ConstellationState, error) {
if err := cl.SetState(stat); err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to set state while creating service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("setting state while creating service account: %w", err)
}
serviceAccount, err := cl.CreateServicePrincipal(ctx)
if err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to create service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("creating service account: %w", err)
}
stat, err = cl.GetState()
if err != nil {
return "", state.ConstellationState{}, fmt.Errorf("failed to get state after creating service account: %w", err)
return "", state.ConstellationState{}, fmt.Errorf("getting state after creating service account: %w", err)
}
return serviceAccount, stat, nil
}

View File

@ -127,7 +127,7 @@ func initialize(ctx context.Context, cmd *cobra.Command, protCl protoClient, ser
return err
}
if err := waiter.WaitForAll(ctx, endpoints, coordinatorstate.AcceptingInit); err != nil {
return fmt.Errorf("failed to wait for peer status: %w", err)
return fmt.Errorf("waiting for all peers status: %w", err)
}
var autoscalingNodeGroups []string
@ -161,7 +161,7 @@ func initialize(ctx context.Context, cmd *cobra.Command, protCl protoClient, ser
}
if err := writeWGQuickFile(fileHandler, vpnHandler, vpnConfig); err != nil {
return fmt.Errorf("write wg-quick file: %w", err)
return fmt.Errorf("writing wg-quick file: %w", err)
}
if flags.autoconfigureWG {

View File

@ -71,7 +71,7 @@ func verify(ctx context.Context, cmd *cobra.Command, provider cloudprovider.Prov
}
if _, err := protoClient.GetState(ctx); err != nil {
if err, ok := rpcStatus.FromError(err); ok {
return fmt.Errorf("unable to verify Constellation cluster: %s", err.Message())
return fmt.Errorf("verifying Constellation cluster: %s", err.Message())
}
return err
}

View File

@ -42,7 +42,7 @@ func (c *Client) CreateInstances(ctx context.Context, input CreateInstancesInput
}
op, err := c.insertInstanceTemplate(ctx, nodeTemplateInput)
if err != nil {
return fmt.Errorf("inserting instanceTemplate failed: %w", err)
return fmt.Errorf("inserting instanceTemplate: %w", err)
}
ops = append(ops, op)
c.nodeTemplate = nodeTemplateInput.Name
@ -64,7 +64,7 @@ func (c *Client) CreateInstances(ctx context.Context, input CreateInstancesInput
}
op, err = c.insertInstanceTemplate(ctx, coordinatorTemplateInput)
if err != nil {
return fmt.Errorf("inserting instanceTemplate failed: %w", err)
return fmt.Errorf("inserting instanceTemplate: %w", err)
}
ops = append(ops, op)
c.coordinatorTemplate = coordinatorTemplateInput.Name
@ -83,7 +83,7 @@ func (c *Client) CreateInstances(ctx context.Context, input CreateInstancesInput
}
op, err = c.insertInstanceGroupManger(ctx, coordinatorGroupInput)
if err != nil {
return fmt.Errorf("inserting instanceGroupManager failed: %w", err)
return fmt.Errorf("inserting instanceGroupManager: %w", err)
}
ops = append(ops, op)
c.coordinatorInstanceGroup = coordinatorGroupInput.Name
@ -98,7 +98,7 @@ func (c *Client) CreateInstances(ctx context.Context, input CreateInstancesInput
}
op, err = c.insertInstanceGroupManger(ctx, nodeGroupInput)
if err != nil {
return fmt.Errorf("inserting instanceGroupManager failed: %w", err)
return fmt.Errorf("inserting instanceGroupManager: %w", err)
}
ops = append(ops, op)
c.nodesInstanceGroup = nodeGroupInput.Name
@ -108,18 +108,18 @@ func (c *Client) CreateInstances(ctx context.Context, input CreateInstancesInput
}
if err := c.waitForInstanceGroupScaling(ctx, c.nodesInstanceGroup); err != nil {
return fmt.Errorf("waiting for instanceGroupScaling failed: %w", err)
return fmt.Errorf("waiting for instanceGroupScaling: %w", err)
}
if err := c.waitForInstanceGroupScaling(ctx, c.coordinatorInstanceGroup); err != nil {
return fmt.Errorf("waiting for instanceGroupScaling failed: %w", err)
return fmt.Errorf("waiting for instanceGroupScaling: %w", err)
}
if err := c.getInstanceIPs(ctx, c.nodesInstanceGroup, c.nodes); err != nil {
return fmt.Errorf("failed to get instanceIPs: %w", err)
return fmt.Errorf("getting instanceIPs: %w", err)
}
if err := c.getInstanceIPs(ctx, c.coordinatorInstanceGroup, c.coordinators); err != nil {
return fmt.Errorf("failed to get instanceIPs: %w", err)
return fmt.Errorf("getting instanceIPs: %w", err)
}
return nil
}
@ -130,7 +130,7 @@ func (c *Client) TerminateInstances(ctx context.Context) error {
if c.nodesInstanceGroup != "" {
op, err := c.deleteInstanceGroupManager(ctx, c.nodesInstanceGroup)
if err != nil {
return fmt.Errorf("deleting instanceGroupManager '%s' failed: %w", c.nodesInstanceGroup, err)
return fmt.Errorf("deleting instanceGroupManager '%s': %w", c.nodesInstanceGroup, err)
}
ops = append(ops, op)
c.nodesInstanceGroup = ""
@ -140,7 +140,7 @@ func (c *Client) TerminateInstances(ctx context.Context) error {
if c.coordinatorInstanceGroup != "" {
op, err := c.deleteInstanceGroupManager(ctx, c.coordinatorInstanceGroup)
if err != nil {
return fmt.Errorf("deleting instanceGroupManager '%s' failed: %w", c.coordinatorInstanceGroup, err)
return fmt.Errorf("deleting instanceGroupManager '%s': %w", c.coordinatorInstanceGroup, err)
}
ops = append(ops, op)
c.coordinatorInstanceGroup = ""
@ -154,7 +154,7 @@ func (c *Client) TerminateInstances(ctx context.Context) error {
if c.nodeTemplate != "" {
op, err := c.deleteInstanceTemplate(ctx, c.nodeTemplate)
if err != nil {
return fmt.Errorf("deleting instanceTemplate failed: %w", err)
return fmt.Errorf("deleting instanceTemplate: %w", err)
}
ops = append(ops, op)
c.nodeTemplate = ""
@ -162,7 +162,7 @@ func (c *Client) TerminateInstances(ctx context.Context) error {
if c.coordinatorTemplate != "" {
op, err := c.deleteInstanceTemplate(ctx, c.coordinatorTemplate)
if err != nil {
return fmt.Errorf("deleting instanceTemplate failed: %w", err)
return fmt.Errorf("deleting instanceTemplate: %w", err)
}
ops = append(ops, op)
c.coordinatorTemplate = ""

View File

@ -14,7 +14,7 @@ func (c *Client) addIAMPolicyBindings(ctx context.Context, input AddIAMPolicyBin
}
policy, err := c.projectsAPI.GetIamPolicy(ctx, getReq)
if err != nil {
return fmt.Errorf("retrieving current iam policy failed: %w", err)
return fmt.Errorf("retrieving current iam policy: %w", err)
}
for _, binding := range input.Bindings {
addIAMPolicy(policy, binding)
@ -24,7 +24,7 @@ func (c *Client) addIAMPolicyBindings(ctx context.Context, input AddIAMPolicyBin
Policy: policy,
}
if _, err := c.projectsAPI.SetIamPolicy(ctx, setReq); err != nil {
return fmt.Errorf("setting new iam policy failed: %w", err)
return fmt.Errorf("setting new iam policy: %w", err)
}
return nil
}

View File

@ -43,7 +43,7 @@ func (c *Client) TerminateServiceAccount(ctx context.Context) error {
Name: "projects/-/serviceAccounts/" + c.serviceAccount,
}
if err := c.iamAPI.DeleteServiceAccount(ctx, req); err != nil {
return fmt.Errorf("deleting service account failed: %w", err)
return fmt.Errorf("deleting service account: %w", err)
}
c.serviceAccount = ""
}
@ -81,11 +81,11 @@ func (c *Client) createServiceAccountKey(ctx context.Context, email string) (gcp
req := createServiceAccountKeyRequest(email)
key, err := c.iamAPI.CreateServiceAccountKey(ctx, req)
if err != nil {
return gcpshared.ServiceAccountKey{}, fmt.Errorf("creating service account key failed: %w", err)
return gcpshared.ServiceAccountKey{}, fmt.Errorf("creating service account key: %w", err)
}
var serviceAccountKey gcpshared.ServiceAccountKey
if err := json.Unmarshal(key.PrivateKeyData, &serviceAccountKey); err != nil {
return gcpshared.ServiceAccountKey{}, fmt.Errorf("decoding service account key JSON failed: %w", err)
return gcpshared.ServiceAccountKey{}, fmt.Errorf("decoding service account key JSON: %w", err)
}
return serviceAccountKey, nil

View File

@ -63,12 +63,12 @@ func (m Metadata) Supported() bool {
func retrieveIdentityDocument(ctx context.Context) (*imds.GetInstanceIdentityDocumentOutput, error) {
cfg, err := config.LoadDefaultConfig(ctx)
if err != nil {
return nil, fmt.Errorf("unable to load default AWS configuration: %w", err)
return nil, fmt.Errorf("loading default AWS configuration: %w", err)
}
client := imds.NewFromConfig(cfg)
identityDocument, err := client.GetInstanceIdentityDocument(ctx, &imds.GetInstanceIdentityDocumentInput{})
if err != nil {
return nil, fmt.Errorf("unable to retrieve AWS instance identity document: %w", err)
return nil, fmt.Errorf("retrieving AWS instance identity document: %w", err)
}
return identityDocument, nil
}

View File

@ -126,7 +126,7 @@ func (m *Metadata) GetInstance(ctx context.Context, providerID string) (cloudtyp
if scaleSetErr == nil {
return instance, nil
}
return cloudtypes.Instance{}, fmt.Errorf("could not retrieve instance given providerID %v as either single vm or scale set vm: %v %v", providerID, singleErr, scaleSetErr)
return cloudtypes.Instance{}, fmt.Errorf("retrieving instance given providerID %v as either single vm or scale set vm: %v; %v", providerID, singleErr, scaleSetErr)
}
// SignalRole signals the constellation role via cloud provider metadata.

View File

@ -20,7 +20,7 @@ func (m *Metadata) getVMInterfaces(ctx context.Context, vm armcompute.VirtualMac
for _, interfaceName := range interfaceNames {
networkInterfacesResp, err := m.networkInterfacesAPI.Get(ctx, resourceGroup, interfaceName, nil)
if err != nil {
return nil, fmt.Errorf("failed to retrieve network interface %v: %w", interfaceName, err)
return nil, fmt.Errorf("retrieving network interface %v: %w", interfaceName, err)
}
networkInterfaces = append(networkInterfaces, networkInterfacesResp.Interface)
}
@ -37,7 +37,7 @@ func (m *Metadata) getScaleSetVMInterfaces(ctx context.Context, vm armcompute.Vi
for _, interfaceName := range interfaceNames {
networkInterfacesResp, err := m.networkInterfacesAPI.GetVirtualMachineScaleSetNetworkInterface(ctx, resourceGroup, scaleSet, instanceID, interfaceName, nil)
if err != nil {
return nil, fmt.Errorf("failed to retrieve network interface %v: %w", interfaceName, err)
return nil, fmt.Errorf("retrieving network interface %v: %w", interfaceName, err)
}
networkInterfaces = append(networkInterfaces, networkInterfacesResp.Interface)
}

View File

@ -56,7 +56,7 @@ func (c *Client) RetrieveInstances(ctx context.Context, project, zone string) ([
break
}
if err != nil {
return nil, fmt.Errorf("retrieving instance list from compute API client failed: %w", err)
return nil, fmt.Errorf("retrieving instance list from compute API client: %w", err)
}
metadata := extractInstanceMetadata(resp.Metadata, "", false)
// skip instances not belonging to the current constellation
@ -112,7 +112,7 @@ func (c *Client) RetrieveInstanceName() (string, error) {
func (c *Client) RetrieveInstanceMetadata(attr string) (string, error) {
value, err := c.metadataAPI.InstanceAttributeValue(attr)
if err != nil {
return "", fmt.Errorf("requesting GCP instance metadata failed: %w", err)
return "", fmt.Errorf("requesting GCP instance metadata: %w", err)
}
return value, nil
}
@ -121,7 +121,7 @@ func (c *Client) RetrieveInstanceMetadata(attr string) (string, error) {
func (c *Client) SetInstanceMetadata(ctx context.Context, project, zone, instanceName, key, value string) error {
instance, err := c.getComputeInstance(ctx, project, zone, instanceName)
if err != nil {
return fmt.Errorf("retrieving instance metadata failed: %w", err)
return fmt.Errorf("retrieving instance metadata: %w", err)
}
if instance == nil || instance.Metadata == nil {
return fmt.Errorf("retrieving instance metadata returned invalid results")
@ -134,7 +134,7 @@ func (c *Client) SetInstanceMetadata(ctx context.Context, project, zone, instanc
metadata := flattenInstanceMetadata(metadataMap, instance.Metadata.Fingerprint, instance.Metadata.Kind)
if err := c.updateInstanceMetadata(ctx, project, zone, instanceName, metadata); err != nil {
return fmt.Errorf("setting instance metadata %v: %v failed with: %w", key, value, err)
return fmt.Errorf("setting instance metadata %v: %v: %w", key, value, err)
}
return nil
}
@ -143,7 +143,7 @@ func (c *Client) SetInstanceMetadata(ctx context.Context, project, zone, instanc
func (c *Client) UnsetInstanceMetadata(ctx context.Context, project, zone, instanceName, key string) error {
instance, err := c.getComputeInstance(ctx, project, zone, instanceName)
if err != nil {
return fmt.Errorf("retrieving instance metadata failed: %w", err)
return fmt.Errorf("retrieving instance metadata: %w", err)
}
if instance == nil || instance.Metadata == nil {
return fmt.Errorf("retrieving instance metadata returned invalid results")
@ -157,7 +157,7 @@ func (c *Client) UnsetInstanceMetadata(ctx context.Context, project, zone, insta
metadata := flattenInstanceMetadata(metadataMap, instance.Metadata.Fingerprint, instance.Metadata.Kind)
if err := c.updateInstanceMetadata(ctx, project, zone, instanceName, metadata); err != nil {
return fmt.Errorf("unsetting instance metadata key %v failed with: %w", key, err)
return fmt.Errorf("unsetting instance metadata key %v: %w", key, err)
}
return nil
}
@ -212,7 +212,7 @@ func (c *Client) getComputeInstance(ctx context.Context, project, zone, instance
}
instance, err := c.instanceAPI.Get(ctx, instanceGetReq)
if err != nil {
return nil, fmt.Errorf("retrieving compute instance failed: %w", err)
return nil, fmt.Errorf("retrieving compute instance: %w", err)
}
return instance, nil
}
@ -227,7 +227,7 @@ func (c *Client) updateInstanceMetadata(ctx context.Context, project, zone, inst
}
if _, err := c.instanceAPI.SetMetadata(ctx, setMetadataReq); err != nil {
return fmt.Errorf("updating instance metadata failed: %w", err)
return fmt.Errorf("updating instance metadata: %w", err)
}
return nil
}
@ -237,7 +237,7 @@ func (c *Client) uid() (string, error) {
// API endpoint: http://metadata.google.internal/computeMetadata/v1/instance/attributes/constellation-uid
uid, err := c.RetrieveInstanceMetadata(core.ConstellationUIDMetadataKey)
if err != nil {
return "", fmt.Errorf("retrieving constellation uid failed: %w", err)
return "", fmt.Errorf("retrieving constellation uid: %w", err)
}
return uid, nil
}

View File

@ -56,7 +56,7 @@ func (m *Metadata) List(ctx context.Context) ([]cloudtypes.Instance, error) {
}
instances, err := m.api.RetrieveInstances(ctx, project, zone)
if err != nil {
return nil, fmt.Errorf("retrieving instances list from GCP api failed: %w", err)
return nil, fmt.Errorf("retrieving instances list from GCP api: %w", err)
}
return instances, nil
}

View File

@ -14,7 +14,7 @@ type Writer struct {
// WriteGCEConf persists the GCE config on disk.
func (w *Writer) WriteGCEConf(config string) error {
if err := w.fs.WriteFile("/etc/gce.conf", []byte(config), 0o644); err != nil {
return fmt.Errorf("writing gce config failed: %w", err)
return fmt.Errorf("writing gce config: %w", err)
}
return nil
}

View File

@ -92,7 +92,7 @@ func main() {
gcpClient, err := gcpcloud.NewClient(context.Background())
if err != nil {
log.Fatalf("creating GCP client failed: %v\n", err)
log.Fatalf("failed to create GCP client: %v\n", err)
}
metadata := gcpcloud.New(gcpClient)
descr, err := metadata.Self(context.Background())

View File

@ -99,7 +99,7 @@ func run(issuer core.QuoteIssuer, vpn core.VPN, tpm vtpm.TPMOpenFunc, getPublicI
func tryJoinClusterOnStartup(getPublicIPAddr func() (string, error), metadata core.ProviderMetadata, logger *zap.Logger) error {
nodePublicIP, err := getPublicIPAddr()
if err != nil {
return fmt.Errorf("failed to retrieve own public ip: %w", err)
return fmt.Errorf("retrieving own public ip: %w", err)
}
if !metadata.Supported() {
logger.Info("Metadata API not implemented for cloud provider")
@ -107,7 +107,7 @@ func tryJoinClusterOnStartup(getPublicIPAddr func() (string, error), metadata co
}
coordinatorEndpoints, err := core.CoordinatorEndpoints(context.TODO(), metadata)
if err != nil {
return fmt.Errorf("failed to retrieve coordinatorEndpoints from cloud provider api: %w", err)
return fmt.Errorf("retrieving coordinatorEndpoints from cloud provider api: %w", err)
}
logger.Info("Retrieved endpoints from cloud-provider API", zap.Strings("endpoints", coordinatorEndpoints))

View File

@ -68,7 +68,7 @@ func CoordinatorEndpoints(ctx context.Context, metadata ProviderMetadata) ([]str
}
instances, err := metadata.List(ctx)
if err != nil {
return nil, fmt.Errorf("retrieving instances list from cloud provider failed: %w", err)
return nil, fmt.Errorf("retrieving instances list from cloud provider: %w", err)
}
coordinatorEndpoints := []string{}
for _, instance := range instances {

View File

@ -178,12 +178,12 @@ func (c *Core) NotifyNodeHeartbeat(addr net.Addr) {
func (c *Core) Initialize(ctx context.Context, dialer Dialer, api PubAPI) (nodeActivated bool, err error) {
nodeActivated, err = vtpm.IsNodeInitialized(c.openTPM)
if err != nil {
return false, fmt.Errorf("failed to check for previous activation using vTPM: %w", err)
return false, fmt.Errorf("checking for previous activation using vTPM: %w", err)
}
if !nodeActivated {
c.zaplogger.Info("Node was never activated. Allowing node to be activated.")
if err := c.vpn.Setup(nil); err != nil {
return false, fmt.Errorf("failed to setup VPN: %w", err)
return false, fmt.Errorf("VPN setup: %w", err)
}
c.state.Advance(state.AcceptingInit)
return false, nil
@ -191,15 +191,15 @@ func (c *Core) Initialize(ctx context.Context, dialer Dialer, api PubAPI) (nodeA
c.zaplogger.Info("Node was previously activated. Attempting re-join.")
nodeState, err := nodestate.FromFile(c.fileHandler)
if err != nil {
return false, fmt.Errorf("failed to read node state: %w", err)
return false, fmt.Errorf("reading node state: %w", err)
}
if err := c.vpn.Setup(nodeState.VPNPrivKey); err != nil {
return false, fmt.Errorf("failed to setup VPN: %w", err)
return false, fmt.Errorf("VPN setup: %w", err)
}
// restart kubernetes
if err := c.kube.StartKubelet(); err != nil {
return false, fmt.Errorf("failed to start kubelet service: %w", err)
return false, fmt.Errorf("starting kubelet service: %w", err)
}
var initialState state.State
@ -214,7 +214,7 @@ func (c *Core) Initialize(ctx context.Context, dialer Dialer, api PubAPI) (nodeA
return false, fmt.Errorf("invalid node role for initialized node: %v", nodeState.Role)
}
if err != nil {
return false, fmt.Errorf("reinit failed: %w", err)
return false, fmt.Errorf("reinit: %w", err)
}
c.zaplogger.Info("Re-join successful.")
@ -226,7 +226,7 @@ func (c *Core) Initialize(ctx context.Context, dialer Dialer, api PubAPI) (nodeA
func (c *Core) PersistNodeState(role role.Role, vpnIP string, ownerID []byte, clusterID []byte) error {
vpnPrivKey, err := c.vpn.GetPrivateKey()
if err != nil {
return fmt.Errorf("failed to retrieve VPN private key: %w", err)
return fmt.Errorf("retrieving VPN private key: %w", err)
}
nodeState := nodestate.NodeState{
Role: role,

View File

@ -8,7 +8,7 @@ import (
// GetDiskUUID gets the disk's UUID.
func (c *Core) GetDiskUUID() (string, error) {
if err := c.encryptedDisk.Open(); err != nil {
return "", fmt.Errorf("retrieving uuid of encrypted disk failed: cannot open disk: %w", err)
return "", fmt.Errorf("retrieving uuid of encrypted disk: cannot open disk: %w", err)
}
defer c.encryptedDisk.Close()
uuid, err := c.encryptedDisk.UUID()
@ -21,7 +21,7 @@ func (c *Core) GetDiskUUID() (string, error) {
// UpdateDiskPassphrase switches the initial random passphrase of the encrypted disk to a permanent passphrase.
func (c *Core) UpdateDiskPassphrase(passphrase string) error {
if err := c.encryptedDisk.Open(); err != nil {
return fmt.Errorf("updating passphrase of encrypted disk failed: cannot open disk: %w", err)
return fmt.Errorf("updating passphrase of encrypted disk: cannot open disk: %w", err)
}
defer c.encryptedDisk.Close()
return c.encryptedDisk.UpdatePassphrase(passphrase)

View File

@ -117,7 +117,7 @@ func getInitialVPNPeers(ctx context.Context, dialer Dialer, logger *zap.Logger,
defer cancel()
conn, err := dialer.Dial(callCTX, coordinatorEndpoint)
if err != nil {
logger.Warn("getting VPN peer information from coordinator failed: dialing failed: ", zap.String("endpoint", coordinatorEndpoint), zap.Error(err))
logger.Warn("failed getting VPN peer information from coordinator: dialing failed: ", zap.String("endpoint", coordinatorEndpoint), zap.Error(err))
continue
}
defer conn.Close()

View File

@ -51,7 +51,7 @@ func (c *Cryptsetup) Open() error {
var err error
c.device, err = c.initByName(stateMapperDevice)
if err != nil {
return fmt.Errorf("unable to initialize crypt device for mapped device %q: %w", stateMapperDevice, err)
return fmt.Errorf("initializing crypt device for mapped device %q: %w", stateMapperDevice, err)
}
return nil
}
@ -96,7 +96,7 @@ func (c *Cryptsetup) UpdatePassphrase(passphrase string) error {
return err
}
if err := c.device.KeyslotChangeByPassphrase(keyslot, keyslot, initialPassphrase, passphrase); err != nil {
return fmt.Errorf("unable to change passphrase for mapped device %q: %w", stateMapperDevice, err)
return fmt.Errorf("changing passphrase for mapped device %q: %w", stateMapperDevice, err)
}
return nil
}
@ -105,7 +105,7 @@ func (c *Cryptsetup) UpdatePassphrase(passphrase string) error {
func (c *Cryptsetup) getInitialPassphrase() (string, error) {
passphrase, err := afero.ReadFile(c.fs, initialKeyPath)
if err != nil {
return "", fmt.Errorf("unable to read first boot encryption passphrase from disk: %w", err)
return "", fmt.Errorf("reading first boot encryption passphrase from disk: %w", err)
}
return string(passphrase), nil
}

View File

@ -51,7 +51,7 @@ func (i *osInstaller) Install(
err = i.copy(tempPath, destination, perm)
}
if err != nil {
return fmt.Errorf("installing from %q failed: copying to destination %q failed: %w", sourceURL, destination, err)
return fmt.Errorf("installing from %q: copying to destination %q: %w", sourceURL, destination, err)
}
}
return nil
@ -61,16 +61,16 @@ func (i *osInstaller) Install(
func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMode) error {
archiveFile, err := i.fs.Open(archivePath)
if err != nil {
return fmt.Errorf("unable to open archive file: %w", err)
return fmt.Errorf("opening archive file: %w", err)
}
defer archiveFile.Close()
gzReader, err := gzip.NewReader(archiveFile)
if err != nil {
return fmt.Errorf("unable to read archive file as gzip: %w", err)
return fmt.Errorf("reading archive file as gzip: %w", err)
}
defer gzReader.Close()
if err := i.fs.MkdirAll(prefix, fs.ModePerm); err != nil {
return fmt.Errorf("unable to create prefix folder: %w", err)
return fmt.Errorf("creating prefix folder: %w", err)
}
tarReader := tar.NewReader(gzReader)
@ -80,10 +80,10 @@ func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMod
return nil
}
if err != nil {
return fmt.Errorf("unable to parse tar header: %w", err)
return fmt.Errorf("parsing tar header: %w", err)
}
if err := verifyTarPath(header.Name); err != nil {
return fmt.Errorf("invalid tar path %q: %w", header.Name, err)
return fmt.Errorf("verifying tar path %q: %w", header.Name, err)
}
switch header.Typeflag {
case tar.TypeDir:
@ -91,7 +91,7 @@ func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMod
return errors.New("cannot create dir for empty path")
}
if err := i.fs.Mkdir(path.Join(prefix, header.Name), fs.FileMode(header.Mode)&perm); err != nil && !errors.Is(err, os.ErrExist) {
return fmt.Errorf("unable to create folder: %w", err)
return fmt.Errorf("creating folder %s: %w", path.Join(prefix, header.Name), err)
}
case tar.TypeReg:
if len(header.Name) == 0 {
@ -99,11 +99,11 @@ func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMod
}
out, err := i.fs.OpenFile(path.Join(prefix, header.Name), os.O_WRONLY|os.O_CREATE, fs.FileMode(header.Mode))
if err != nil {
return fmt.Errorf("unable to create file for writing: %w", err)
return fmt.Errorf("creating file %s for writing: %w", path.Join(prefix, header.Name), err)
}
defer out.Close()
if _, err := io.Copy(out, tarReader); err != nil {
return fmt.Errorf("unable to write extracted file contents: %w", err)
return fmt.Errorf("writing extracted file contents: %w", err)
}
case tar.TypeSymlink:
if err := verifyTarPath(header.Linkname); err != nil {
@ -117,7 +117,7 @@ func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMod
}
if symlinker, ok := i.fs.Fs.(afero.Symlinker); ok {
if err := symlinker.SymlinkIfPossible(path.Join(prefix, header.Name), path.Join(prefix, header.Linkname)); err != nil {
return fmt.Errorf("creating symlink failed: %w", err)
return fmt.Errorf("creating symlink: %w", err)
}
} else {
return errors.New("fs does not support symlinks")
@ -132,16 +132,16 @@ func (i *osInstaller) extractArchive(archivePath, prefix string, perm fs.FileMod
func (i *osInstaller) downloadToTempDir(ctx context.Context, url string, transforms ...transform.Transformer) (string, error) {
out, err := afero.TempFile(i.fs, "", "")
if err != nil {
return "", fmt.Errorf("unable to create destination temp file: %w", err)
return "", fmt.Errorf("creating destination temp file: %w", err)
}
defer out.Close()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", fmt.Errorf("request to download %q failed: %w", url, err)
return "", fmt.Errorf("request to download %q: %w", url, err)
}
resp, err := i.hClient.Do(req)
if err != nil {
return "", fmt.Errorf("request to download %q failed: %w", url, err)
return "", fmt.Errorf("request to download %q: %w", url, err)
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("request to download %q failed with status code: %v", url, resp.Status)
@ -151,7 +151,7 @@ func (i *osInstaller) downloadToTempDir(ctx context.Context, url string, transfo
transformReader := transform.NewReader(resp.Body, transform.Chain(transforms...))
if _, err = io.Copy(out, transformReader); err != nil {
return "", fmt.Errorf("downloading %q failed: %w", url, err)
return "", fmt.Errorf("downloading %q: %w", url, err)
}
return out.Name(), nil
}
@ -160,16 +160,16 @@ func (i *osInstaller) downloadToTempDir(ctx context.Context, url string, transfo
func (i *osInstaller) copy(oldname, newname string, perm fs.FileMode) (err error) {
old, openOldErr := i.fs.OpenFile(oldname, os.O_RDONLY, fs.ModePerm)
if openOldErr != nil {
return fmt.Errorf("unable to copy %q to %q: cannot open source file for reading: %w", oldname, newname, openOldErr)
return fmt.Errorf("copying %q to %q: cannot open source file for reading: %w", oldname, newname, openOldErr)
}
defer func() { _ = old.Close() }()
// create destination path if not exists
if err := i.fs.MkdirAll(path.Dir(newname), fs.ModePerm); err != nil {
return fmt.Errorf("unable to copy %q to %q: unable to create destination folder: %w", oldname, newname, err)
return fmt.Errorf("copying %q to %q: unable to create destination folder: %w", oldname, newname, err)
}
new, openNewErr := i.fs.OpenFile(newname, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, perm)
if openNewErr != nil {
return fmt.Errorf("unable to copy %q to %q: cannot open destination file for writing: %w", oldname, newname, openNewErr)
return fmt.Errorf("copying %q to %q: cannot open destination file for writing: %w", oldname, newname, openNewErr)
}
defer func() {
_ = new.Close()
@ -178,7 +178,7 @@ func (i *osInstaller) copy(oldname, newname string, perm fs.FileMode) (err error
}
}()
if _, err := io.Copy(new, old); err != nil {
return fmt.Errorf("unable to copy %q to %q: copying file contents failed: %w", oldname, newname, err)
return fmt.Errorf("copying %q to %q: copying file contents: %w", oldname, newname, err)
}
return nil

View File

@ -34,7 +34,7 @@ func ParseJoinCommand(joinCommand string) (*kubeadm.BootstrapTokenDiscovery, err
flags.Bool("control-plane", false, "")
flags.String("certificate-key", "", "")
if err := flags.Parse(argv[3:]); err != nil {
return nil, fmt.Errorf("parsing flag arguments failed: %v %w", argv, err)
return nil, fmt.Errorf("parsing flag arguments: %v %w", argv, err)
}
if result.Token == "" {

View File

@ -26,16 +26,16 @@ type Client struct {
func New(config []byte) (*Client, error) {
clientConfig, err := clientcmd.RESTConfigFromKubeConfig(config)
if err != nil {
return nil, fmt.Errorf("creating k8s client config from kubeconfig failed: %w", err)
return nil, fmt.Errorf("creating k8s client config from kubeconfig: %w", err)
}
clientset, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, fmt.Errorf("creating k8s client from kubeconfig failed: %w", err)
return nil, fmt.Errorf("creating k8s client from kubeconfig: %w", err)
}
restClientGetter, err := newRESTClientGetter(config)
if err != nil {
return nil, fmt.Errorf("creating k8s RESTClientGetter from kubeconfig failed: %w", err)
return nil, fmt.Errorf("creating k8s RESTClientGetter from kubeconfig: %w", err)
}
builder := resource.NewBuilder(restClientGetter).Unstructured()
@ -51,7 +51,7 @@ func (c *Client) ApplyOneObject(info *resource.Info, forceConflicts bool) error
// server-side-apply uses unstructured JSON instead of strict typing on the client side.
data, err := runtime.Encode(unstructured.UnstructuredJSONScheme, info.Object)
if err != nil {
return fmt.Errorf("preparing resource for server-side apply failed: encoding of resource failed: %w", err)
return fmt.Errorf("preparing resource for server-side apply: encoding of resource: %w", err)
}
options := metav1.PatchOptions{
Force: &forceConflicts,
@ -64,7 +64,7 @@ func (c *Client) ApplyOneObject(info *resource.Info, forceConflicts bool) error
&options,
)
if err != nil {
return fmt.Errorf("failed to apply object %v using server-side apply: %w", info, err)
return fmt.Errorf("applying object %v using server-side apply: %w", info, err)
}
return info.Refresh(obj, true)
@ -75,7 +75,7 @@ func (c *Client) GetObjects(resources resources.Marshaler) ([]*resource.Info, er
// convert our resource struct into YAML
data, err := resources.Marshal()
if err != nil {
return nil, fmt.Errorf("converting resources to YAML failed: %w", err)
return nil, fmt.Errorf("converting resources to YAML: %w", err)
}
// read into resource.Info using builder
reader := bytes.NewReader(data)

View File

@ -55,7 +55,7 @@ func (k *Kubectl) Apply(resources resources.Marshaler, forceConflicts bool) erro
// apply each object, one by one
for i, resource := range infos {
if err := client.ApplyOneObject(resource, forceConflicts); err != nil {
return fmt.Errorf("kubectl apply of object %v/%v failed: %w", i, len(infos), err)
return fmt.Errorf("kubectl apply of object %v/%v: %w", i, len(infos), err)
}
}

View File

@ -78,7 +78,7 @@ func UnmarshalK8SResources(data []byte, into any) error {
decoder := serializer.NewCodecFactory(scheme.Scheme).UniversalDecoder()
documents, err := splitYAML(data)
if err != nil {
return fmt.Errorf("unable to split deployment YAML into multiple documents: %w", err)
return fmt.Errorf("splitting deployment YAML into multiple documents: %w", err)
}
if len(documents) != value.NumField() {
return fmt.Errorf("expected %v YAML documents, got %v", value.NumField(), len(documents))

View File

@ -10,12 +10,12 @@ import (
func restartSystemdUnit(ctx context.Context, unit string) error {
conn, err := dbus.NewSystemdConnectionContext(ctx)
if err != nil {
return fmt.Errorf("establishing systemd connection failed: %w", err)
return fmt.Errorf("establishing systemd connection: %w", err)
}
restartChan := make(chan string)
if _, err := conn.RestartUnitContext(ctx, unit, "replace", restartChan); err != nil {
return fmt.Errorf("restarting systemd unit %q failed: %w", unit, err)
return fmt.Errorf("restarting systemd unit %q: %w", unit, err)
}
// Wait for the restart to finish and actually check if it was
@ -34,12 +34,12 @@ func restartSystemdUnit(ctx context.Context, unit string) error {
func startSystemdUnit(ctx context.Context, unit string) error {
conn, err := dbus.NewSystemdConnectionContext(ctx)
if err != nil {
return fmt.Errorf("establishing systemd connection failed: %w", err)
return fmt.Errorf("establishing systemd connection: %w", err)
}
startChan := make(chan string)
if _, err := conn.StartUnitContext(ctx, unit, "replace", startChan); err != nil {
return fmt.Errorf("starting systemd unit %q failed: %w", unit, err)
return fmt.Errorf("starting systemd unit %q: %w", unit, err)
}
// Wait for the enable to finish and actually check if it was
@ -58,11 +58,11 @@ func startSystemdUnit(ctx context.Context, unit string) error {
func enableSystemdUnit(ctx context.Context, unitPath string) error {
conn, err := dbus.NewSystemdConnectionContext(ctx)
if err != nil {
return fmt.Errorf("establishing systemd connection failed: %w", err)
return fmt.Errorf("establishing systemd connection: %w", err)
}
if _, _, err := conn.EnableUnitFilesContext(ctx, []string{unitPath}, true, true); err != nil {
return fmt.Errorf("enabling systemd unit %q failed: %w", unitPath, err)
return fmt.Errorf("enabling systemd unit %q: %w", unitPath, err)
}
return nil
}

View File

@ -80,20 +80,20 @@ func (k *KubernetesUtil) InitCluster(ctx context.Context, initConfig []byte) err
// TODO: audit policy should be user input
auditPolicy, err := resources.NewDefaultAuditPolicy().Marshal()
if err != nil {
return fmt.Errorf("failed to generate default audit policy: %w", err)
return fmt.Errorf("generating default audit policy: %w", err)
}
if err := os.WriteFile(auditPolicyPath, auditPolicy, 0o644); err != nil {
return fmt.Errorf("failed to write default audit policy: %w", err)
return fmt.Errorf("writing default audit policy: %w", err)
}
initConfigFile, err := os.CreateTemp("", "kubeadm-init.*.yaml")
if err != nil {
return fmt.Errorf("failed to create init config file %v: %w", initConfigFile.Name(), err)
return fmt.Errorf("creating init config file %v: %w", initConfigFile.Name(), err)
}
defer os.Remove(initConfigFile.Name())
if _, err := initConfigFile.Write(initConfig); err != nil {
return fmt.Errorf("writing kubeadm init yaml config %v failed: %w", initConfigFile.Name(), err)
return fmt.Errorf("writing kubeadm init yaml config %v: %w", initConfigFile.Name(), err)
}
cmd := exec.CommandContext(ctx, kubeadmPath, "init", "--config", initConfigFile.Name())
@ -103,7 +103,7 @@ func (k *KubernetesUtil) InitCluster(ctx context.Context, initConfig []byte) err
if errors.As(err, &exitErr) {
return fmt.Errorf("kubeadm init failed (code %v) with: %s", exitErr.ExitCode(), exitErr.Stderr)
}
return fmt.Errorf("kubeadm init failed: %w", err)
return fmt.Errorf("kubeadm init: %w", err)
}
return nil
}
@ -227,7 +227,7 @@ func (k *KubernetesUtil) setupQemuPodNetwork(ctx context.Context) error {
// SetupAutoscaling deploys the k8s cluster autoscaler.
func (k *KubernetesUtil) SetupAutoscaling(kubectl Client, clusterAutoscalerConfiguration resources.Marshaler, secrets resources.Marshaler) error {
if err := kubectl.Apply(secrets, true); err != nil {
return fmt.Errorf("applying cluster-autoscaler Secrets failed: %w", err)
return fmt.Errorf("applying cluster-autoscaler Secrets: %w", err)
}
return kubectl.Apply(clusterAutoscalerConfiguration, true)
}
@ -240,13 +240,13 @@ func (k *KubernetesUtil) SetupActivationService(kubectl Client, activationServic
// SetupCloudControllerManager deploys the k8s cloud-controller-manager.
func (k *KubernetesUtil) SetupCloudControllerManager(kubectl Client, cloudControllerManagerConfiguration resources.Marshaler, configMaps resources.Marshaler, secrets resources.Marshaler) error {
if err := kubectl.Apply(configMaps, true); err != nil {
return fmt.Errorf("applying ccm ConfigMaps failed: %w", err)
return fmt.Errorf("applying ccm ConfigMaps: %w", err)
}
if err := kubectl.Apply(secrets, true); err != nil {
return fmt.Errorf("applying ccm Secrets failed: %w", err)
return fmt.Errorf("applying ccm Secrets: %w", err)
}
if err := kubectl.Apply(cloudControllerManagerConfiguration, true); err != nil {
return fmt.Errorf("applying ccm failed: %w", err)
return fmt.Errorf("applying ccm: %w", err)
}
return nil
}
@ -266,20 +266,20 @@ func (k *KubernetesUtil) JoinCluster(ctx context.Context, joinConfig []byte) err
// TODO: audit policy should be user input
auditPolicy, err := resources.NewDefaultAuditPolicy().Marshal()
if err != nil {
return fmt.Errorf("failed to generate default audit policy: %w", err)
return fmt.Errorf("generating default audit policy: %w", err)
}
if err := os.WriteFile(auditPolicyPath, auditPolicy, 0o644); err != nil {
return fmt.Errorf("failed to write default audit policy: %w", err)
return fmt.Errorf("writing default audit policy: %w", err)
}
joinConfigFile, err := os.CreateTemp("", "kubeadm-join.*.yaml")
if err != nil {
return fmt.Errorf("failed to create join config file %v: %w", joinConfigFile.Name(), err)
return fmt.Errorf("creating join config file %v: %w", joinConfigFile.Name(), err)
}
defer os.Remove(joinConfigFile.Name())
if _, err := joinConfigFile.Write(joinConfig); err != nil {
return fmt.Errorf("writing kubeadm init yaml config %v failed: %w", joinConfigFile.Name(), err)
return fmt.Errorf("writing kubeadm init yaml config %v: %w", joinConfigFile.Name(), err)
}
// run `kubeadm join` to join a worker node to an existing Kubernetes cluster
@ -289,7 +289,7 @@ func (k *KubernetesUtil) JoinCluster(ctx context.Context, joinConfig []byte) err
if errors.As(err, &exitErr) {
return fmt.Errorf("kubeadm join failed (code %v) with: %s", exitErr.ExitCode(), exitErr.Stderr)
}
return fmt.Errorf("kubeadm join failed: %w", err)
return fmt.Errorf("kubeadm join: %w", err)
}
return nil
@ -298,7 +298,7 @@ func (k *KubernetesUtil) JoinCluster(ctx context.Context, joinConfig []byte) err
// SetupKMS deploys the KMS deployment.
func (k *KubernetesUtil) SetupKMS(kubectl Client, kmsConfiguration resources.Marshaler) error {
if err := kubectl.Apply(kmsConfiguration, true); err != nil {
return fmt.Errorf("applying KMS configuration failed: %w", err)
return fmt.Errorf("applying KMS configuration: %w", err)
}
return nil
}
@ -308,7 +308,7 @@ func (k *KubernetesUtil) StartKubelet() error {
ctx, cancel := context.WithTimeout(context.TODO(), kubeletStartTimeout)
defer cancel()
if err := enableSystemdUnit(ctx, kubeletServiceEtcPath); err != nil {
return fmt.Errorf("enabling kubelet systemd unit failed: %w", err)
return fmt.Errorf("enabling kubelet systemd unit: %w", err)
}
return startSystemdUnit(ctx, "kubelet.service")
}
@ -331,7 +331,7 @@ func (k *KubernetesUtil) GetControlPlaneJoinCertificateKey(ctx context.Context)
if errors.As(err, &exitErr) {
return "", fmt.Errorf("kubeadm upload-certs failed (code %v) with: %s", exitErr.ExitCode(), exitErr.Stderr)
}
return "", fmt.Errorf("kubeadm upload-certs failed: %w", err)
return "", fmt.Errorf("kubeadm upload-certs: %w", err)
}
// Example output:
/*
@ -350,7 +350,7 @@ func (k *KubernetesUtil) GetControlPlaneJoinCertificateKey(ctx context.Context)
func (k *KubernetesUtil) CreateJoinToken(ctx context.Context, ttl time.Duration) (*kubeadm.BootstrapTokenDiscovery, error) {
output, err := exec.CommandContext(ctx, kubeadmPath, "token", "create", "--ttl", ttl.String(), "--print-join-command").Output()
if err != nil {
return nil, fmt.Errorf("kubeadm token create failed: %w", err)
return nil, fmt.Errorf("kubeadm token create: %w", err)
}
// `kubeadm token create [...] --print-join-command` outputs the following format:
// kubeadm join [API_SERVER_ENDPOINT] --token [TOKEN] --discovery-token-ca-cert-hash [DISCOVERY_TOKEN_CA_CERT_HASH]

View File

@ -52,37 +52,37 @@ func (k *kubernetesVersion) installK8sComponents(ctx context.Context, inst insta
if err := inst.Install(
ctx, k.CNIPluginsURL, []string{cniPluginsDir}, executablePerm, true,
); err != nil {
return fmt.Errorf("failed to install cni plugins: %w", err)
return fmt.Errorf("installing cni plugins: %w", err)
}
if err := inst.Install(
ctx, k.CrictlURL, []string{binDir}, executablePerm, true,
); err != nil {
return fmt.Errorf("failed to install crictl: %w", err)
return fmt.Errorf("installing crictl: %w", err)
}
if err := inst.Install(
ctx, k.KubeletServiceURL, []string{kubeletServiceEtcPath, kubeletServiceStatePath}, systemdUnitPerm, false, replace.String("/usr/bin", binDir),
); err != nil {
return fmt.Errorf("failed to install kubelet service: %w", err)
return fmt.Errorf("installing kubelet service: %w", err)
}
if err := inst.Install(
ctx, k.KubeadmConfURL, []string{kubeadmConfEtcPath, kubeadmConfStatePath}, systemdUnitPerm, false, replace.String("/usr/bin", binDir),
); err != nil {
return fmt.Errorf("failed to install kubeadm conf: %w", err)
return fmt.Errorf("installing kubeadm conf: %w", err)
}
if err := inst.Install(
ctx, k.KubeletURL, []string{kubeletPath}, executablePerm, false,
); err != nil {
return fmt.Errorf("failed to install kubelet: %w", err)
return fmt.Errorf("installing kubelet: %w", err)
}
if err := inst.Install(
ctx, k.KubeadmURL, []string{kubeadmPath}, executablePerm, false,
); err != nil {
return fmt.Errorf("failed to install kubeadm: %w", err)
return fmt.Errorf("installing kubeadm: %w", err)
}
if err := inst.Install(
ctx, k.KubectlURL, []string{kubectlPath}, executablePerm, false,
); err != nil {
return fmt.Errorf("failed to install kubectl: %w", err)
return fmt.Errorf("installing kubectl: %w", err)
}
return nil
}

View File

@ -17,7 +17,7 @@ type KubeconfigReader struct {
func (r KubeconfigReader) ReadKubeconfig() ([]byte, error) {
kubeconfig, err := r.fs.ReadFile(kubeconfigPath)
if err != nil {
return nil, fmt.Errorf("reading gce config failed: %w", err)
return nil, fmt.Errorf("reading gce config: %w", err)
}
return kubeconfig, nil
}

View File

@ -118,14 +118,14 @@ func (k *KubeWrapper) InitCluster(
initConfig.SetControlPlaneEndpoint(controlPlaneEndpointIP)
initConfigYAML, err := initConfig.Marshal()
if err != nil {
return fmt.Errorf("encoding kubeadm init configuration as YAML failed: %w", err)
return fmt.Errorf("encoding kubeadm init configuration as YAML: %w", err)
}
if err := k.clusterUtil.InitCluster(ctx, initConfigYAML); err != nil {
return fmt.Errorf("kubeadm init failed: %w", err)
return fmt.Errorf("kubeadm init: %w", err)
}
kubeConfig, err := k.GetKubeconfig()
if err != nil {
return fmt.Errorf("reading kubeconfig after cluster initialization failed: %w", err)
return fmt.Errorf("reading kubeconfig after cluster initialization: %w", err)
}
k.client.SetKubeconfig(kubeConfig)
@ -139,12 +139,12 @@ func (k *KubeWrapper) InitCluster(
ProviderID: providerID,
}
if err = k.clusterUtil.SetupPodNetwork(ctx, setupPodNetworkInput); err != nil {
return fmt.Errorf("setup of pod network failed: %w", err)
return fmt.Errorf("setting up pod network: %w", err)
}
kms := resources.NewKMSDeployment(masterSecret)
if err = k.clusterUtil.SetupKMS(k.client, kms); err != nil {
return fmt.Errorf("setup of kms failed: %w", err)
return fmt.Errorf("setting up kms: %w", err)
}
if err := k.setupActivationService(k.cloudProvider, k.initialMeasurementsJSON, id); err != nil {
@ -152,14 +152,14 @@ func (k *KubeWrapper) InitCluster(
}
if err := k.setupCCM(context.TODO(), vpnIP, subnetworkPodCIDR, cloudServiceAccountURI, instance); err != nil {
return fmt.Errorf("setting up cloud controller manager failed: %w", err)
return fmt.Errorf("setting up cloud controller manager: %w", err)
}
if err := k.setupCloudNodeManager(); err != nil {
return fmt.Errorf("setting up cloud node manager failed: %w", err)
return fmt.Errorf("setting up cloud node manager: %w", err)
}
if err := k.setupClusterAutoscaler(instance, cloudServiceAccountURI, autoscalingNodeGroups); err != nil {
return fmt.Errorf("setting up cluster autoscaler failed: %w", err)
return fmt.Errorf("setting up cluster autoscaler: %w", err)
}
accessManager := resources.NewAccessManagerDeployment(sshUsers)
@ -216,10 +216,10 @@ func (k *KubeWrapper) JoinCluster(ctx context.Context, args *kubeadm.BootstrapTo
}
joinConfigYAML, err := joinConfig.Marshal()
if err != nil {
return fmt.Errorf("encoding kubeadm join configuration as YAML failed: %w", err)
return fmt.Errorf("encoding kubeadm join configuration as YAML: %w", err)
}
if err := k.clusterUtil.JoinCluster(ctx, joinConfigYAML); err != nil {
return fmt.Errorf("joining cluster failed: %v %w ", string(joinConfigYAML), err)
return fmt.Errorf("joining cluster: %v; %w ", string(joinConfigYAML), err)
}
go k.clusterUtil.FixCilium(nodeName)

View File

@ -23,7 +23,7 @@ type NodeState struct {
func FromFile(fileHandler file.Handler) (*NodeState, error) {
nodeState := &NodeState{}
if err := fileHandler.ReadJSON(nodeStatePath, nodeState); err != nil {
return nil, fmt.Errorf("could not load node state: %w", err)
return nil, fmt.Errorf("loading node state: %w", err)
}
return nodeState, nil
}

View File

@ -105,7 +105,7 @@ func (a *API) ActivateAsCoordinator(in *pubproto.ActivateAsCoordinatorRequest, s
id := attestationtypes.ID{Owner: ownerID, Cluster: clusterID}
kubeconfig, err := a.core.InitCluster(context.TODO(), in.AutoscalingNodeGroups, in.CloudServiceAccountUri, id, in.MasterSecret, in.SshUserKeys)
if err != nil {
return status.Errorf(codes.Internal, "initializing Kubernetes cluster failed: %v", err)
return status.Errorf(codes.Internal, "initializing Kubernetes cluster: %v", err)
}
// run the VPN-API server
@ -206,7 +206,7 @@ func (a *API) RequestStateDiskKey(ctx context.Context, in *pubproto.RequestState
}
key, err := a.core.GetDataKey(ctx, in.DiskUuid, config.RNGLengthDefault)
if err != nil {
return nil, status.Errorf(codes.Internal, "unable to load key: %v", err)
return nil, status.Errorf(codes.Internal, "getting data key: %v", err)
}
peer, err := a.peerFromContext(ctx)
@ -394,12 +394,12 @@ func (a *API) activateNode(nodePublicIP string, nodeVPNIP string, initialPeers [
func (a *API) assemblePeerStruct(vpnIP string, _ role.Role) (peer.Peer, error) {
vpnPubKey, err := a.core.GetVPNPubKey()
if err != nil {
a.logger.Error("could not get key", zap.Error(err))
a.logger.Error("failed to get VPN pub key", zap.Error(err))
return peer.Peer{}, err
}
publicIP, err := a.getPublicIPAddr()
if err != nil {
a.logger.Error("could not get public IP", zap.Error(err))
a.logger.Error("failed to get public IP", zap.Error(err))
return peer.Peer{}, err
}
return peer.Peer{

View File

@ -224,7 +224,7 @@ func (a *API) activateCoordinator(ctx context.Context, coordinatorIP string, ssh
for _, p := range peers {
if p.Role == role.Coordinator && p.VPNIP != thisPeer.VPNIP {
if err := a.triggerCoordinatorUpdate(context.TODO(), p.PublicIP); err != nil {
a.logger.Error("triggerCoordinatorUpdate failed", zap.Error(err), zap.String("endpoint", p.PublicIP), zap.String("vpnip", p.VPNIP))
a.logger.Error("failed to trigger coordinator update", zap.Error(err), zap.String("endpoint", p.PublicIP), zap.String("vpnip", p.VPNIP))
}
}
}
@ -263,7 +263,7 @@ func (a *API) TriggerCoordinatorUpdate(ctx context.Context, in *pubproto.Trigger
func (a *API) GetPeerVPNPublicKey(ctx context.Context, in *pubproto.GetPeerVPNPublicKeyRequest) (*pubproto.GetPeerVPNPublicKeyResponse, error) {
key, err := a.core.GetVPNPubKey()
if err != nil {
return nil, status.Errorf(codes.Internal, "could not obtain VPNPubKey %v", err)
return nil, status.Errorf(codes.Internal, "obtaining VPNPubKey: %v", err)
}
return &pubproto.GetPeerVPNPublicKeyResponse{CoordinatorPubKey: key}, nil
}

View File

@ -65,7 +65,7 @@ func (a *API) ActivateAsNode(stream pubproto.API_ActivateAsNodeServer) (reterr e
*/
message, err := stream.Recv()
if err != nil {
return status.Errorf(codes.Internal, "could not receive initial request from coordinator: %v", err)
return status.Errorf(codes.Internal, "receiving initial request from coordinator: %v", err)
}
initialRequest, ok := message.GetRequest().(*pubproto.ActivateAsNodeRequest_InitialRequest)
if !ok {
@ -137,7 +137,7 @@ func (a *API) ActivateAsNode(stream pubproto.API_ActivateAsNodeServer) (reterr e
*/
message, err = stream.Recv()
if err != nil {
return status.Errorf(codes.Internal, "could not receive state disk key from coordinator: %v", err)
return status.Errorf(codes.Internal, "failed to receive state disk key from coordinator: %v", err)
}
diskKey, ok := message.GetRequest().(*pubproto.ActivateAsNodeRequest_StateDiskKey)
if !ok {

View File

@ -13,7 +13,7 @@ import (
func (a *API) GetVPNPeers(context.Context, *pubproto.GetVPNPeersRequest) (*pubproto.GetVPNPeersResponse, error) {
_, peers, err := a.core.GetPeers(0)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get peers: %v", err)
return nil, status.Errorf(codes.Internal, "getting peers: %v", err)
}
return &pubproto.GetVPNPeersResponse{

View File

@ -53,11 +53,11 @@ func GetIPAddr() (string, error) {
func GetInterfaceIP(netInterface string) (string, error) {
netif, err := net.InterfaceByName(netInterface)
if err != nil {
return "", fmt.Errorf("could not find interface %s: %w", netInterface, err)
return "", fmt.Errorf("finding interface %s: %w", netInterface, err)
}
addrs, err := netif.Addrs()
if err != nil {
return "", fmt.Errorf("could not retrieve interface ip addresses %s: %w", netInterface, err)
return "", fmt.Errorf("retrieving interface ip addresses %s: %w", netInterface, err)
}
for _, addr := range addrs {
if ipn, ok := addr.(*net.IPNet); ok {

View File

@ -52,7 +52,7 @@ func (w *Wireguard) Setup(privKey []byte) error {
func (w *Wireguard) GetPrivateKey() ([]byte, error) {
device, err := w.client.Device(netInterface)
if err != nil {
return nil, fmt.Errorf("unable to retrieve wireguard private key from device %v: %w", netInterface, err)
return nil, fmt.Errorf("retrieving wireguard private key from device %v: %w", netInterface, err)
}
return device.PrivateKey[:], nil
}
@ -150,12 +150,12 @@ func prettyWgError(err error) error {
func (w *Wireguard) UpdatePeers(peers []peer.Peer) error {
wgPeers, err := transformToWgpeer(peers)
if err != nil {
return fmt.Errorf("failed to transform peers to wireguard-peers: %w", err)
return fmt.Errorf("transforming peers to wireguard-peers: %w", err)
}
deviceData, err := w.client.Device(netInterface)
if err != nil {
return fmt.Errorf("failed to obtain device data: %w", err)
return fmt.Errorf("obtaining device data: %w", err)
}
// convert to map for easier lookup
storePeers := make(map[string]wgtypes.Peer)

View File

@ -42,7 +42,7 @@ func runDeploy(cmd *cobra.Command, args []string) error {
}
configName, err := cmd.Flags().GetString("config")
if err != nil {
return err
return fmt.Errorf("parsing config path argument: %w", err)
}
fileHandler := file.NewHandler(afero.NewOsFs())
debugConfig, err := config.FromFile(fileHandler, debugConfigName)
@ -78,9 +78,9 @@ func deploy(cmd *cobra.Command, fileHandler file.Handler, constellationConfig *c
err := fileHandler.ReadJSON(constants.StateFilename, &stat)
if errors.Is(err, fs.ErrNotExist) {
log.Println("Unable to load statefile. Maybe you forgot to run \"constellation create ...\" first?")
return fmt.Errorf("loading statefile failed: %w", err)
return fmt.Errorf("loading statefile: %w", err)
} else if err != nil {
return fmt.Errorf("loading statefile failed: %w", err)
return fmt.Errorf("loading statefile: %w", err)
}
ips, err = getIPsFromConfig(stat, *constellationConfig)
if err != nil {
@ -119,7 +119,7 @@ func deployOnEndpoint(ctx context.Context, in deployOnEndpointInput) error {
defer cancel()
conn, err := grpc.DialContext(dialCTX, in.debugdEndpoint, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return fmt.Errorf("error connecting to other instance via gRPC: %w", err)
return fmt.Errorf("connecting to other instance via gRPC: %w", err)
}
defer conn.Close()
client := pb.NewDebugdClient(conn)
@ -155,13 +155,13 @@ func deployOnEndpoint(ctx context.Context, in deployOnEndpointInput) error {
stream, err := client.UploadCoordinator(ctx)
if err != nil {
return fmt.Errorf("starting coordinator upload to instance %v failed: %w", in.debugdEndpoint, err)
return fmt.Errorf("starting coordinator upload to instance %v: %w", in.debugdEndpoint, err)
}
streamErr := in.reader.ReadStream(in.coordinatorPath, stream, debugd.Chunksize, true)
uploadResponse, closeErr := stream.CloseAndRecv()
if closeErr != nil {
return fmt.Errorf("closing upload stream after uploading coordinator to %v failed: %w", in.debugdEndpoint, closeErr)
return fmt.Errorf("closing upload stream after uploading coordinator to %v: %w", in.debugdEndpoint, closeErr)
}
if uploadResponse.Status == pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_FILE_EXISTS {
log.Println("Coordinator was already uploaded")

View File

@ -27,9 +27,9 @@ func FromFile(fileHandler file.Handler, name string) (*CDBGConfig, error) {
conf := &CDBGConfig{}
if err := fileHandler.ReadYAML(name, conf); err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("unable to find %s - consult the README on how to setup cdbg", name)
return nil, fmt.Errorf("%s not found - consult the README on how to setup cdbg", name)
}
return nil, fmt.Errorf("could not load config from file %s: %w", name, err)
return nil, fmt.Errorf("loading config from file %s: %w", name, err)
}
return conf, nil
}

View File

@ -41,14 +41,14 @@ func (f *FileStreamer) WriteStream(filename string, stream ReadChunkStream, show
// try to read from stream once before acquiring write lock
chunk, err := stream.Recv()
if err != nil {
return fmt.Errorf("reading stream failed: %w", err)
return fmt.Errorf("reading stream: %w", err)
}
f.mux.Lock()
defer f.mux.Unlock()
file, err := f.fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755)
if err != nil {
return fmt.Errorf("open %v for writing failed: %w", filename, err)
return fmt.Errorf("open %v for writing: %w", filename, err)
}
defer file.Close()
@ -70,12 +70,12 @@ func (f *FileStreamer) WriteStream(filename string, stream ReadChunkStream, show
}
_ = file.Close()
_ = f.fs.Remove(filename)
return fmt.Errorf("reading stream failed: %w", err)
return fmt.Errorf("reading stream: %w", err)
}
if _, err := file.Write(chunk.Content); err != nil {
_ = file.Close()
_ = f.fs.Remove(filename)
return fmt.Errorf("writing chunk to disk failed: %w", err)
return fmt.Errorf("writing chunk to disk: %w", err)
}
if showProgress {
_ = bar.Add(len(chunk.Content))
@ -99,7 +99,7 @@ func (f *FileStreamer) ReadStream(filename string, stream WriteChunkStream, chun
}
file, err := f.fs.OpenFile(filename, os.O_RDONLY, 0o755)
if err != nil {
return fmt.Errorf("open %v for reading failed: %w", filename, err)
return fmt.Errorf("open %v for reading: %w", filename, err)
}
defer file.Close()
@ -107,7 +107,7 @@ func (f *FileStreamer) ReadStream(filename string, stream WriteChunkStream, chun
if showProgress {
stat, err := file.Stat()
if err != nil {
return fmt.Errorf("performing stat on %v to get the file size failed: %w", filename, err)
return fmt.Errorf("performing stat on %v to get the file size: %w", filename, err)
}
bar = progressbar.NewOptions64(
stat.Size(),
@ -125,11 +125,11 @@ func (f *FileStreamer) ReadStream(filename string, stream WriteChunkStream, chun
if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("reading file chunk failed: %w", err)
return fmt.Errorf("reading file chunk: %w", err)
}
if err = stream.Send(&pb.Chunk{Content: buf[:n]}); err != nil {
return fmt.Errorf("sending chunk failed: %w", err)
return fmt.Errorf("sending chunk: %w", err)
}
if showProgress {
_ = bar.Add(n)

View File

@ -43,17 +43,17 @@ func (d *Download) DownloadCoordinator(ctx context.Context, ip string) error {
d.attemptedDownloads[serverAddr] = time.Now()
conn, err := d.dial(ctx, serverAddr)
if err != nil {
return fmt.Errorf("error connecting to other instance via gRPC: %w", err)
return fmt.Errorf("connecting to other instance via gRPC: %w", err)
}
defer conn.Close()
client := pb.NewDebugdClient(conn)
stream, err := client.DownloadCoordinator(ctx, &pb.DownloadCoordinatorRequest{})
if err != nil {
return fmt.Errorf("starting coordinator download from other instance failed: %w", err)
return fmt.Errorf("starting coordinator download from other instance: %w", err)
}
if err := d.writer.WriteStream(debugd.CoordinatorDeployFilename, stream, true); err != nil {
return fmt.Errorf("streaming coordinator from other instance failed: %w", err)
return fmt.Errorf("streaming coordinator from other instance: %w", err)
}
log.Printf("Successfully downloaded coordinator from %s\n", ip)
@ -64,7 +64,7 @@ func (d *Download) DownloadCoordinator(ctx context.Context, ip string) error {
Action: Restart,
}
if err := d.serviceManager.SystemdAction(ctx, restartAction); err != nil {
return fmt.Errorf("restarting coordinator failed: %w", err)
return fmt.Errorf("restarting coordinator: %w", err)
}
return nil

View File

@ -157,7 +157,7 @@ func (f *fakeStreamToFileWriter) WriteStream(filename string, stream coordinator
if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("reading stream failed: %w", err)
return fmt.Errorf("reading stream: %w", err)
}
f.chunks = append(f.chunks, chunk.Content)
}
@ -173,7 +173,7 @@ type fakeOnlyDownloadServer struct {
func (f *fakeOnlyDownloadServer) DownloadCoordinator(request *pb.DownloadCoordinatorRequest, stream pb.Debugd_DownloadCoordinatorServer) error {
for _, chunk := range f.chunks {
if err := stream.Send(&pb.Chunk{Content: chunk}); err != nil {
return fmt.Errorf("sending chunk failed: %w", err)
return fmt.Errorf("sending chunk: %w", err)
}
}
return f.downladErr

View File

@ -80,7 +80,7 @@ type dbusConn interface {
func (s *ServiceManager) SystemdAction(ctx context.Context, request ServiceManagerRequest) error {
conn, err := s.dbus.NewSystemdConnectionContext(ctx)
if err != nil {
return fmt.Errorf("establishing systemd connection failed: %w", err)
return fmt.Errorf("establishing systemd connection: %w", err)
}
resultChan := make(chan string)
@ -97,7 +97,7 @@ func (s *ServiceManager) SystemdAction(ctx context.Context, request ServiceManag
return errors.New("unknown systemd action: " + request.Action.String())
}
if err != nil {
return fmt.Errorf("failed to perform systemd action %v on unit %v: %w", request.Action, request.Unit, err)
return fmt.Errorf("performing systemd action %v on unit %v: %w", request.Action, request.Unit, err)
}
if request.Action == Reload {
@ -124,11 +124,11 @@ func (s *ServiceManager) WriteSystemdUnitFile(ctx context.Context, unit SystemdU
s.systemdUnitFilewriteLock.Lock()
defer s.systemdUnitFilewriteLock.Unlock()
if err := afero.WriteFile(s.fs, fmt.Sprintf("%s/%s", systemdUnitFolder, unit.Name), []byte(unit.Contents), 0o644); err != nil {
return fmt.Errorf("writing systemd unit file \"%v\" failed: %w", unit.Name, err)
return fmt.Errorf("writing systemd unit file \"%v\": %w", unit.Name, err)
}
if err := s.SystemdAction(ctx, ServiceManagerRequest{Unit: unit.Name, Action: Reload}); err != nil {
return fmt.Errorf("performing systemd daemon-reload failed: %w", err)
return fmt.Errorf("performing systemd daemon-reload: %w", err)
}
log.Printf("Wrote systemd unit file: %s/%s and performed daemon-reload\n", systemdUnitFolder, unit.Name)
@ -142,7 +142,7 @@ func DeployDefaultServiceUnit(ctx context.Context, serviceManager *ServiceManage
Name: debugd.CoordinatorSystemdUnitName,
Contents: debugd.CoordinatorSystemdUnitContents,
}); err != nil {
return fmt.Errorf("writing systemd unit file %q failed: %w", debugd.CoordinatorSystemdUnitName, err)
return fmt.Errorf("writing systemd unit file %q: %w", debugd.CoordinatorSystemdUnitName, err)
}
// try to start the default service if the binary exists but ignore failure.

View File

@ -51,11 +51,11 @@ func NewAzure(ctx context.Context) (*Fetcher, error) {
func (f *Fetcher) DiscoverDebugdIPs(ctx context.Context) ([]string, error) {
self, err := f.metaAPI.Self(ctx)
if err != nil {
return nil, fmt.Errorf("retrieving own instance failed: %w", err)
return nil, fmt.Errorf("retrieving own instance: %w", err)
}
instances, err := f.metaAPI.List(ctx)
if err != nil {
return nil, fmt.Errorf("retrieving instances failed: %w", err)
return nil, fmt.Errorf("retrieving instances: %w", err)
}
// filter own instance from instance list
for i, instance := range instances {
@ -75,7 +75,7 @@ func (f *Fetcher) DiscoverDebugdIPs(ctx context.Context) ([]string, error) {
func (f *Fetcher) FetchSSHKeys(ctx context.Context) ([]ssh.UserKey, error) {
self, err := f.metaAPI.Self(ctx)
if err != nil {
return nil, fmt.Errorf("retrieving ssh keys from cloud provider metadata failed: %w", err)
return nil, fmt.Errorf("retrieving ssh keys from cloud provider metadata: %w", err)
}
keys := []ssh.UserKey{}

View File

@ -77,7 +77,7 @@ func (s *debugdServer) UploadCoordinator(stream pb.Debugd_UploadCoordinatorServe
}
log.Printf("Uploading coordinator failed: %v\n", err)
responseStatus = pb.UploadCoordinatorStatus_UPLOAD_COORDINATOR_UPLOAD_FAILED
return fmt.Errorf("uploading coordinator failed: %w", err)
return fmt.Errorf("uploading coordinator: %w", err)
}
log.Println("Successfully uploaded coordinator")
@ -110,7 +110,7 @@ func Start(wg *sync.WaitGroup, serv pb.DebugdServer) {
pb.RegisterDebugdServer(grpcServer, serv)
lis, err := net.Listen("tcp", net.JoinHostPort("0.0.0.0", debugd.DebugdPort))
if err != nil {
log.Fatalf("failed to listen: %v", err)
log.Fatalf("listening failed: %v", err)
}
log.Println("gRPC server is waiting for connections")
grpcServer.Serve(lis)

View File

@ -381,7 +381,7 @@ func (f *fakeStreamer) WriteStream(filename string, stream coordinator.ReadChunk
if errors.Is(err, io.EOF) {
return f.writeStreamErr
}
return fmt.Errorf("reading stream failed: %w", err)
return fmt.Errorf("reading stream: %w", err)
}
f.writeStreamChunks = append(f.writeStreamChunks, chunk.Content)
}

View File

@ -27,11 +27,11 @@ func terraformOut(workspaceDir string) (terraformOutput, error) {
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return terraformOutput{}, fmt.Errorf("failed to run terraform output: %q: %w", stderr.String(), err)
return terraformOutput{}, fmt.Errorf("command terraform output failed: %q: %w", stderr.String(), err)
}
var tfOut terraformOutput
if err := json.Unmarshal(stdout.Bytes(), &tfOut); err != nil {
return terraformOutput{}, fmt.Errorf("failed to unmarshal terraform output: %w", err)
return terraformOutput{}, fmt.Errorf("unmarshaling terraform output: %w", err)
}
return tfOut, nil
}
@ -62,11 +62,11 @@ func transformState(tfOut terraformOutput) state.ConstellationState {
func writeState(workspaceDir string, conState state.ConstellationState) error {
rawState, err := json.Marshal(conState)
if err != nil {
return fmt.Errorf("failed to marshal state: %w", err)
return fmt.Errorf("marshaling state: %w", err)
}
stateFile := fmt.Sprintf("%s/constellation-state.json", workspaceDir)
if err := os.WriteFile(stateFile, rawState, 0o644); err != nil {
return fmt.Errorf("failed to write state: %w", err)
return fmt.Errorf("writing state: %w", err)
}
return nil
}

View File

@ -68,7 +68,7 @@ func trustedKeyFromGCEAPI(getClient func(ctx context.Context, opts ...option.Cli
defer cancel()
client, err := getClient(ctx)
if err != nil {
return nil, fmt.Errorf("unable to create GCE client: %w", err)
return nil, fmt.Errorf("creating GCE client: %w", err)
}
defer client.Close()
@ -78,7 +78,7 @@ func trustedKeyFromGCEAPI(getClient func(ctx context.Context, opts ...option.Cli
Zone: instanceInfo.GetZone(),
})
if err != nil {
return nil, fmt.Errorf("could not retrieve VM identity: %w", err)
return nil, fmt.Errorf("retrieving VM identity: %w", err)
}
if instance.SigningKey == nil || instance.SigningKey.EkPub == nil {

View File

@ -45,7 +45,7 @@ func (u Unix) CreateUserWithSpecificUIDAndGID(ctx context.Context, username stri
if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == exitCodeAlreadyInUse {
return ErrUserOrGroupAlreadyExists
}
return fmt.Errorf("creating a new user failed: %w", err)
return fmt.Errorf("creating a new user: %w", err)
}
return nil
}

View File

@ -164,11 +164,11 @@ func (l *LinuxUserManager) GetLinuxUser(username string) (LinuxUser, error) {
entry := entries[username]
uid, err := strconv.Atoi(entry.Uid)
if err != nil {
return LinuxUser{}, fmt.Errorf("failed to parse users uid: %w", err)
return LinuxUser{}, fmt.Errorf("parsing users uid: %w", err)
}
gid, err := strconv.Atoi(entry.Gid)
if err != nil {
return LinuxUser{}, fmt.Errorf("failed to parse users gid: %w", err)
return LinuxUser{}, fmt.Errorf("parsing users gid: %w", err)
}
return LinuxUser{
Username: username,

View File

@ -86,7 +86,7 @@ func (c *KMSClient) CreateKEK(ctx context.Context, keyID string, key []byte) err
var err error
key, err = util.GetRandomKey(config.SymmetricKeyLength)
if err != nil {
return fmt.Errorf("could not generate key: %w", err)
return fmt.Errorf("key generation: %w", err)
}
}
@ -118,7 +118,7 @@ func (c *KMSClient) GetDEK(ctx context.Context, kekID, keyID string, dekSize int
// If the DEK does not exist we generate a new random DEK and save it to storage
newDEK, err := util.GetRandomKey(dekSize)
if err != nil {
return nil, fmt.Errorf("could not generate key: %w", err)
return nil, fmt.Errorf("key generation: %w", err)
}
return newDEK, c.putDEK(ctx, keyID, kek, newDEK)
}

View File

@ -130,7 +130,7 @@ func (c *HSMClient) GetDEK(ctx context.Context, kekID string, keyID string, dekS
// If the DEK does not exist we generate a new random DEK and save it to storage
newDEK, err := util.GetRandomKey(dekSize)
if err != nil {
return nil, fmt.Errorf("could not generate key: %w", err)
return nil, fmt.Errorf("key generation: %w", err)
}
if err := c.putDEK(ctx, kekID, keyID, newDEK); err != nil {
return nil, fmt.Errorf("creating new DEK: %w", err)

View File

@ -118,7 +118,7 @@ func (c *KMSClient) GetDEK(ctx context.Context, kekID, keyID string, dekSize int
// If the DEK does not exist we generate a new random DEK and save it to storage
newDEK, err := util.GetRandomKey(dekSize)
if err != nil {
return nil, fmt.Errorf("could not generate key: %w", err)
return nil, fmt.Errorf("key generation: %w", err)
}
return newDEK, c.putDEK(ctx, client, kekID, keyID, newDEK)
}
@ -217,7 +217,7 @@ func (c *KMSClient) importKEK(ctx context.Context, keyID string, key []byte, cli
}
wrappedKey, err := wrapCryptoKey(key, wrappingPublicKey)
if err != nil {
return nil, fmt.Errorf("unable to wrap key: %w", err)
return nil, fmt.Errorf("wrapping public key: %w", err)
}
// Perform the actual key import

View File

@ -199,7 +199,7 @@ func getConfig(values url.Values, keys []string) ([]string, error) {
}
val, err := url.QueryUnescape(val)
if err != nil {
return res, fmt.Errorf("could not unescape value for key: %q", key)
return res, fmt.Errorf("failed to unescape value for key: %q", key)
}
res[idx] = val
}

View File

@ -143,10 +143,10 @@ func (c *CryptMapper) CloseCryptDevice(volumeID string) error {
klog.V(4).Infof("Skipping unmapping for disk %q: volume does not exist or is already unmapped", volumeID)
return nil
}
return fmt.Errorf("failed to get device path for disk %q: %w", cryptPrefix+volumeID, err)
return fmt.Errorf("getting device path for disk %q: %w", cryptPrefix+volumeID, err)
}
if err := closeCryptDevice(c.mapper, source, volumeID, "crypt"); err != nil {
return fmt.Errorf("failed to close crypt device: %w", err)
return fmt.Errorf("closing crypt device: %w", err)
}
integrity, err := filepath.EvalSymlinks(cryptPrefix + volumeID + integritySuffix)
@ -154,7 +154,7 @@ func (c *CryptMapper) CloseCryptDevice(volumeID string) error {
// If device was created with integrity, we need to also close the integrity device
integrityErr := closeCryptDevice(c.mapper, integrity, volumeID+integritySuffix, "integrity")
if integrityErr != nil {
klog.Errorf("Could not close integrity device: %s", integrityErr)
klog.Errorf("Failed to close integrity device: %s", integrityErr)
return integrityErr
}
}
@ -164,7 +164,7 @@ func (c *CryptMapper) CloseCryptDevice(volumeID string) error {
// integrity device does not exist
return nil
}
return fmt.Errorf("failed to get device path for disk %q: %w", cryptPrefix+volumeID, err)
return fmt.Errorf("getting device path for disk %q: %w", cryptPrefix+volumeID, err)
}
return nil
@ -205,14 +205,14 @@ func closeCryptDevice(device DeviceMapper, source, volumeID, deviceType string)
klog.V(4).Infof("Unmapping dm-%s volume %q for device %q", deviceType, cryptPrefix+volumeID, source)
if err := device.InitByName(volumeID); err != nil {
klog.Errorf("Could not initialize dm-%s to unmap device %q: %s", deviceType, source, err)
return fmt.Errorf("could not initialize dm-%s to unmap device %q: %w", deviceType, source, err)
klog.Errorf("Failed to initialize dm-%s to unmap device %q: %s", deviceType, source, err)
return fmt.Errorf("initializing dm-%s to unmap device %q: %w", deviceType, source, err)
}
defer device.Free()
if err := device.Deactivate(volumeID); err != nil {
klog.Errorf("Could not deactivate dm-%s volume %q for device %q: %s", deviceType, cryptPrefix+volumeID, source, err)
return fmt.Errorf("could not deactivate dm-%s volume %q for device %q: %w", deviceType, cryptPrefix+volumeID, source, err)
klog.Errorf("Failed to deactivate dm-%s volume %q for device %q: %s", deviceType, cryptPrefix+volumeID, source, err)
return fmt.Errorf("deactivating dm-%s volume %q for device %q: %w", deviceType, cryptPrefix+volumeID, source, err)
}
klog.V(4).Infof("Successfully unmapped dm-%s volume %q for device %q", deviceType, cryptPrefix+volumeID, source)
@ -249,7 +249,7 @@ func openCryptDevice(ctx context.Context, device DeviceMapper, source, volumeID
klog.V(4).Infof("Device %q is not formatted as LUKS2 partition, checking for existing format...", source)
format, err := diskInfo(source)
if err != nil {
return "", fmt.Errorf("could not determine if disk is formatted: %w", err)
return "", fmt.Errorf("determining if disk is formatted: %w", err)
}
if format != "" {
// Device is already formated, return an error
@ -277,8 +277,8 @@ func openCryptDevice(ctx context.Context, device DeviceMapper, source, volumeID
CipherMode: "xts-plain64",
VolumeKeySize: keySize,
}); err != nil {
klog.Errorf("Formatting device %q failed: %s", source, err)
return "", fmt.Errorf("formatting device %q failed: %w", source, err)
klog.Errorf("Failed to format device %q: %s", source, err)
return "", fmt.Errorf("formatting device %q: %w", source, err)
}
uuid := device.GetUUID()

View File

@ -40,7 +40,7 @@ func (k *ConstellationKMS) GetDEK(ctx context.Context, dekID string, dekSize int
conn,
)
if err != nil {
return nil, fmt.Errorf("could not get data encryption key from Constellation Coordinator: %w", err)
return nil, fmt.Errorf("getting data encryption key from Constellation Coordinator: %w", err)
}
return res.DataKey, nil