-
Notifications
You must be signed in to change notification settings - Fork 1
Make instance UUIDs stable across restarts #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,7 @@ | ||
| target/ | ||
|
|
||
| # VS Code | ||
| .vscode/ | ||
|
|
||
| # misc | ||
| .DS_Store |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| package io.apitally.common; | ||
|
|
||
| import java.io.Closeable; | ||
| import java.io.IOException; | ||
| import java.nio.ByteBuffer; | ||
| import java.nio.channels.FileChannel; | ||
| import java.nio.channels.FileLock; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.StandardOpenOption; | ||
| import java.nio.file.attribute.FileTime; | ||
| import java.security.MessageDigest; | ||
| import java.security.NoSuchAlgorithmException; | ||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.HexFormat; | ||
| import java.util.UUID; | ||
|
|
||
| public class InstanceLock implements Closeable { | ||
| private static final int MAX_SLOTS = 100; | ||
| private static final int MAX_LOCK_AGE_SECONDS = 24 * 60 * 60; | ||
|
|
||
| private final UUID instanceUuid; | ||
| private final FileChannel lockChannel; | ||
|
|
||
| private InstanceLock(UUID uuid, FileChannel lockChannel) { | ||
| this.instanceUuid = uuid; | ||
| this.lockChannel = lockChannel; | ||
| } | ||
|
|
||
| public UUID getInstanceUuid() { | ||
| return instanceUuid; | ||
| } | ||
|
|
||
| public static InstanceLock create(String clientId, String env) { | ||
| return create(clientId, env, Path.of(System.getProperty("java.io.tmpdir"), "apitally")); | ||
| } | ||
|
|
||
| static InstanceLock create(String clientId, String env, Path lockDir) { | ||
| try { | ||
| Files.createDirectories(lockDir); | ||
| } catch (Exception e) { | ||
| return new InstanceLock(UUID.randomUUID(), null); | ||
| } | ||
|
|
||
| String appEnvHash; | ||
| try { | ||
| appEnvHash = getAppEnvHash(clientId, env); | ||
| } catch (Exception e) { | ||
| return new InstanceLock(UUID.randomUUID(), null); | ||
| } | ||
|
|
||
| for (int slot = 0; slot < MAX_SLOTS; slot++) { | ||
| Path lockPath = lockDir.resolve("instance_" + appEnvHash + "_" + slot + ".lock"); | ||
| FileChannel channel = null; | ||
| try { | ||
| channel = FileChannel.open( | ||
| lockPath, | ||
| StandardOpenOption.CREATE, | ||
| StandardOpenOption.READ, | ||
| StandardOpenOption.WRITE); | ||
|
|
||
| FileLock lock = channel.tryLock(); | ||
| if (lock == null) { | ||
| channel.close(); | ||
| continue; | ||
| } | ||
|
|
||
| FileTime lastModified = Files.getLastModifiedTime(lockPath); | ||
| boolean tooOld = Duration.between(lastModified.toInstant(), Instant.now()).getSeconds() > MAX_LOCK_AGE_SECONDS; | ||
|
|
||
| String existingUuid = readChannel(channel); | ||
| UUID uuid = parseUuid(existingUuid); | ||
|
|
||
| if (uuid != null && !tooOld) { | ||
| return new InstanceLock(uuid, channel); | ||
| } | ||
|
|
||
| UUID newUuid = UUID.randomUUID(); | ||
| channel.truncate(0); | ||
| channel.write(ByteBuffer.wrap(newUuid.toString().getBytes(StandardCharsets.UTF_8))); | ||
| channel.force(true); | ||
|
|
||
| return new InstanceLock(newUuid, channel); | ||
| } catch (Exception e) { | ||
| if (channel != null) { | ||
| try { | ||
| channel.close(); | ||
| } catch (IOException ignored) { | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return new InstanceLock(UUID.randomUUID(), null); | ||
| } | ||
|
|
||
| private static String readChannel(FileChannel channel) throws IOException { | ||
| channel.position(0); | ||
| ByteBuffer buffer = ByteBuffer.allocate(64); | ||
| int bytesRead = channel.read(buffer); | ||
| if (bytesRead <= 0) { | ||
| return ""; | ||
| } | ||
| return new String(buffer.array(), 0, bytesRead, StandardCharsets.UTF_8).trim(); | ||
| } | ||
|
|
||
| private static UUID parseUuid(String s) { | ||
| if (s == null || s.isEmpty()) { | ||
| return null; | ||
| } | ||
| try { | ||
| return UUID.fromString(s); | ||
| } catch (IllegalArgumentException e) { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| private static String getAppEnvHash(String clientId, String env) throws NoSuchAlgorithmException { | ||
| MessageDigest digest = MessageDigest.getInstance("SHA-256"); | ||
| byte[] hash = digest.digest((clientId + ":" + env).getBytes(StandardCharsets.UTF_8)); | ||
| return HexFormat.of().formatHex(hash, 0, 4); | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| if (lockChannel != null) { | ||
| try { | ||
| lockChannel.close(); | ||
| } catch (IOException ignored) { | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,152 @@ | ||
| package io.apitally.common; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNotEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.security.MessageDigest; | ||
| import java.security.NoSuchAlgorithmException; | ||
| import java.time.Instant; | ||
| import java.time.temporal.ChronoUnit; | ||
| import java.util.Comparator; | ||
| import java.util.HexFormat; | ||
| import java.util.UUID; | ||
|
|
||
| import org.junit.jupiter.api.AfterEach; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| class InstanceLockTest { | ||
| private Path tempDir; | ||
|
|
||
| @BeforeEach | ||
| void setUp() throws IOException { | ||
| tempDir = Files.createTempDirectory("apitally_test_"); | ||
| } | ||
|
|
||
| @AfterEach | ||
| void tearDown() throws IOException { | ||
| if (tempDir != null && Files.exists(tempDir)) { | ||
| try (var paths = Files.walk(tempDir)) { | ||
| paths.sorted(Comparator.reverseOrder()) | ||
| .forEach(path -> { | ||
| try { | ||
| Files.deleteIfExists(path); | ||
| } catch (IOException ignored) { | ||
| } | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void createsNewUUID() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
| String env = "test"; | ||
|
|
||
| try (InstanceLock lock = InstanceLock.create(clientId, env, tempDir)) { | ||
| assertNotNull(lock.getInstanceUuid()); | ||
|
|
||
| String hash = getAppEnvHash(clientId, env); | ||
| Path lockFile = tempDir.resolve("instance_" + hash + "_0.lock"); | ||
| assertTrue(Files.exists(lockFile)); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void reusesExistingUUID() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
| String env = "test"; | ||
|
|
||
| UUID firstUuid; | ||
| try (InstanceLock lock1 = InstanceLock.create(clientId, env, tempDir)) { | ||
| firstUuid = lock1.getInstanceUuid(); | ||
| } | ||
|
|
||
| try (InstanceLock lock2 = InstanceLock.create(clientId, env, tempDir)) { | ||
| assertEquals(firstUuid, lock2.getInstanceUuid()); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void differentEnvsGetDifferentUUIDs() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
|
|
||
| try (InstanceLock lock1 = InstanceLock.create(clientId, "env1", tempDir); | ||
| InstanceLock lock2 = InstanceLock.create(clientId, "env2", tempDir)) { | ||
| assertNotEquals(lock1.getInstanceUuid(), lock2.getInstanceUuid()); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void multipleSlots() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
| String env = "test"; | ||
|
|
||
| try (InstanceLock lock1 = InstanceLock.create(clientId, env, tempDir); | ||
| InstanceLock lock2 = InstanceLock.create(clientId, env, tempDir); | ||
| InstanceLock lock3 = InstanceLock.create(clientId, env, tempDir)) { | ||
|
|
||
| assertNotEquals(lock1.getInstanceUuid(), lock2.getInstanceUuid()); | ||
| assertNotEquals(lock2.getInstanceUuid(), lock3.getInstanceUuid()); | ||
| assertNotEquals(lock1.getInstanceUuid(), lock3.getInstanceUuid()); | ||
|
|
||
| String hash = getAppEnvHash(clientId, env); | ||
| assertTrue(Files.exists(tempDir.resolve("instance_" + hash + "_0.lock"))); | ||
| assertTrue(Files.exists(tempDir.resolve("instance_" + hash + "_1.lock"))); | ||
| assertTrue(Files.exists(tempDir.resolve("instance_" + hash + "_2.lock"))); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void overwritesOldUUID() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
| String env = "test"; | ||
| String hash = getAppEnvHash(clientId, env); | ||
|
|
||
| String oldUuid = "550e8400-e29b-41d4-a716-446655440000"; | ||
| Path lockFile = tempDir.resolve("instance_" + hash + "_0.lock"); | ||
| Files.writeString(lockFile, oldUuid); | ||
| Instant oldTime = Instant.now().minus(25, ChronoUnit.HOURS); | ||
| Files.setLastModifiedTime(lockFile, java.nio.file.attribute.FileTime.from(oldTime)); | ||
|
|
||
| try (InstanceLock lock = InstanceLock.create(clientId, env, tempDir)) { | ||
| assertNotEquals(UUID.fromString(oldUuid), lock.getInstanceUuid()); | ||
| assertNotNull(lock.getInstanceUuid()); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void overwritesInvalidUUID() throws IOException { | ||
| String clientId = UUID.randomUUID().toString(); | ||
| String env = "test"; | ||
| String hash = getAppEnvHash(clientId, env); | ||
|
|
||
| Path lockFile = tempDir.resolve("instance_" + hash + "_0.lock"); | ||
| Files.writeString(lockFile, "not-a-valid-uuid"); | ||
|
|
||
| UUID uuid; | ||
| try (InstanceLock lock = InstanceLock.create(clientId, env, tempDir)) { | ||
| uuid = lock.getInstanceUuid(); | ||
| assertNotNull(uuid); | ||
| } | ||
|
|
||
| String content = Files.readString(lockFile).trim(); | ||
| assertEquals(uuid.toString(), content); | ||
| } | ||
|
|
||
| private static String getAppEnvHash(String clientId, String env) { | ||
| try { | ||
| MessageDigest digest = MessageDigest.getInstance("SHA-256"); | ||
| byte[] hash = digest.digest((clientId + ":" + env).getBytes(StandardCharsets.UTF_8)); | ||
| return HexFormat.of().formatHex(hash, 0, 4); | ||
| } catch (NoSuchAlgorithmException e) { | ||
| throw new RuntimeException("SHA-256 not available", e); | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.