|
| 1 | +/** |
| 2 | + * Copyright 2009 the original author or authors. |
| 3 | + * |
| 4 | + * <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file |
| 5 | + * except in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * <p>http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * <p>Unless required by applicable law or agreed to in writing, software distributed under the |
| 10 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | + * express or implied. See the License for the specific language governing permissions and |
| 12 | + * limitations under the License. |
| 13 | + */ |
| 14 | +package net.javacrumbs.shedlock.provider.elasticsearch9; |
| 15 | + |
| 16 | +import static net.javacrumbs.shedlock.core.ClockProvider.now; |
| 17 | +import static net.javacrumbs.shedlock.support.Utils.getHostname; |
| 18 | + |
| 19 | +import co.elastic.clients.elasticsearch.ElasticsearchClient; |
| 20 | +import co.elastic.clients.elasticsearch._types.ElasticsearchException; |
| 21 | +import co.elastic.clients.elasticsearch._types.Refresh; |
| 22 | +import co.elastic.clients.elasticsearch._types.Result; |
| 23 | +import co.elastic.clients.elasticsearch.core.UpdateRequest; |
| 24 | +import co.elastic.clients.elasticsearch.core.UpdateResponse; |
| 25 | +import co.elastic.clients.json.JsonData; |
| 26 | +import java.io.IOException; |
| 27 | +import java.time.Instant; |
| 28 | +import java.util.Collections; |
| 29 | +import java.util.Map; |
| 30 | +import java.util.Optional; |
| 31 | +import net.javacrumbs.shedlock.core.AbstractSimpleLock; |
| 32 | +import net.javacrumbs.shedlock.core.LockConfiguration; |
| 33 | +import net.javacrumbs.shedlock.core.LockProvider; |
| 34 | +import net.javacrumbs.shedlock.core.SimpleLock; |
| 35 | +import net.javacrumbs.shedlock.support.LockException; |
| 36 | +import net.javacrumbs.shedlock.support.annotation.NonNull; |
| 37 | + |
| 38 | +/** |
| 39 | + * It uses a collection that contains documents like this: |
| 40 | + * |
| 41 | + * <pre> |
| 42 | + * { |
| 43 | + * "name" : "lock name", |
| 44 | + * "lockUntil" : { |
| 45 | + * "type": "date", |
| 46 | + * "format": "epoch_millis" |
| 47 | + * }, |
| 48 | + * "lockedAt" : { |
| 49 | + * "type": "date", |
| 50 | + * "format": "epoch_millis" |
| 51 | + * }: |
| 52 | + * "lockedBy" : "hostname" |
| 53 | + * } |
| 54 | + * </pre> |
| 55 | + * |
| 56 | + * <p> |
| 57 | + * lockedAt and lockedBy are just for troubleshooting and are not read by the |
| 58 | + * code |
| 59 | + * |
| 60 | + * <ol> |
| 61 | + * <li>Attempts to insert a new lock record. As an optimization, we keep |
| 62 | + * in-memory track of created lock records. If the record has been inserted, |
| 63 | + * returns lock. |
| 64 | + * <li>We will try to update lock record using filter _id == name AND lock_until |
| 65 | + * <= now |
| 66 | + * <li>If the update succeeded (1 updated document), we have the lock. If the |
| 67 | + * update failed (0 updated documents) somebody else holds the lock |
| 68 | + * <li>When unlocking, lock_until is set to now. |
| 69 | + * </ol> |
| 70 | + */ |
| 71 | +public class ElasticsearchLockProvider implements LockProvider { |
| 72 | + static final String SCHEDLOCK_DEFAULT_INDEX = "shedlock"; |
| 73 | + static final String LOCK_UNTIL = "lockUntil"; |
| 74 | + static final String LOCKED_AT = "lockedAt"; |
| 75 | + static final String LOCKED_BY = "lockedBy"; |
| 76 | + static final String NAME = "name"; |
| 77 | + |
| 78 | + private static final String UPDATE_SCRIPT = "if (ctx._source." + LOCK_UNTIL + " <= " + "params." + LOCKED_AT |
| 79 | + + ") { " + "ctx._source." + LOCKED_BY + " = params." + LOCKED_BY + "; " + "ctx._source." + LOCKED_AT |
| 80 | + + " = params." + LOCKED_AT + "; " + "ctx._source." + LOCK_UNTIL + " = params." + LOCK_UNTIL + "; " |
| 81 | + + "} else { " + "ctx.op = 'none' " + "}"; |
| 82 | + |
| 83 | + private final ElasticsearchClient client; |
| 84 | + private final String hostname; |
| 85 | + private final String index; |
| 86 | + |
| 87 | + private ElasticsearchLockProvider(@NonNull ElasticsearchClient client, @NonNull String index) { |
| 88 | + this.client = client; |
| 89 | + this.hostname = getHostname(); |
| 90 | + this.index = index; |
| 91 | + } |
| 92 | + |
| 93 | + public ElasticsearchLockProvider(@NonNull ElasticsearchClient client) { |
| 94 | + this(client, SCHEDLOCK_DEFAULT_INDEX); |
| 95 | + } |
| 96 | + |
| 97 | + @Override |
| 98 | + @NonNull |
| 99 | + public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) { |
| 100 | + try { |
| 101 | + Instant now = now(); |
| 102 | + Instant lockAtMostUntil = lockConfiguration.getLockAtMostUntil(); |
| 103 | + Map<String, JsonData> lockObject = lockObject(lockConfiguration.getName(), lockAtMostUntil, now); |
| 104 | + |
| 105 | + // The object exist only to have some type we can work with |
| 106 | + Lock pojo = new Lock(lockConfiguration.getName(), hostname, now, lockAtMostUntil); |
| 107 | + |
| 108 | + UpdateRequest<Lock, Lock> updateRequest = UpdateRequest.of(ur -> ur.index(index) |
| 109 | + .id(lockConfiguration.getName()) |
| 110 | + .refresh(Refresh.True) |
| 111 | + .script(sc -> sc.lang("painless") |
| 112 | + .source(builder -> builder.scriptString(UPDATE_SCRIPT)) |
| 113 | + .params(lockObject)) |
| 114 | + .upsert(pojo)); |
| 115 | + |
| 116 | + UpdateResponse<Lock> res = client.update(updateRequest, Lock.class); |
| 117 | + if (res.result() != Result.NoOp) { |
| 118 | + return Optional.of(new ElasticsearchSimpleLock(lockConfiguration)); |
| 119 | + } else { // nothing happened |
| 120 | + return Optional.empty(); |
| 121 | + } |
| 122 | + } catch (IOException | ElasticsearchException e) { |
| 123 | + if ((e instanceof ElasticsearchException && ((ElasticsearchException) e).status() == 409)) { |
| 124 | + return Optional.empty(); |
| 125 | + } else { |
| 126 | + throw new LockException("Unexpected exception occurred", e); |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private Map<String, JsonData> lockObject(String name, Instant lockUntil, Instant lockedAt) { |
| 132 | + return Map.of( |
| 133 | + NAME, |
| 134 | + JsonData.of(name), |
| 135 | + LOCKED_BY, |
| 136 | + JsonData.of(hostname), |
| 137 | + LOCKED_AT, |
| 138 | + JsonData.of(lockedAt.toEpochMilli()), |
| 139 | + LOCK_UNTIL, |
| 140 | + JsonData.of(lockUntil.toEpochMilli())); |
| 141 | + } |
| 142 | + |
| 143 | + private final class ElasticsearchSimpleLock extends AbstractSimpleLock { |
| 144 | + |
| 145 | + private ElasticsearchSimpleLock(LockConfiguration lockConfiguration) { |
| 146 | + super(lockConfiguration); |
| 147 | + } |
| 148 | + |
| 149 | + @Override |
| 150 | + public void doUnlock() { |
| 151 | + // Set lockUtil to now or lockAtLeastUntil whichever is later |
| 152 | + try { |
| 153 | + Map<String, JsonData> lockObject = Collections.singletonMap( |
| 154 | + "unlockTime", |
| 155 | + JsonData.of(lockConfiguration.getUnlockTime().toEpochMilli())); |
| 156 | + |
| 157 | + UpdateRequest<Lock, Lock> updateRequest = UpdateRequest.of(ur -> ur.index(index) |
| 158 | + .id(lockConfiguration.getName()) |
| 159 | + .refresh(Refresh.True) |
| 160 | + .script(sc -> sc.lang("painless") |
| 161 | + .source(builder -> builder.scriptString("ctx._source.lockUntil = params.unlockTime")) |
| 162 | + .params(lockObject))); |
| 163 | + client.update(updateRequest, Lock.class); |
| 164 | + } catch (IOException | ElasticsearchException e) { |
| 165 | + throw new LockException("Unexpected exception occurred", e); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private record Lock(String name, String lockedBy, long lockedAt, long lockUntil) { |
| 171 | + Lock(String name, String lockedBy, Instant lockedAt, Instant lockUntil) { |
| 172 | + this(name, lockedBy, lockedAt.toEpochMilli(), lockUntil.toEpochMilli()); |
| 173 | + } |
| 174 | + } |
| 175 | +} |
0 commit comments