Skip to content

clone on read from cache #321

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 1 commit into from
Jan 25, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.javaoperatorsdk.operator.processing;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.fabric8.kubernetes.client.CustomResource;
import java.util.Map;
import java.util.Optional;
Expand All @@ -14,6 +16,7 @@ public class CustomResourceCache {

private static final Logger log = LoggerFactory.getLogger(CustomResourceCache.class);

private ObjectMapper objectMapper = new ObjectMapper();
private final Map<String, CustomResource> resources = new ConcurrentHashMap<>();
private final Lock lock = new ReentrantLock();

Expand All @@ -38,8 +41,29 @@ public void cacheResource(CustomResource resource, Predicate<CustomResource> pre
}
}

/**
* We clone the object so the one in the cache is not changed by the controller or dispatcher.
* Therefore the cached object always represents the object coming from the API server.
*
* @param uuid
* @return
*/
public Optional<CustomResource> getLatestResource(String uuid) {
return Optional.ofNullable(resources.get(uuid));
return Optional.ofNullable(clone(resources.get(uuid)));
}

private CustomResource clone(CustomResource customResource) {
try {
if (customResource == null) {
return null;
}
CustomResource clonedObject =
objectMapper.readValue(
objectMapper.writeValueAsString(customResource), customResource.getClass());
return clonedObject;
} catch (JsonProcessingException e) {
throw new IllegalStateException(e);
}
}

public CustomResource cleanup(String customResourceUid) {
Expand Down