Skip to content

fix: Introducing initializers for handling lock cleanup on start - #1342

Merged
jvherweg merged 1 commit into
versions/5.0.0from
fix/issue-1085
Jul 6, 2022
Merged

jvherweg merged 1 commit into
versions/5.0.0from
fix/issue-1085

Conversation

@wkerckho

Copy link
Copy Markdown
Contributor

📁 Related issues

#1085

✍️ Description

Code changes
  • Added interface Initializable in addition to the existing abstract class Initializer (which implements AsyncHandler). This allows classes already extending AsyncHandler for some other purpose, to have another entry point for initialization purposes.
  • Introduced InitializableHandler as a wrapper class for bridging classes implementing Initializable with the existing initializer constructs based on Initializer/AsyncHandler.
  • Added a Finalizer abstract class and a FinalizableHandler wrapper class with the goal of having symmetry in the initialization and finalization mechanisms.
  • Refactored the existing initializers and finalizers based on these changes.
    • Changed type for finalizer attribute in App from Finalizable to Finalizer and updated the calling code in App.stop()
    • Removed the obsolete ParallelFinalizer as Finalizable implementations can now be wrapped with FinalizableHandler for use within ParallelHandler.
  • FileSystemResourceLocker now implements Initializable. The existing cleanup code in finalize() was moved to a private method clearLocks, so it can be reused in the implementation of initialize(). The ensureDirSync statement in the constructor has been replaced with a call to ensureDir (async) in initialize() as this can be seen as part of the initialization process.
  • RedisLocker now implements Initializable. The existing cleanup code in finalize() was moved to a private method clearLocks, so it can be reused in the implementation of initialize(). An additional property finalizeCalled was added to RedisLocker that is set to true when finalize() is called, with the goal of preventing new Redis operations once finalization has been triggered and to throw more descriptive errors in this case.
Test changes
  • Added coverage for initialize() in FileSystemResourceLocker.test.ts
  • Added coverage for initialize() in RedisLocker.test.ts. This required added mock implementations for the redis keys and del functions. Removed some test cases that no longer make sense and extended the existing finalize() tests so that these check that keys are being cleaned up (instead of just checking that redis.quit was called).
  • Introduced a new integration test ResourceLockCleanup.test.ts which tests if the persistent locking implementations (File-based and Redis-based) correctly cleanup any pre-existing locks at startup (e.g. this can happen in case of an ungraceful shutdown).
Config changes
  • Introduced two new fixed stages in the server lifecycle:
    • urn:solid-server:default:StartCleanupInitializer is called as the first Initializer in the urn:solid-server:default:PrimarySequenceInitializer sequence. Crucial cleanup & initialization logic that should happen before any other initialization (with the exception of logging initialization) should be added to this SequenceHandler.
    • urn:solid-server:default:StopCleanupFinalizer is called as the final Finalizer stage after the existing urn:solid-server:default:Finalizer. Cleanup with consequences on the platform operations and thus that should happen after any other finalization, should be added to this SequenceHandler.
    • The cleaning up of File and Redis-based locks are examples of Initializers and Finalizers which could have an impact on the correct operation of other Initializers and Finalizers, and have been added to the StartCleanupInitializer and StopCleanupFinalizer respectively. This change also makes sure that initialize() is called if the default util/resource-locker/file.json and util/resource-locker/redis.json are imported.
    • Removed all occurences of ParallelFinalizer as these can now be replaced with ParallelHandler in combination with wrapping the entries using FinalizableHandler.

I'm open for suggestions on better names for StartCleanupInitializer and StopCleanupFinalizer!

✅ PR check list

