diff --git a/internal/pkg/agent/storage/encrypted_disk_store.go b/internal/pkg/agent/storage/encrypted_disk_store.go index 280d1c8b3ba..7af2869bf7a 100644 --- a/internal/pkg/agent/storage/encrypted_disk_store.go +++ b/internal/pkg/agent/storage/encrypted_disk_store.go @@ -88,8 +88,13 @@ func (d *EncryptedDiskStore) ensureKey(ctx context.Context) error { return nil } -// Save will write the encrypted storage to disk. -// Specifically it will write to a .tmp file then rotate the file to the target name to ensure that an error does not corrupt the previously written file. +// Save will read 'in' and write its contents encrypted to disk. +// If EncryptedDiskStore.Load() was called, the io.ReadCloser it returns MUST be +// closed before Save() can be called. It is so because Save() writes to a .tmp +// file then rotate the file to the target name to ensure that an error does not +// corrupt the previously written file. +// Specially on windows systems, if the original files is still open because of +// Load(), Save() would fail. func (d *EncryptedDiskStore) Save(in io.Reader) error { // Ensure has agent key err := d.ensureKey(d.ctx) diff --git a/internal/pkg/agent/storage/storage.go b/internal/pkg/agent/storage/storage.go index 952f82c5883..bf7d47fe293 100644 --- a/internal/pkg/agent/storage/storage.go +++ b/internal/pkg/agent/storage/storage.go @@ -14,7 +14,9 @@ const perms os.FileMode = 0600 // Store saves the io.Reader. type Store interface { - // Save the io.Reader. + // Save the io.Reader. Depending on the underlying implementation, if + // Storage.Load() was called, the io.ReadCloser MUST be closed before Save() + // can be called. Save(io.Reader) error } diff --git a/internal/pkg/agent/storage/store/migrations.go b/internal/pkg/agent/storage/store/migrations.go index d8247e0fba8..5fd75ecfb50 100644 --- a/internal/pkg/agent/storage/store/migrations.go +++ b/internal/pkg/agent/storage/store/migrations.go @@ -112,7 +112,8 @@ func migrateYAMLStateStoreToStateStoreV1(store storage.Storage) error { } st, err := readState(reader) - defer reader.Close() + // close it as soon as possible and before the next store save + _ = reader.Close() if err == nil { // it's a valid JSON, therefore nothing to migrate return nil