Before this pull request can be merged, a core maintainer will check whether

  • this PR is labeled with the correct semver label
    • semver.patch: Backwards compatible bug fixes.
    • semver.minor: Backwards compatible feature additions.
    • semver.major: Breaking changes. This includes changing interfaces or configuration behaviour.
  • the correct branch is targeted. Patch updates can target main, other changes should target the latest versions/* branch.
  • the RELEASE_NOTES.md document in case of relevant feature or config changes.
  • any relevant documentation was updated to reflect the changes in this PR.

@wkerckho
wkerckho requested a review from jvherweg June 15, 2022 13:31

@jvherweg jvherweg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly minor comments, looks good. RELEASE_NOTES still needs to be update to indicate the config/interface changes.

Any idea why the integration tests are failing though? Seems as there is still a potential race condition with locks being removed by 2 different handlers?

Comment thread config/app/init/base/init.json Outdated
"@id": "urn:solid-server:default:PrimarySequenceInitializer",
"@type":"SequenceHandler",
"handlers": [
{ "@id": "urn:solid-server:default:StartCleanupInitializer"},

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would go for CleanupInitializer and CleanupFinalizer as the start/stop is already implied by the name.

Comment thread config/app/main/default.json Outdated
]
},
{
"comment": "These finalizers will all be executed sequentially as last when stopping the server.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"comment": "These finalizers will all be executed sequentially as last when stopping the server.",
"comment": "These finalizers will all be executed sequentially last when stopping the server.",

Comment thread config/app/main/default.json Outdated
Comment on lines +13 to +14
{ "@id": "urn:solid-server:default:Finalizer" },
{ "@id": "urn:solid-server:default:StopCleanupFinalizer" }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we currently have any issues if these are not split up or is this just to mirror the initializer approach?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not aware of any concrete issues (as opposed to what I experienced with the Initializers). The rationale was that cleanup (such as deleting a lock folder) could negatively impact other finalizers that e.g. operate on the ResourceStore. So you could say I mirrored the initializer approach.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough. Felt a bit too much since we don't really need it right now, but might not be bad to already add it.

Comment thread config/util/resource-locker/file.json Outdated
"expiration": 3000
},
{
"comment": "Makes sure the FileSystemResourceLocker starts with a clean slate when the application is started.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment should actually be on the InitializableHandler below since this is RDF and otherwise all comments will be attached to the StartCleanupInitializer. Doesn't matter that much in practice since I assume everyone just reads the json-ld files directly, but can be correct here since the effect is the same.

For example below we did this wrong in the finalizer but then we didn't have a specific class yet to add that comment though so we cheated by adding it to the main finalizer. But that can also be changed now.

Would also rephrase the comment to focus on the why (to prevent dangling locks that could cause a conflict).

Comment thread config/util/resource-locker/redis.json Outdated
"expiration": 3000
},
{
"comment": "Makes sure the RedisLocker starts with a clean slate when the application is started.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comments as above.

Comment thread src/util/locking/RedisLocker.ts Outdated
}

private async clearLocks(): Promise<void> {
// Remove any lock still open

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move this to tsdoc above the function.


beforeAll(async(): Promise<void> => {
// Clean the working dir
await removeFolder(rootFilePath);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this necessary? If this folder is not empty it means something has gone wrong with the test run (since afterAll also removes the folder), which would also be an issue for many other tests that write files to the disk.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! I sometimes terminate the process when debugging, which can lead to folder content remaining on disk. I will remove this statement, as this will never occur in the CI pipeline.

) as Record<string, any>;
({ app, store, locker } = instances);

// Call locker.initialize() manually, so we can create a test resource

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this necessary to create a test resource? The config uses the backend resource store so it doesn't pass through the locking store.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I had an error when I didn't initialize before creating the test resource.. I will investigate!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So apparently, it's a call to ensureDir of the lockfolder that is required for the test resource creation to succeed.
This used to be called from the FileSystemResourceLocker constructor, but I've moved this to the initialize() implementation. I guess the resource store expects the root folder to exist, which is not guaranteed at this point (as the test has not started the server), and ensureDir for the lock-folder, also creates the parent folders, thus avoiding this issue.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The resource store should be able to handle the fact that the root container does not exist yet and create it in the process. We used to have a memory locking system and then everything worked fine then so I'm not exactly sure what the problem is. Not starting the server yet does mean that the root initializer has not created the root container yet, but that one also just does it by calling the resource store, so why would that call succeed and this one fail?


it('should not be affected by dangling locks.', async(): Promise<void> => {
// Simulate lock existing before server startup, by creating a (write) lock directly
const promise = locker.withWriteLock(resourceIdentifier, async(): Promise<void> => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this test (slightly) different from the file one? If they can be the same this can be generalized.

@@ -0,0 +1,63 @@
{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this config (and the other new one below) potentially be merged with one of the already existing ones? By introducing a new entry in the recordobject or defining the resource store outside of the config like we do in some other integration tests for example. That way we have less configs we have to keep up to date.

@jvherweg

Copy link
Copy Markdown
Member

This also clears the locks of the read-write locker since it removes the same folder right? Should probably mention that in a comment somewhere and create a new issue afterwards that we should look into doing this in a cleaner way so there is no codependency.

@jvherweg jvherweg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly documentation comments

Comment thread RELEASE_NOTES.md Outdated
Comment on lines +43 to +51
- The init handlers were restructured with the goal of introducing a new initialization phase that is executed right after initialization of the logging infrastructure, but before everything else. This phase is represented by a `SequenceHandler` with id `urn:solid-server:default:CleanupInitializer`. Critical init operations (on which subsequent init handlers also depend), especially related to cleaning up the server state before launch, must be added here. This extra phase was mirrored for finalization (`SequenceHandler` with id `CleanupFinalizer`), allowing to configure extra finalization steps to be executed after all the regular finalizers (represented by the `ParallelHandler` with id `urn:solid-server:default:Finalizer`). The default configurations were modified to reflect these changes.
- `config/app/init/base/init.json` defines the `CleanupInitializer`.
- `config/app/main/default.json` defines the `CleanupFinalizer`.
- `config/util/resource-locker/file.json` registers init and finalization handlers for resource lock cleanup.
- `config/util/resource-locker/redis.json` registers init and finalization handlers for resource lock cleanup.
- Configured instances of `ParallelFinalizer` were replaced with `ParallelHandler` in combination with instances of the new `FinalizableHandler` wrapper, allowing `ParallelFinalizer` to be removed and thus reducing the number of concepts.
- `config/app/identity/handler/account-store/default.json`
- `config/identity/ownership/token.json`
- `config/ldp/authorization/readers/access-checkers/agent-group.json`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general I try to have short lines here to not overload the release notes so I would have just had 3 entries "Restructured the init configs", "Added lock cleanup", and "Updated finalizers" (or perhaps a few more words than that). The main question is, can what is said here also be seen clearly in the configs when looking at them? Things that can be seen by checking those shouldn't really be repeated here. E.g., when looking at the config it's clear there is a cleanup initializer now. Partially because I'm afraid people would skip over this if it's too much, but I might be wrong. Feel free to discuss though as this is quite subjective.

The paths should not start with config though, just the first folder in there so /app/init/.... The entry right above this one is wrong in that regard.

Comment thread RELEASE_NOTES.md
- Both `TemplateEngine` implementations now take a `baseUrl` parameter as input.
- The `IdentityProviderFactory` and `ConvertingErrorHandler` now additionally take a `PreferenceParser` as input.
- Error handlers now take the incoming HttpRequest as input instead of just the preferences.
- Extended the initialization/finalization system:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar comment as above here. So far we have never actually put why we did things here, just what changed.

Comment thread config/app/init/base/init.json Outdated
}
},
{
"comment": "These initializers will all be executed sequentially first when starting (the primary process) of the server.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"comment": "These initializers will all be executed sequentially first when starting (the primary process) of the server.",
"comment": "Initializers that need to cleanup or do anything else before something writes to the backend should be added here.",

Comment thread config/app/main/default.json Outdated
"@type": "ParallelFinalizer",
"finalizers": [
{ "@id": "urn:solid-server:default:ServerInitializer" }
"comment": "This is going to determine the sequence of finalizers that needs to be called when stopping the server.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"comment": "This is going to determine the sequence of finalizers that needs to be called when stopping the server.",
"comment": "Is executed when the server is stopped.",

The phrasing was to indicate that new entries could be added here, but this is no longer the case.

Comment thread config/app/main/default.json Outdated
]
},
{
"comment": "These finalizers will all be executed sequentially last when stopping the server.",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"comment": "These finalizers will all be executed sequentially last when stopping the server.",
"comment": "Finalizers that need to cleanup once no more data will be written to the backend should be added here.",

});

afterAll(async(): Promise<void> => {
// Stop the server

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Stop the server
// Stop the server

});

it('should not be affected by dangling locks.', async(): Promise<void> => {
// Simulate lock existing before server startup, by creating a (write) lock directly

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Simulate lock existing before server startup, by creating a (write) lock directly
// Simulate lock existing before server startup, by creating a (write) lock directly

@@ -0,0 +1,65 @@
{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume this config can be deleted since it's not used anywhere.

Comment on lines +121 to +122
const onCompromise =
locker['defaultLockOptions'].onCompromised!; // eslint-disable-line @typescript-eslint/dot-notation

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const onCompromise =
locker['defaultLockOptions'].onCompromised!; // eslint-disable-line @typescript-eslint/dot-notation
// eslint-disable-next-line @typescript-eslint/dot-notation
const onCompromise = locker['defaultLockOptions'].onCompromised!;

Although I'm not sure why dot notation is not used?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not use dot notation, because I needed a way for accessing the private property defaultLockOptions, but maybe there is a better way of doing this?

I will rewrite this section as part of the requested change for still having defaultLockOptions outside of the FileSystemResourceLocker class, but I will still require access to a private property, so tips are welcome!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just figured out casting to any can be an alternative solution..

@jvherweg
jvherweg merged commit 1c65b06 into versions/5.0.0 Jul 6, 2022
@jvherweg
jvherweg deleted the fix/issue-1085 branch July 6, 2022 08:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants