index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty | Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/transmitters/ChoiceOfTwoEventTransmitter.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.netty.transmitters;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.publish.EventChannel;
import io.mantisrx.publish.EventTransmitter;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.internal.exceptions.NonRetryableException;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import io.mantisrx.publish.netty.pipeline.HttpEventChannel;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This transmitter is a variant of a random load balancing algorithm which chooses a worker based
* on the choice-of-two algorithm in order to avoid herding behavior exhibited by other load balancing
* algorithms.
*/
public class ChoiceOfTwoEventTransmitter implements EventTransmitter {
private static final Logger LOG = LoggerFactory.getLogger(ChoiceOfTwoEventTransmitter.class);
private final MrePublishConfiguration configuration;
private final Registry registry;
private final Timer channelSendTime;
private final MantisJobDiscovery jobDiscovery;
private final EventChannel eventChannel;
private final ChoiceOfTwoWorkerPool workerPool;
private final Counter noWorkersDroppedCount;
private final Counter noDiscoveryDroppedCount;
/**
* Creates a new instance.
*/
public ChoiceOfTwoEventTransmitter(MrePublishConfiguration config,
Registry registry,
MantisJobDiscovery jobDiscovery,
EventChannel eventChannel) {
this.configuration = config;
this.registry = registry;
this.channelSendTime =
SpectatorUtils.buildAndRegisterTimer(
registry, "sendTime", "channel", HttpEventChannel.CHANNEL_TYPE);
this.noWorkersDroppedCount =
SpectatorUtils.buildAndRegisterCounter(
registry,
"mantisEventsDropped",
"reason", "transmitterNoWorkers");
this.noDiscoveryDroppedCount =
SpectatorUtils.buildAndRegisterCounter(
registry,
"mantisEventsDropped",
"reason", "transmitterNoDiscoveryInfo");
this.jobDiscovery = jobDiscovery;
this.eventChannel = eventChannel;
this.workerPool = new ChoiceOfTwoWorkerPool(config, registry, this.eventChannel);
}
@Override
public void send(Event event, String stream) {
String app = configuration.appName();
String jobCluster = jobDiscovery.getJobCluster(app, stream);
Optional<JobDiscoveryInfo> jobDiscoveryInfo = jobDiscovery.getCurrentJobWorkers(jobCluster);
if (jobDiscoveryInfo.isPresent()) {
List<MantisWorker> workers = jobDiscoveryInfo.get().getIngestStageWorkers().getWorkers();
int numWorkers = workers.size();
if (numWorkers > 0) {
workerPool.refresh(workers);
final long start = registry.clock().wallTime();
try {
workerPool.record(event, eventChannel::send);
} catch (NonRetryableException e) {
LOG.trace("No workers for job cluster {}, dropping event", jobCluster);
noWorkersDroppedCount.increment();
}
final long end = registry.clock().wallTime();
channelSendTime.record(end - start, TimeUnit.MILLISECONDS);
} else {
LOG.trace("No workers for job cluster {}, dropping event", jobCluster);
noWorkersDroppedCount.increment();
}
} else {
LOG.trace("No job discovery info for job cluster {}, dropping event", jobCluster);
noDiscoveryDroppedCount.increment();
}
}
}
| 8,300 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty | Create_ds/mantis/mantis-publish/mantis-publish-netty/src/main/java/io/mantisrx/publish/netty/transmitters/ChoiceOfTwoWorkerPool.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.netty.transmitters;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.impl.AtomicDouble;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.publish.EventChannel;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.exceptions.NonRetryableException;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import io.mantisrx.publish.netty.pipeline.HttpEventChannel;
import io.netty.channel.Channel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
/**
* Maintains a set of active, usable {@link MantisWorker}s represented by a key-value mapping of
* {@code key: MantisWorker, value: error count}.
* <p>
* Capacity:
* <p>
* This pool maintains a working set of pool up to a configurable capacity. Upon {@link #refresh(List, boolean)},
* it will update its working set.
* <p>
* Blacklist:
* <p>
* Callers can use this class to record worker failures for an action.
* Once a worker has reached a configurable number of failures, it will be blacklisted.
* The caller can then decide whether or not to continue using that worker.
* <p>
* Workers will be removed from the blacklist by having their error counts reset after a configurable amount of time.
* This is to prevent a worker from indefinitely being blacklisted.
*/
class ChoiceOfTwoWorkerPool {
private final Registry registry;
private final AtomicDouble workerPoolGauge;
private final AtomicDouble blacklistedWorkersGauge;
private final int capacity;
private final int errorQuota;
private final int errorTimeoutSec;
private final int refreshIntervalSec;
private final ConcurrentMap<MantisWorker, Integer> pool;
/**
* Backed by {@link ConcurrentHashMap.KeySetView}.
*/
private final Set<MantisWorker> blacklist;
private final EventChannel eventChannel;
private AtomicLong lastFetchMs;
private AtomicLong lastBlacklistRefreshMs;
ChoiceOfTwoWorkerPool(MrePublishConfiguration config, Registry registry, EventChannel eventChannel) {
this.registry = registry;
this.workerPoolGauge = SpectatorUtils.buildAndRegisterGauge(
registry, "workerPool", "channel", HttpEventChannel.CHANNEL_TYPE);
this.blacklistedWorkersGauge = SpectatorUtils.buildAndRegisterGauge(
registry, "blacklistedWorkers", "channel", HttpEventChannel.CHANNEL_TYPE);
this.capacity = config.getWorkerPoolCapacity();
this.errorQuota = config.getWorkerPoolWorkerErrorQuota();
this.errorTimeoutSec = config.getWorkerPoolWorkerErrorTimeoutSec();
this.refreshIntervalSec = config.getWorkerPoolRefreshIntervalSec();
this.pool = new ConcurrentHashMap<>(config.getWorkerPoolCapacity());
this.blacklist = ConcurrentHashMap.newKeySet();
this.eventChannel = eventChannel;
this.lastFetchMs = new AtomicLong(0);
this.lastBlacklistRefreshMs = new AtomicLong(0);
}
/**
* Refreshes this pool of {@link MantisWorker}s by checking for staleness and if workers should be
* removed from the blacklist after a configurable amount of time.
* <p>
* Worker Replacement:
* <p>
* 1. If the fresh set of workers is the same or has new workers, then do nothing.
* 2. If a worker in the pool doesn't exist in the fresh set of workers, then replace it.
* 3. If a worker in the pool is blacklisted, then replace it.
* <p>
* If {@code force = false}, this method will try to refresh the pool even if the pool is full.
* It does this in case a worker in the pool no longer exists according to the fresh set of workers.
* This may happen in horizontal scaling situations.
* <p>
* Blacklist and Worker Error Timeout:
* <p>
* If workers error more than the allowed quota, they will be placed into the blacklist. Blacklisted workers will
* remain blacklisted for a timeout period, after which they may be again considered for selection.
*
* @param freshWorkers a list of pool to potentially refresh the pool.
* @param force if {@code true}, clear out the entire pool and add new pool up to the capacity;
* if {@code false}, replace pool using the worker replacement strategy.
*/
void refresh(List<MantisWorker> freshWorkers, boolean force) {
if (!shouldRefresh(lastFetchMs.get(), refreshIntervalSec * 1000)) {
return;
}
if (force) {
pool.clear();
workerPoolGauge.set((double) pool.size());
}
if (shouldRefresh(lastBlacklistRefreshMs.get(), errorTimeoutSec * 1000)) {
blacklist.clear();
blacklistedWorkersGauge.set((double) blacklist.size());
lastBlacklistRefreshMs.set(registry.clock().wallTime());
}
Set<MantisWorker> staleWorkers = new HashSet<>(pool.keySet());
Set<MantisWorker> diff = new HashSet<>(staleWorkers);
// Keep stale workers that exist in the fresh set.
staleWorkers.retainAll(freshWorkers);
diff.removeAll(staleWorkers);
// Remove worker from the pool. No need to explicitly close the underlying Netty channel because
// it would have already been closed by the attached CloseFutureListener in the HttpEventChannelManager.
diff.forEach(pool::remove);
// Exclude stale workers from candidate consideration.
freshWorkers.removeAll(diff);
Iterator<MantisWorker> candidates = freshWorkers.iterator();
while (candidates.hasNext() && pool.size() < capacity) {
MantisWorker candidate = candidates.next();
if (!blacklist.contains(candidate)) {
pool.put(candidate, 0);
workerPoolGauge.set((double) pool.size());
}
}
lastFetchMs.set(registry.clock().wallTime());
}
/**
* Refreshes this pool of {@link MantisWorker}s without a full replacement.
*
* @param workers a list of pool to potentially refresh the pool.
*/
void refresh(List<MantisWorker> workers) {
refresh(workers, false);
}
private boolean shouldRefresh(long timestamp, long interval) {
return registry.clock().wallTime() - timestamp > interval;
}
/**
* Runs the {@link BiFunction}, checks for failures, and increments error count for a {@link MantisWorker}.
*/
CompletableFuture<Void> record(
Event event,
BiFunction<MantisWorker, Event, CompletableFuture<Void>> function)
throws NonRetryableException {
MantisWorker worker = getRandomWorker();
if (worker == null) {
throw new NonRetryableException("no available workers in pool");
}
CompletableFuture<Void> future = function.apply(worker, event);
// RetryableException and NonRetryableException are generally what would be thrown.
future.whenCompleteAsync((v, t) -> {
if (t != null) {
// Increment error count for this specific worker.
pool.put(worker, pool.get(worker) + 1);
if (shouldBlacklist(worker)) {
// Immediately close Netty channel and remove blacklisted worker from pool.
eventChannel.close(worker);
pool.remove(worker);
workerPoolGauge.set((double) pool.size());
blacklist.add(worker);
blacklistedWorkersGauge.set((double) blacklist.size());
}
}
});
return future;
}
/**
* Determines whether or not a worker should be blacklisted.
*/
private boolean shouldBlacklist(MantisWorker worker) {
return pool.getOrDefault(worker, 0) > errorQuota;
}
/**
* Determines whether or not a worker in the pool is over the pool's configured per-worker error quota.
*/
boolean isBlacklisted(MantisWorker worker) {
return blacklist.contains(worker);
}
/**
* Returns a random choice-of-two {@link MantisWorker} from the pool.
*/
MantisWorker getRandomWorker() {
int poolSize = pool.size();
if (poolSize == 0) {
return null;
} else if (poolSize == 1) {
return (MantisWorker) pool.keySet().toArray()[0];
} else {
List<MantisWorker> candidates = new ArrayList<>(pool.keySet());
int randomIndex1 = ThreadLocalRandom.current().nextInt(pool.size());
int randomIndex2 = ThreadLocalRandom.current().nextInt(pool.size());
MantisWorker candidate1 = candidates.get(randomIndex1);
MantisWorker candidate2 = candidates.get(randomIndex2);
double candidate1Score = getWorkerScore(candidate1);
double candidate2Score = getWorkerScore(candidate2);
return candidate1Score <= candidate2Score ? candidate1 : candidate2;
}
}
/**
* Returns the number of errors for a given worker in the pool.
*/
int getWorkerErrors(MantisWorker worker) {
return pool.getOrDefault(worker, 0);
}
/**
* Calculate a worker score. Lower is better.
* <p>
* Currently, the only factor is the {@link Channel}'s buffer size.
*/
private double getWorkerScore(MantisWorker worker) {
return eventChannel.bufferSize(worker);
}
/**
* Returns the number of {@link MantisWorker}s currently in the pool.
*/
int size() {
return pool.size();
}
/**
* Returns the total number of {@link MantisWorker} that can be cached by this pool.
*/
int capacity() {
return capacity;
}
}
| 8,301 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/EventDrainerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.config.MrePublishConfiguration;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EventDrainerTest {
private StreamManager streamManager;
private EventProcessor processor;
private EventTransmitter transmitter;
private EventDrainer drainer;
@BeforeEach
void setup() {
MrePublishConfiguration config = mock(MrePublishConfiguration.class);
Registry registry = new DefaultRegistry();
streamManager = mock(StreamManager.class);
processor = mock(EventProcessor.class);
transmitter = mock(EventTransmitter.class);
Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC);
drainer = new EventDrainer(
config,
streamManager,
registry,
processor,
transmitter,
clock);
Set<String> streams = new HashSet<>();
streams.add("requestEvents");
when(streamManager.getRegisteredStreams()).thenReturn(streams);
}
@AfterEach
void teardown() {
}
@Test
void shouldDrainAndSendForExistingSubscribers() {
when(streamManager.hasSubscriptions(anyString())).thenReturn(true);
BlockingQueue<Event> events = new LinkedBlockingQueue<>();
Event event = new Event();
event.set("k1", "v1");
events.offer(event);
when(streamManager.getQueueForStream(anyString()))
.thenReturn(Optional.of(events));
when(processor.process(anyString(), any(Event.class)))
.thenReturn(mock(Event.class));
drainer.run();
verify(transmitter, times(1))
.send(any(Event.class), any());
}
@Test
void shouldDrainAndNoopForNonexistentSubscribers() {
when(streamManager.hasSubscriptions(anyString())).thenReturn(false);
drainer.run();
verify(transmitter, times(0))
.send(any(Event.class), any());
}
} | 8,302 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/EventProcessorTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.api.config.SettableConfig;
import com.netflix.archaius.config.DefaultSettableConfig;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.internal.mql.MQLSubscription;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class EventProcessorTest {
private StreamManager streamManager;
private EventProcessor eventProcessor;
@BeforeEach
void setUp() {
SettableConfig config = new DefaultSettableConfig();
config.setProperty(SampleArchaiusMrePublishConfiguration.MRE_CLIENT_BLACKLIST_KEYS_PROP, "param.password");
PropertyRepository repository =
DefaultPropertyFactory.from(config);
streamManager = mock(StreamManager.class);
MrePublishConfiguration mrePublishConfiguration = new SampleArchaiusMrePublishConfiguration(repository);
Tee tee = mock(Tee.class);
doNothing().when(tee).tee(anyString(), any(Event.class));
eventProcessor = new EventProcessor(mrePublishConfiguration, streamManager, tee);
}
@Test
void shouldReturnEnrichedEventForStream() throws Exception {
when(streamManager.hasSubscriptions(anyString())).thenReturn(true);
SettableConfig config = new DefaultSettableConfig();
PropertyRepository repository =
DefaultPropertyFactory.from(config);
MrePublishConfiguration mrePublishConfiguration = new SampleArchaiusMrePublishConfiguration(repository);
Subscription subscription = new MQLSubscription("id", "select * where true");
Set<Subscription> subscriptions = new ConcurrentSkipListSet<>();
subscriptions.add(subscription);
when(streamManager.getStreamSubscriptions(anyString())).thenReturn(subscriptions);
Event event = new Event();
event.set("k1", "v1");
Event actual = eventProcessor.process(StreamType.DEFAULT_EVENT_STREAM, event);
// Single event with a `select * where true` yields the single event.
assertEquals(actual.get("mantisStream"), StreamType.DEFAULT_EVENT_STREAM);
assertEquals(actual.get("type"), "EVENT");
assertEquals(actual.get("k1"), "v1");
assertEquals(((ArrayList)actual.get("matched-clients")).size(), 1);
assertEquals(((ArrayList)actual.get("matched-clients")).get(0), "id");
}
@Test
void shouldReturnEmptyEventForStream() throws Exception {
when(streamManager.hasSubscriptions(anyString())).thenReturn(false);
Event event = new Event();
event.set("k1", "v1");
Event actual = eventProcessor.process(StreamType.DEFAULT_EVENT_STREAM, event);
// No subscriptions
assertNull(actual);
Subscription subscription = mock(MQLSubscription.class);
when(subscription.matches(any(Event.class))).thenReturn(false);
Set<Subscription> subscriptions = new ConcurrentSkipListSet<>();
subscriptions.add(subscription);
when(streamManager.getStreamSubscriptions(anyString())).thenReturn(subscriptions);
actual = eventProcessor.process(StreamType.DEFAULT_EVENT_STREAM, event);
// A subscription exists but doesn't match.
assertNull(actual);
}
@Test
void shouldMaskSensitiveFields() {
Map<String, Object> data = new HashMap<>();
data.put("param.password", "hunter2");
data.put("myname", "mantis");
Event re = new Event(data);
eventProcessor.maskSensitiveFields(re);
assertSame("***", re.get("param.password"));
assertEquals(re.get("myname"), "mantis");
}
@Test
void shouldHandleJava8Time() {
Map<String, Object> data = new HashMap<>();
data.put("myname", "mantis");
data.put("time", Instant.parse("2000-01-01T00:01:00.00Z"));
Event re = new Event(data);
assertEquals("{\"myname\":\"mantis\",\"time\":946684860.000000000}", re.toJsonString());
}
}
| 8,303 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/AbstractSubscriptionTrackerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration.MAX_SUBS_PER_STREAM_FORMAT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.api.config.SettableConfig;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.proto.MantisServerSubscription;
import io.mantisrx.publish.proto.MantisServerSubscriptionEnvelope;
import io.mantisrx.shaded.com.google.common.collect.ImmutableList;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class AbstractSubscriptionTrackerTest {
private SettableConfig config;
private StreamManager streamManager;
private TestSubscriptionTracker subscriptionTracker;
private final String SOURCE_JOB_NAME = "RequestEventSubTrackerTestJobCluster";
@BeforeEach
public void setup() {
config = new DefaultSettableConfig();
config.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_EXPIRY_INTERVAL_SEC_PROP, 0);
PropertyRepository propertyRepository = DefaultPropertyFactory.from(config);
SampleArchaiusMrePublishConfiguration archaiusConfiguration = new SampleArchaiusMrePublishConfiguration(propertyRepository);
Registry registry = new DefaultRegistry();
MantisJobDiscovery mockJobDiscovery = mock(MantisJobDiscovery.class);
Map<String, String> streamJobClusterMap = new HashMap<>();
streamJobClusterMap.put(StreamType.DEFAULT_EVENT_STREAM, SOURCE_JOB_NAME);
streamJobClusterMap.put("requestStream", SOURCE_JOB_NAME);
when(mockJobDiscovery.getStreamNameToJobClusterMapping(anyString())).thenReturn(streamJobClusterMap);
streamManager = new StreamManager(registry, archaiusConfiguration);
subscriptionTracker = new TestSubscriptionTracker(archaiusConfiguration, registry, mockJobDiscovery, streamManager);
}
@Test
public void testDiscardSubscriptionsBeyondMax() {
config.setProperty(String.format(MAX_SUBS_PER_STREAM_FORMAT, StreamType.DEFAULT_EVENT_STREAM), 2);
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id3", "select * from defaultStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<String> subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("id1", "id2");
assertEquals(expected, subIds);
}
@Test
public void testDefaultStreamKeyAsStreamName() {
config.setProperty(String.format(MAX_SUBS_PER_STREAM_FORMAT, StreamType.DEFAULT_EVENT_STREAM), 2);
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<String> subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("id1", "id2");
assertEquals(expected, subIds);
}
@Test
public void testMaxSubscriptionCountChange() {
config.setProperty(String.format(MAX_SUBS_PER_STREAM_FORMAT, StreamType.DEFAULT_EVENT_STREAM), 2);
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id3", "select * from defaultStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<String> subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("id1", "id2");
assertEquals(expected, subIds);
config.setProperty(String.format(MAX_SUBS_PER_STREAM_FORMAT, StreamType.DEFAULT_EVENT_STREAM), 4);
nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id3", "select * from defaultStream where id = 3", null),
new MantisServerSubscription("id4", "select * from defaultStream where id = 4", null),
new MantisServerSubscription("id5", "select * from defaultStream where id = 5", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
expected = ImmutableSet.of("id1", "id2", "id3", "id4");
assertEquals(expected, subIds);
}
@Test
public void testSubscriptionUpdate() {
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id3", "select * from defaultStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<String> subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("id1", "id2", "id3");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id3", "select * from defaultStream where id = 3", null),
new MantisServerSubscription("id4", "select * from defaultStream where id = 4", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
expected = ImmutableSet.of("id1", "id2", "id3", "id4");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("id4", "select * from defaultStream where id = 4", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subIds = subscriptionTracker.getCurrentSubscriptions().stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
expected = ImmutableSet.of("id2", "id4");
assertEquals(expected, subIds);
}
@Test
public void testUpdateMultipleStreams() {
String requestStream = "requestStream";
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
streamManager.registerStream(requestStream);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("default_id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null)
);
List<MantisServerSubscription> nextRequestSubs = ImmutableList.of();
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<String> subIds = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM).stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("default_id1", "default_id2", "default_id3");
assertEquals(expected, subIds);
Set<Subscription> subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "default_id3");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("request_id4", "select * from requestStream where id = 4", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subs = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("default_id1");
assertEquals(expected, subIds);
subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "request_id4");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("request_id4", "select * from requestStream where id = 4", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subs = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("default_id1", "default_id3");
assertEquals(expected, subIds);
subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "request_id4", "default_id3");
assertEquals(expected, subIds);
}
@Test
public void testUpdateMultipleStreamsWithUnionSubscriptions() {
String requestStream = "requestStream";
streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM);
streamManager.registerStream(requestStream);
List<MantisServerSubscription> nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("default_id2", "select * from defaultStream where id = 2", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
Set<Subscription> subs = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
Set<String> subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
Set<String> expected = ImmutableSet.of("default_id1", "default_id2", "default_id3");
assertEquals(expected, subIds);
subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "default_id3");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("request_id4", "select * from requestStream where id = 4", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subs = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("default_id1");
assertEquals(expected, subIds);
subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "request_id4");
assertEquals(expected, subIds);
nextSubs = ImmutableList.of(
new MantisServerSubscription("default_id1", "select * from defaultStream where id = 1", null),
new MantisServerSubscription("request_id1", "select * from requestStream where id = 1", null),
new MantisServerSubscription("request_id2", "select * from requestStream where id = 2", null),
new MantisServerSubscription("request_id4", "select * from requestStream where id = 4", null),
new MantisServerSubscription("default_id3", "select * from defaultStream, requestStream where id = 3", null)
);
subscriptionTracker.setSubscriptions(ImmutableMap.of(SOURCE_JOB_NAME, nextSubs));
subs = streamManager.getStreamSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("default_id1", "default_id3");
assertEquals(expected, subIds);
subs = streamManager.getStreamSubscriptions(requestStream);
subIds = subs.stream().map(Subscription::getSubscriptionId).collect(Collectors.toSet());
expected = ImmutableSet.of("request_id1", "request_id2", "request_id4", "default_id3");
assertEquals(expected, subIds);
}
public static class TestSubscriptionTracker extends AbstractSubscriptionTracker {
private Map<String, List<MantisServerSubscription>> nextSubscriptions;
public TestSubscriptionTracker(
MrePublishConfiguration mrePublishConfiguration,
Registry registry,
MantisJobDiscovery jobDiscovery,
StreamManager streamManager) {
super(mrePublishConfiguration, registry, jobDiscovery, streamManager);
}
/**
* Set next subscriptions for a job cluster
* @param subscriptions A {@link Map} of jobCluster to subscription.
* */
public void setSubscriptions(Map<String, List<MantisServerSubscription>> subscriptions) {
this.nextSubscriptions = subscriptions;
this.refreshSubscriptions();
}
@Override
public Optional<MantisServerSubscriptionEnvelope> fetchSubscriptions(String jobCluster) {
if (nextSubscriptions != null && !nextSubscriptions.isEmpty()) {
return Optional.of(new MantisServerSubscriptionEnvelope(nextSubscriptions.get(jobCluster)));
} else {
return Optional.empty();
}
}
}
}
| 8,304 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/DefaultSubscriptionTrackerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.verify;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.ipc.http.HttpClient;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.discovery.proto.StageWorkers;
import io.mantisrx.discovery.proto.StreamJobClusterMap;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.proto.MantisServerSubscription;
import io.mantisrx.publish.proto.MantisServerSubscriptionEnvelope;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
public class DefaultSubscriptionTrackerTest {
private static final int subscriptionExpiryIntervalSec = 3;
private final Map<String, String> streamJobClusterMap = new HashMap<>();
@Rule
public WireMockRule mantisWorker1 = new WireMockRule(options().dynamicPort());
@Rule
public WireMockRule mantisWorker2 = new WireMockRule(options().dynamicPort());
@Rule
public WireMockRule mantisWorker3 = new WireMockRule(options().dynamicPort());
private DefaultSubscriptionTracker subscriptionTracker;
private MantisJobDiscovery mockJobDiscovery;
private StreamManager mockStreamManager;
private HttpClient httpClient;
public DefaultSubscriptionTrackerTest() {
streamJobClusterMap.put(StreamType.DEFAULT_EVENT_STREAM, "RequestEventSubTrackerTestJobCluster");
streamJobClusterMap.put(StreamType.LOG_EVENT_STREAM, "LogEventSubTrackerTestJobCluster");
}
private MrePublishConfiguration testConfig() {
DefaultSettableConfig settableConfig = new DefaultSettableConfig();
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.DEFAULT_EVENT_STREAM, streamJobClusterMap.get(StreamType.DEFAULT_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.LOG_EVENT_STREAM, streamJobClusterMap.get(StreamType.LOG_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_REFRESH_INTERVAL_SEC_PROP, 30);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_EXPIRY_INTERVAL_SEC_PROP, subscriptionExpiryIntervalSec);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP, 30);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_HOSTNAME_PROP, "127.0.0.1");
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_PORT_PROP, 7171);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_FETCH_QUERY_PARAMS_STR_PROP, "app=DefaultSubscriptionTrackerTest&type=unit_test");
PropertyRepository propertyRepository = DefaultPropertyFactory.from(settableConfig);
return new SampleArchaiusMrePublishConfiguration(propertyRepository);
}
protected Set<String> getCurrentSubIds(String streamName) {
String lookupKey = StreamJobClusterMap.DEFAULT_STREAM_KEY.equals(streamName)
? StreamType.DEFAULT_EVENT_STREAM
: streamName;
return this.mockStreamManager.getStreamSubscriptions(lookupKey).stream().map(Subscription::getSubscriptionId)
.collect(Collectors.toSet());
}
@BeforeEach
public void setup() {
MrePublishConfiguration mrePublishConfiguration = testConfig();
Registry registry = new DefaultRegistry();
mockJobDiscovery = mock(MantisJobDiscovery.class);
mockStreamManager = spy(new StreamManager(registry, mrePublishConfiguration));
mantisWorker1.start();
mantisWorker2.start();
mantisWorker3.start();
httpClient = HttpClient.create(registry);
subscriptionTracker = new DefaultSubscriptionTracker(mrePublishConfiguration, registry, mockJobDiscovery, mockStreamManager, httpClient);
when(mockJobDiscovery.getStreamNameToJobClusterMapping(anyString())).thenReturn(streamJobClusterMap);
}
@AfterEach
public void teardown() {
mantisWorker1.shutdown();
mantisWorker2.shutdown();
mantisWorker3.shutdown();
}
@Test
public void testSubscriptionsResolveToMajorityAmongWorkers() throws IOException {
String streamName = StreamType.DEFAULT_EVENT_STREAM;
String jobCluster = streamJobClusterMap.get(streamName);
String jobId = jobCluster + "-1";
Set<String> streams = Collections.singleton(streamName);
when(mockStreamManager.getRegisteredStreams()).thenReturn(streams);
// worker 1 subs list
MantisServerSubscriptionEnvelope w1Subs = SubscriptionsHelper.createSubsEnvelope(2, 0);
mantisWorker1.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(w1Subs)))
);
// workers 2 and 3 publish the same subs list
MantisServerSubscriptionEnvelope majoritySubs = SubscriptionsHelper.createSubsEnvelope(5, 2);
mantisWorker2.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(majoritySubs)))
);
mantisWorker3.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(majoritySubs)))
);
JobDiscoveryInfo jdi = new JobDiscoveryInfo(jobCluster, jobId,
Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Arrays.asList(
new MantisWorker("127.0.0.1", mantisWorker1.port()),
new MantisWorker("127.0.0.1", mantisWorker2.port()),
new MantisWorker("127.0.0.1", mantisWorker3.port())
))));
when(mockJobDiscovery.getCurrentJobWorkers(jobCluster)).thenReturn(Optional.of(jdi));
for (String stream : streamJobClusterMap.keySet()) {
if (!stream.equals(StreamType.DEFAULT_EVENT_STREAM)) {
when(mockJobDiscovery.getCurrentJobWorkers(streamJobClusterMap.get(streamJobClusterMap.get(stream)))).thenReturn(Optional.empty());
}
}
subscriptionTracker.refreshSubscriptions();
Set<String> currentSubIds = getCurrentSubIds(streamName);
// subs resolved to majority among workers
assertEquals(majoritySubs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds);
assertNotEquals(w1Subs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds);
// verify all new subscriptions propagated as ADD to StreamManager
ArgumentCaptor<Subscription> captor = ArgumentCaptor.forClass(Subscription.class);
verify(mockStreamManager, times(5)).addStreamSubscription(captor.capture());
List<Subscription> subsAdded = captor.getAllValues();
Map<String, Subscription> subIdToSubMap = subsAdded.stream().collect(Collectors.toMap(Subscription::getSubscriptionId, s -> s));
assertEquals(majoritySubs.getSubscriptionList().size(), subIdToSubMap.size());
majoritySubs.getSubscriptionList().forEach(sub -> {
assertTrue(subIdToSubMap.containsKey(sub.getSubscriptionId()));
assertEquals(sub.getQuery(), subIdToSubMap.get(sub.getSubscriptionId()).getRawQuery());
});
}
@Test
public void testSubscriptionsFetchFailureHandling() throws IOException, InterruptedException {
String streamName = StreamType.DEFAULT_EVENT_STREAM;
String jobCluster = streamJobClusterMap.get(streamName);
String jobId = jobCluster + "-1";
Set<String> streams = Collections.singleton(streamName);
when(mockStreamManager.getRegisteredStreams()).thenReturn(streams);
// worker 1 subs list
MantisServerSubscriptionEnvelope majoritySubs = SubscriptionsHelper.createSubsEnvelope(2, 0);
mantisWorker1.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(majoritySubs)))
);
JobDiscoveryInfo jdi = new JobDiscoveryInfo(jobCluster, jobId,
Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Collections.singletonList(
new MantisWorker("127.0.0.1", mantisWorker1.port())
))));
when(mockJobDiscovery.getCurrentJobWorkers(jobCluster)).thenReturn(Optional.of(jdi));
for (String stream : streamJobClusterMap.keySet()) {
if (!stream.equals(StreamType.DEFAULT_EVENT_STREAM)) {
when(mockJobDiscovery.getCurrentJobWorkers(streamJobClusterMap.get(streamJobClusterMap.get(stream)))).thenReturn(Optional.empty());
}
}
subscriptionTracker.refreshSubscriptions();
Set<String> currentSubIds = getCurrentSubIds(streamName);
// subs resolved to majority among workers
assertEquals(majoritySubs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds);
// verify all new subscriptions propagated as ADD to StreamManager
ArgumentCaptor<Subscription> captor = ArgumentCaptor.forClass(Subscription.class);
verify(mockStreamManager, times(2)).addStreamSubscription(captor.capture());
List<Subscription> subsAdded = captor.getAllValues();
Map<String, Subscription> subIdToSubMap = subsAdded.stream().collect(Collectors.toMap(Subscription::getSubscriptionId, s -> s));
assertEquals(majoritySubs.getSubscriptionList().size(), subIdToSubMap.size());
majoritySubs.getSubscriptionList().forEach(sub -> {
assertTrue(subIdToSubMap.containsKey(sub.getSubscriptionId()));
assertEquals(sub.getQuery(), subIdToSubMap.get(sub.getSubscriptionId()).getRawQuery());
});
// simulate a subscription fetch failure on next refresh
mantisWorker1.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(400)
));
subscriptionTracker.refreshSubscriptions();
Set<String> currentSubIds2 = getCurrentSubIds(streamName);
// subs resolved to majority among workers
assertEquals(majoritySubs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds2);
Thread.sleep(subscriptionExpiryIntervalSec * 1000 + 100);
subscriptionTracker.refreshSubscriptions();
assertTrue(getCurrentSubIds(streamName).isEmpty());
// verify all previously added subscriptions cleaned up and propagated as REMOVE to StreamManager
ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class);
verify(mockStreamManager, times(2)).removeStreamSubscription(captor2.capture());
List<String> subsAdded2 = captor2.getAllValues();
assertEquals(majoritySubs.getSubscriptionList().size(), subsAdded2.size());
majoritySubs.getSubscriptionList().forEach(sub -> {
assertTrue(subsAdded2.contains(sub.getSubscriptionId()));
});
}
@Disabled("broken test; somewhere from git commit: de88e88ba8b..a64e8d1ad68")
public void testJobDiscoveryFailureHandling() throws IOException, InterruptedException {
String streamName = StreamType.DEFAULT_EVENT_STREAM;
String jobCluster = streamJobClusterMap.get(streamName);
String jobId = jobCluster + "-1";
Set<String> streams = Collections.singleton(streamName);
when(mockStreamManager.getRegisteredStreams()).thenReturn(streams);
// worker 1 subs list
MantisServerSubscriptionEnvelope majoritySubs = SubscriptionsHelper.createSubsEnvelope(2, 0);
mantisWorker1.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(majoritySubs)))
);
JobDiscoveryInfo jdi = new JobDiscoveryInfo(jobCluster, jobId,
Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Collections.singletonList(
new MantisWorker("127.0.0.1", mantisWorker1.port())
))));
when(mockJobDiscovery.getCurrentJobWorkers(jobCluster)).thenReturn(Optional.of(jdi));
for (String stream : streamJobClusterMap.keySet()) {
if (!stream.equals(StreamType.DEFAULT_EVENT_STREAM)) {
when(mockJobDiscovery.getCurrentJobWorkers(streamJobClusterMap.get(streamJobClusterMap.get(stream)))).thenReturn(Optional.empty());
}
}
subscriptionTracker.refreshSubscriptions();
Set<String> currentSubIds = getCurrentSubIds(streamName);
// subs resolved to majority among workers
assertEquals(majoritySubs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds);
// verify all new subscriptions propagated as ADD to StreamManager
ArgumentCaptor<Subscription> captor = ArgumentCaptor.forClass(Subscription.class);
verify(mockStreamManager, times(2)).addStreamSubscription(captor.capture());
List<Subscription> subsAdded = captor.getAllValues();
Map<String, Subscription> subIdToSubMap = subsAdded.stream().collect(Collectors.toMap(Subscription::getSubscriptionId, s -> s));
assertEquals(majoritySubs.getSubscriptionList().size(), subIdToSubMap.size());
majoritySubs.getSubscriptionList().forEach(sub -> {
assertTrue(subIdToSubMap.containsKey(sub.getSubscriptionId()));
assertEquals(sub.getQuery(), subIdToSubMap.get(sub.getSubscriptionId()).getRawQuery());
});
// simulate the job discovery fetch failure
when(mockJobDiscovery.getCurrentJobWorkers(jobCluster)).thenReturn(Optional.empty());
subscriptionTracker.refreshSubscriptions();
Set<String> currentSubIds2 = getCurrentSubIds(streamName);
// subs resolved to majority among workers
assertEquals(majoritySubs.getSubscriptions().stream().map(MantisServerSubscription::getSubscriptionId).collect(Collectors.toSet()), currentSubIds2);
// sleep for subs expiry interval and refreshSubs to trigger a cleanup of subs due to job discovery failure
Thread.sleep(subscriptionExpiryIntervalSec * 1000 + 100);
subscriptionTracker.refreshSubscriptions();
assertTrue(getCurrentSubIds(streamName).isEmpty());
// verify all previously added subscriptions cleaned up and propagated as REMOVE to StreamManager
ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class);
verify(mockStreamManager, times(2)).removeStreamSubscription(captor2.capture());
List<String> subsAdded2 = captor2.getAllValues();
assertEquals(majoritySubs.getSubscriptionList().size(), subsAdded2.size());
majoritySubs.getSubscriptionList().forEach(sub -> {
assertTrue(subsAdded2.contains(sub.getSubscriptionId()));
});
}
@Test
public void testSubsNotRefreshOnNoRegisteredStreams() throws IOException {
String streamName = StreamType.DEFAULT_EVENT_STREAM;
String jobCluster = streamJobClusterMap.get(streamName);
String jobId = jobCluster + "-1";
Set<String> streams = Collections.singleton(streamName);
when(mockStreamManager.getRegisteredStreams()).thenReturn(Collections.emptySet(), streams);
// when(mockStreamManager.getRegisteredStreams()).thenReturn(streams);
// worker 1 subs list
MantisServerSubscriptionEnvelope majoritySubs = SubscriptionsHelper.createSubsEnvelope(2, 0);
mantisWorker1.stubFor(get(urlMatching("/\\?jobId=.*"))
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(majoritySubs)))
);
JobDiscoveryInfo jdi = new JobDiscoveryInfo(jobCluster, jobId,
Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Collections.singletonList(
new MantisWorker("127.0.0.1", mantisWorker1.port())
))));
when(mockJobDiscovery.getCurrentJobWorkers(jobCluster)).thenReturn(Optional.of(jdi));
for (String stream : streamJobClusterMap.keySet()) {
if (!stream.equals(StreamType.DEFAULT_EVENT_STREAM)) {
when(mockJobDiscovery.getCurrentJobWorkers(streamJobClusterMap.get(streamJobClusterMap.get(stream)))).thenReturn(Optional.empty());
}
}
subscriptionTracker.refreshSubscriptions();
assertTrue(getCurrentSubIds(streamName).isEmpty());
verify(mockStreamManager, times(1)).getRegisteredStreams();
verifyZeroInteractions(mockJobDiscovery);
}
private static class SubscriptionsHelper {
static MantisServerSubscriptionEnvelope createSubsEnvelope(int numSubs, int offset) {
List<MantisServerSubscription> subList = new ArrayList<>(numSubs);
for (int i = 0; i < numSubs; i++) {
String subId = "testSubId-" + (i + offset);
String query = "SELECT * FROM stream";
subList.add(new MantisServerSubscription(subId, query));
}
return new MantisServerSubscriptionEnvelope(subList);
}
}
}
| 8,305 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/MantisEventPublisherTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.DefaultSettableConfig;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.api.PublishStatus;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
public class MantisEventPublisherTest {
private MrePublishConfiguration testConfig(boolean mantisPublishClientEnabled) {
DefaultSettableConfig settableConfig = new DefaultSettableConfig();
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.MRE_CLIENT_ENABLED_PROP, mantisPublishClientEnabled);
PropertyRepository propertyRepository = DefaultPropertyFactory.from(settableConfig);
return new SampleArchaiusMrePublishConfiguration(propertyRepository);
}
private StreamManager streamManager;
@Before
public void setup() {
streamManager = mock(StreamManager.class);
}
private void assertStatusAsync(PublishStatus expected, CompletionStage<PublishStatus> actualF) {
final CountDownLatch latch = new CountDownLatch(1);
actualF.whenComplete((s, t) -> {
try {
assertEquals(expected, s);
latch.countDown();
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
});
try {
assertTrue("timed out waiting for status callback", latch.await(1, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private Event testEvent() {
return new Event(new HashMap<>(Collections.singletonMap("k", "v")));
}
@Test
public void testPublishStatusEnqueued() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.of(new LinkedBlockingDeque<>()));
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(true);
boolean publishEnabled = true;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(new Event(new HashMap<>(Collections.singletonMap("k", "v"))));
assertStatusAsync(PublishStatus.ENQUEUED, statusF);
}
@Test
public void testPublishStatusSkipOnDisabled() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.of(new LinkedBlockingDeque<>()));
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(true);
boolean publishEnabled = false;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(testEvent());
assertStatusAsync(PublishStatus.SKIPPED_CLIENT_NOT_ENABLED, statusF);
}
@Test
public void testPublishStatusSkipOnInvalidEvent() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.of(new LinkedBlockingDeque<>()));
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(true);
boolean publishEnabled = true;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(new Event());
assertStatusAsync(PublishStatus.SKIPPED_INVALID_EVENT, statusF);
}
@Test
public void testPublishStatusSkipOnNoSubscriptions() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.of(new LinkedBlockingDeque<>()));
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(false);
boolean publishEnabled = true;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(testEvent());
assertStatusAsync(PublishStatus.SKIPPED_NO_SUBSCRIPTIONS, statusF);
}
@Test
public void testPublishStatusFailOnStreamNotRegistered() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.empty());
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(true);
boolean publishEnabled = true;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(testEvent());
assertStatusAsync(PublishStatus.FAILED_STREAM_NOT_REGISTERED, statusF);
}
@Test
public void testPublishStatusFailOnQueueFull() {
when(streamManager.registerStream(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(Optional.ofNullable(new LinkedBlockingQueue<>(1)));
when(streamManager.hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM)).thenReturn(true);
boolean publishEnabled = true;
MantisEventPublisher eventPublisher = new MantisEventPublisher(testConfig(publishEnabled), streamManager);
CompletionStage<PublishStatus> statusF = eventPublisher.publish(testEvent());
statusF.whenComplete((s, t) -> assertEquals(PublishStatus.ENQUEUED, s));
CompletionStage<PublishStatus> statusF2 = eventPublisher.publish(testEvent());
statusF2.whenComplete((s, t) -> assertEquals(PublishStatus.FAILED_QUEUE_FULL, s));
}
}
| 8,306 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/StreamManagerTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.api.config.SettableConfig;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.spectator.api.DefaultRegistry;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.core.SubscriptionFactory;
import java.util.Iterator;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class StreamManagerTest {
private SettableConfig config;
private StreamManager streamManager;
@BeforeEach
void setUp() {
config = new DefaultSettableConfig();
PropertyRepository propertyRepository = DefaultPropertyFactory.from(config);
SampleArchaiusMrePublishConfiguration archaiusConfiguration = new SampleArchaiusMrePublishConfiguration(propertyRepository);
streamManager = new StreamManager(new DefaultRegistry(), archaiusConfiguration);
}
@Test
void testCreateStreamQueue() {
final String streamName = "testStream";
streamManager.registerStream(streamName);
assertFalse(streamManager.hasSubscriptions(streamName));
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
Set<Subscription> streamSubscriptions =
streamManager.getStreamSubscriptions(streamName);
assertEquals(0, streamSubscriptions.size());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
}
@Test
void testAddStreamSubscription() {
final String streamName = StreamType.DEFAULT_EVENT_STREAM;
Optional<Subscription> subscriptionO =
SubscriptionFactory.getSubscription("subId1", "false");
assertTrue(subscriptionO.isPresent());
streamManager.addStreamSubscription(subscriptionO.get());
assertTrue(streamManager.hasSubscriptions(streamName));
Set<Subscription> streamSubscriptions =
streamManager.getStreamSubscriptions(streamName);
assertEquals(1, streamSubscriptions.size());
for (final Subscription s : streamSubscriptions) {
assertEquals(s, subscriptionO.get());
}
assertFalse(streamManager.getQueueForStream(streamName).isPresent());
assertFalse(streamManager.getStreamMetrics(streamName).isPresent());
assertTrue(streamManager.getRegisteredStreams().isEmpty());
}
@Test
void testInvalidSubscription() {
Optional<Subscription> subscriptionO = SubscriptionFactory.getSubscription("subId1", "SELECT * FROM stream WHERE true SAMPLE {\\\"strategy\\\":\\\"RANDOM\\\", \\\"threshold\\\":200}");
assertFalse(subscriptionO.isPresent());
}
@Test
void testAddRemoveStreamSubscription() {
final String streamName = "testStream";
// create stream queue
streamManager.registerStream(streamName);
// add subscription
Optional<Subscription> subscriptionO = SubscriptionFactory
.getSubscription("subId2", "SELECT a,b FROM " + streamName);
assertTrue(subscriptionO.isPresent());
streamManager.addStreamSubscription(subscriptionO.get());
assertTrue(streamManager.hasSubscriptions(streamName));
Set<Subscription> streamSubscriptions =
streamManager.getStreamSubscriptions(streamName);
assertEquals(1, streamSubscriptions.size());
for (final Subscription s : streamSubscriptions) {
assertEquals(s, subscriptionO.get());
}
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
streamManager.removeStreamSubscription(subscriptionO.get());
assertFalse(streamManager.hasSubscriptions(streamName));
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
}
@Test
void testAddRemoveStreamSubscription2() {
final String streamName = "testStream";
// create stream queue
streamManager.registerStream(streamName);
// add subscription
Optional<Subscription> subscriptionO = SubscriptionFactory
.getSubscription("subId2", "SELECT a,b FROM " + streamName);
assertTrue(subscriptionO.isPresent());
streamManager.addStreamSubscription(subscriptionO.get());
assertTrue(streamManager.hasSubscriptions(streamName));
Set<Subscription> streamSubscriptions = streamManager.getStreamSubscriptions(streamName);
assertEquals(1, streamSubscriptions.size());
for (final Subscription s : streamSubscriptions) {
assertEquals(s, subscriptionO.get());
}
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
// add subscription with duplicate subscriptionId should replace old subscription
Optional<Subscription> subscriptionO2 = SubscriptionFactory
.getSubscription("subId2", "SELECT a,b,c FROM " + streamName);
assertTrue(subscriptionO2.isPresent());
streamManager.addStreamSubscription(subscriptionO2.get());
assertTrue(streamManager.hasSubscriptions(streamName));
Set<Subscription> streamSubscriptions2 = streamManager.getStreamSubscriptions(streamName);
assertEquals(1, streamSubscriptions2.size());
Iterator<Subscription> iterator = streamSubscriptions2.iterator();
assertEquals(subscriptionO2.get(), iterator.next());
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
// remove sub
streamManager.removeStreamSubscription(subscriptionO.get());
assertFalse(streamManager.hasSubscriptions(streamName));
assertEquals(0, streamManager.getStreamSubscriptions(streamName).size());
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
}
@Test
void testAddRemoveStreamSubscriptionId() {
final String streamName = "testStream";
// create stream queue
streamManager.registerStream(streamName);
// add subscription
final String subId = "subId3";
Optional<Subscription> subscriptionO = SubscriptionFactory
.getSubscription(subId, "SELECT * FROM " + streamName);
assertTrue(subscriptionO.isPresent());
streamManager.addStreamSubscription(subscriptionO.get());
assertTrue(streamManager.hasSubscriptions(streamName));
Set<Subscription> streamSubscriptions =
streamManager.getStreamSubscriptions(streamName);
assertEquals(1, streamSubscriptions.size());
for (final Subscription s : streamSubscriptions) {
assertEquals(s, subscriptionO.get());
}
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
streamManager.removeStreamSubscription(subId);
assertFalse(streamManager.hasSubscriptions(streamName));
assertTrue(streamManager.getQueueForStream(streamName).isPresent());
assertTrue(streamManager.getStreamMetrics(streamName).isPresent());
assertEquals(1, streamManager.getRegisteredStreams().size());
assertEquals(streamName, streamManager.getRegisteredStreams().iterator().next());
}
@Test
void testStreamLimits() throws InterruptedException {
final String streamName = "testStream";
// create stream queue
int maxStreams = 5;
config.setProperty(SampleArchaiusMrePublishConfiguration.MAX_NUM_STREAMS_NAME, maxStreams);
for (int i = 0; i < maxStreams; i++) {
config.setProperty(
String.format(SampleArchaiusMrePublishConfiguration.PER_STREAM_QUEUE_SIZE_FORMAT, streamName + "1"),
maxStreams);
assertTrue(streamManager
.registerStream(streamName + i).isPresent());
}
// stream should not get created since limit is reached
assertFalse(streamManager
.registerStream(streamName + "Trigger").isPresent());
assertEquals(maxStreams, streamManager.getRegisteredStreams().size());
// Override inactive stream duration and wait for all streams
// to become inactive before adding new streams
long inactiveMillis = 500L;
config.setProperty(
SampleArchaiusMrePublishConfiguration.STREAM_INACTIVE_DURATION_THRESHOLD_NAME,
inactiveMillis / 1000L);
Thread.sleep(inactiveMillis * 2);
for (int i = 0; i < maxStreams; i++) {
assertTrue(streamManager
.registerStream(streamName + "New" + i).isPresent());
}
assertEquals(maxStreams, streamManager.getRegisteredStreams().size());
// revert the inactive stream duration threshold
config.setProperty(
SampleArchaiusMrePublishConfiguration.STREAM_INACTIVE_DURATION_THRESHOLD_NAME, 24 * 60 * 60);
}
}
| 8,307 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/internal/discovery/MantisJobDiscoveryTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.junit.jupiter.api.Assertions.*;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.ipc.http.HttpClient;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.publish.DefaultObjectMapper;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.mantisapi.DefaultMantisApiClient;
import io.mantisrx.publish.internal.discovery.mantisapi.MantisApiClient;
import io.mantisrx.publish.internal.discovery.proto.JobSchedulingInfo;
import io.mantisrx.publish.internal.discovery.proto.MantisJobState;
import io.mantisrx.publish.internal.discovery.proto.WorkerAssignments;
import io.mantisrx.publish.internal.discovery.proto.WorkerHost;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MantisJobDiscoveryTest {
private static final Logger logger = LoggerFactory.getLogger(MantisJobDiscoveryTest.class);
private final Map<String, String> streamJobClusterMap = new HashMap<>();
@Rule
public WireMockRule mantisApi = new WireMockRule(options().dynamicPort());
private MrePublishConfiguration config;
private MantisJobDiscovery jobDiscovery;
public MantisJobDiscoveryTest() {
streamJobClusterMap.put(StreamType.DEFAULT_EVENT_STREAM, "RequestEventSubTrackerTestJobCluster");
streamJobClusterMap.put(StreamType.LOG_EVENT_STREAM, "LogEventSubTrackerTestJobCluster");
}
private MrePublishConfiguration testConfig() {
DefaultSettableConfig settableConfig = new DefaultSettableConfig();
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.DEFAULT_EVENT_STREAM, streamJobClusterMap.get(StreamType.DEFAULT_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.LOG_EVENT_STREAM, streamJobClusterMap.get(StreamType.LOG_EVENT_STREAM));
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.SUBS_REFRESH_INTERVAL_SEC_PROP, 30);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP, 1);
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_HOSTNAME_PROP, "127.0.0.1");
settableConfig.setProperty(SampleArchaiusMrePublishConfiguration.DISCOVERY_API_PORT_PROP, mantisApi.port());
PropertyRepository propertyRepository = DefaultPropertyFactory.from(settableConfig);
return new SampleArchaiusMrePublishConfiguration(propertyRepository);
}
@BeforeEach
public void setup() {
mantisApi.start();
config = testConfig();
Registry registry = new DefaultRegistry();
MantisApiClient mantisApiClient = new DefaultMantisApiClient(config, HttpClient.create(registry));
this.jobDiscovery = new MantisJobDiscoveryCachingImpl(config, registry, mantisApiClient);
}
@AfterEach
public void teardown() {
mantisApi.shutdown();
}
@Test
public void testJobDiscoveryFetch() throws IOException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
String jobId = jobCluster + "-1";
JobSchedulingInfo jobSchedulingInfo = new JobSchedulingInfo(jobId, Collections.singletonMap(1, new WorkerAssignments(1, 1, Collections.singletonMap(1,
new WorkerHost("127.0.0.1", 0, Collections.emptyList(), MantisJobState.Started, 1, 7777, 7151)
))));
// JobDiscoveryInfo jobDiscoveryInfo = new JobDiscoveryInfo(jobCluster, jobId,
// Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Arrays.asList(
// new MantisWorker("127.0.0.1", 7151)
// ))));
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getHost());
}
@Test
@Ignore("another flaky test")
public void testJobDiscoveryFetchFailureHandlingAfterSuccess() throws IOException, InterruptedException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
String jobId = jobCluster + "-1";
JobSchedulingInfo jobSchedulingInfo = new JobSchedulingInfo(jobId, Collections.singletonMap(1, new WorkerAssignments(1, 1, Collections.singletonMap(1,
new WorkerHost("127.0.0.1", 0, Collections.emptyList(), MantisJobState.Started, 1, 7777, 7151)
))));
// JobDiscoveryInfo jobDiscoveryInfo = new JobDiscoveryInfo(jobCluster, jobId,
// Collections.singletonMap(1, new StageWorkers(jobCluster, jobId, 1, Arrays.asList(
// new MantisWorker("127.0.0.1", 7151)
// ))));
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(200)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers.get().getIngestStageWorkers().getWorkers().get(0).getHost());
logger.info("sleep to force a refresh after configured interval");
Thread.sleep((config.jobDiscoveryRefreshIntervalSec() + 1) * 1000);
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(503)
.withBody(DefaultObjectMapper.getInstance().writeValueAsBytes(jobSchedulingInfo)))
);
Optional<JobDiscoveryInfo> currentJobWorkers2 = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers2.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers2.get().getIngestStageWorkers().getWorkers().get(0).getHost());
logger.info("sleep to let async refresh complete");
Thread.sleep(1000);
mantisApi.verify(2, getRequestedFor(urlMatching("/jobClusters/discoveryInfo/" + jobCluster)));
// should continue serving old Job Discovery data after a 503
Optional<JobDiscoveryInfo> currentJobWorkers3 = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertTrue(currentJobWorkers3.isPresent());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().size(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().size());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getCustomPort(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().get(0).getPort());
assertEquals(jobSchedulingInfo.getWorkerAssignments().get(1).getHosts().get(1).getHost(), currentJobWorkers3.get().getIngestStageWorkers().getWorkers().get(0).getHost());
}
@Test
public void testJobDiscoveryFetch4XXRespHandling() throws InterruptedException {
String jobCluster = "MantisJobDiscoveryTestJobCluster";
// worker 1 subs list
mantisApi.stubFor(get("/jobClusters/discoveryInfo/" + jobCluster)
.willReturn(aResponse()
.withStatus(404)
.withBody("")
));
int iterations = 3;
for (int i = 0; i < iterations; i++) {
Optional<JobDiscoveryInfo> currentJobWorkers = jobDiscovery.getCurrentJobWorkers(jobCluster);
assertFalse(currentJobWorkers.isPresent());
Thread.sleep((config.jobDiscoveryRefreshIntervalSec() + 1) * 1000);
}
mantisApi.verify(iterations, getRequestedFor(urlMatching("/jobClusters/discoveryInfo/" + jobCluster)));
}
}
| 8,308 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/test/java/io/mantisrx/publish/internal/discovery/mantisapi/DefaultMantisApiClientTest.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.mantisapi;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.google.common.collect.Lists;
import com.netflix.archaius.DefaultPropertyFactory;
import com.netflix.archaius.api.PropertyRepository;
import com.netflix.archaius.config.DefaultSettableConfig;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.ipc.http.HttpClient;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.discovery.proto.StageWorkers;
import io.mantisrx.publish.config.SampleArchaiusMrePublishConfiguration;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DefaultMantisApiClientTest {
@Rule
public WireMockRule mantisAPI = new WireMockRule(options().dynamicPort());
@BeforeEach
public void setup() {
mantisAPI.start();
}
@AfterEach
public void teardown() {
mantisAPI.shutdown();
}
@Test
public void simpleTest() throws Exception {
mantisAPI.stubFor(get(urlMatching("/jobClusters/discoveryInfo/TestJob"))
.willReturn(aResponse()
.withStatus(200)
.withBody(readStub("mantisapi/jobclusters_discoveryinfo_stub.json"))));
mantisAPI.stubFor(get(urlMatching("/api/v1/mantis/publish/streamJobClusterMap\\?app=testApp"))
.willReturn(aResponse()
.withStatus(200)
.withBody(readStub("mantisapi/jobclustermap_stub.json"))));
final DefaultRegistry registry = new DefaultRegistry();
final Properties props = new Properties();
final DefaultSettableConfig config = new DefaultSettableConfig();
props.put("mantis.publish.discovery.api.hostname", "127.0.0.1");
props.put("mantis.publish.discovery.api.port", mantisAPI.port());
config.setProperties(props);
final PropertyRepository propsRepo = DefaultPropertyFactory.from(config);
final DefaultMantisApiClient defaultMantisApiClient = new DefaultMantisApiClient(new SampleArchaiusMrePublishConfiguration(propsRepo), HttpClient.create(registry));
final CompletableFuture<JobDiscoveryInfo> jobDiscoveryInfoCompletableFuture = defaultMantisApiClient.jobDiscoveryInfo("TestJob");
final JobDiscoveryInfo jobDiscoveryInfo = jobDiscoveryInfoCompletableFuture.get(5, TimeUnit.SECONDS);
final CompletableFuture<AppJobClustersMap> jobClusterMapping = defaultMantisApiClient.getJobClusterMapping(Optional.of("testApp"));
final AppJobClustersMap appJobClustersMap = jobClusterMapping.get(5, TimeUnit.SECONDS);
final Map<Integer, StageWorkers> stageWorkersMap = new HashMap<>();
stageWorkersMap.put(1, new StageWorkers("TestJob",
"TestJob",
1,
Lists.newArrayList(new MantisWorker("111.11.111.41", 7158), new MantisWorker("111.11.11.42", 7158))));
final JobDiscoveryInfo expectedInfo = new JobDiscoveryInfo("TestJob", "TestJob", stageWorkersMap);
final Map<String, Object> mappings = new HashMap<>();
final Map<String, String> vals = new HashMap<>();
vals.put("__default__", "SharedMrePublishEventSource");
mappings.put("testApp", vals);
final AppJobClustersMap expectedMap = new AppJobClustersMap("1", 3, mappings);
Assertions.assertEquals(expectedInfo, jobDiscoveryInfo);
Assertions.assertEquals(expectedMap, appJobClustersMap);
}
private static final byte[] readStub(String resourceFile) throws IOException {
InputStream inputStream = DefaultMantisApiClientTest.class.getClassLoader().getResourceAsStream(resourceFile);
return IOUtils.toByteArray(inputStream);
}
}
| 8,309 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/AbstractSubscriptionTracker.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import io.mantisrx.discovery.proto.StreamJobClusterMap;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.core.SubscriptionFactory;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import io.mantisrx.publish.proto.MantisServerSubscription;
import io.mantisrx.publish.proto.MantisServerSubscriptionEnvelope;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class handles the logic for stream -> job cluster discovery. A class that extends this abstract class is
* expected to perform the actual fetch given a stream and cluster names. The storage of the subscriptions is off loaded
* to the stream manager (See {@link StreamManager}). Thus, the stream manager is the source of truth of current active
* subscriptions. For the same reason, the stream manager also stores which streams are registered. This class will only
* fetch subscriptions for streams that are registered.
*/
public abstract class AbstractSubscriptionTracker implements SubscriptionTracker {
private static final Logger LOG = LoggerFactory.getLogger(AbstractSubscriptionTracker.class);
private final MrePublishConfiguration mrePublishConfiguration;
private final Registry registry;
private final MantisJobDiscovery jobDiscovery;
private final StreamManager streamManager;
private final Counter refreshSubscriptionInvokedCount;
private final Counter refreshSubscriptionSuccessCount;
private final Counter refreshSubscriptionFailedCount;
private final Counter staleSubscriptionRemovedCount;
public AbstractSubscriptionTracker(MrePublishConfiguration mrePublishConfiguration,
Registry registry,
MantisJobDiscovery jobDiscovery,
StreamManager streamManager) {
this.mrePublishConfiguration = mrePublishConfiguration;
this.registry = registry;
this.jobDiscovery = jobDiscovery;
this.streamManager = streamManager;
this.refreshSubscriptionInvokedCount = SpectatorUtils.buildAndRegisterCounter(registry,
"refreshSubscriptionInvokedCount");
this.refreshSubscriptionSuccessCount = SpectatorUtils.buildAndRegisterCounter(registry,
"refreshSubscriptionSuccessCount");
this.refreshSubscriptionFailedCount = SpectatorUtils.buildAndRegisterCounter(registry,
"refreshSubscriptionFailedCount");
this.staleSubscriptionRemovedCount = SpectatorUtils.buildAndRegisterCounter(registry,
"staleSubscriptionRemovedCount");
}
/**
* Given a set of subscriptions representing the current universe of valid subscriptions
* this function propogates the changes by adding subscriptions that are not currently
* present and removing those that are no longer present.
*
* @param currentSubscriptions A {@link Set} of {@link MantisServerSubscription} representing all current subscriptions to be added or kept if present.
* @param extension A {@link Set} of {@link MantisServerSubscription} representing a subscriptions to be kept if present but not added if not present.
* */
void propagateSubscriptionChanges(Set<MantisServerSubscription> currentSubscriptions, Set<MantisServerSubscription> extension) {
Set<Subscription> previousSubscriptions = getCurrentSubscriptions();
// Add newSubscriptions not present in previousSubscriptions
currentSubscriptions.stream()
.filter(c -> !previousSubscriptions.stream()
.map(ps -> ps.getSubscriptionId())
.collect(Collectors.toSet())
.contains(c.getSubscriptionId()))
.forEach(newSub -> {
try {
Optional<Subscription> subscription = SubscriptionFactory
.getSubscription(newSub.getSubscriptionId(), newSub.getQuery());
if (subscription.isPresent()) {
streamManager.addStreamSubscription(subscription.get());
} else {
LOG.info("will not add invalid subscription {}", newSub);
}
} catch (Throwable t) {
LOG.debug("failed to add subscription {}", newSub, t);
}
});
Set<String> idsToKeep = currentSubscriptions.stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet());
idsToKeep.addAll(extension.stream().map(x -> x.getSubscriptionId()).collect(Collectors.toSet()));
// Remove previousSubscriptions not present in currentSubscriptions and not present
// in the extension list
previousSubscriptions.stream()
.filter(o -> !idsToKeep.contains(o.getSubscriptionId()))
.forEach(o -> {
try {
streamManager.removeStreamSubscription(o.getSubscriptionId());
} catch (Throwable t) {
LOG.debug("failed to remove subscription {}", o.getSubscriptionId());
}
});
}
/**
* Get current set of subscriptions for a given jobCluster.
*
* @param jobCluster Mantis Job Cluster name
*
* @return Optional of MantisServerSubscriptionEnvelope on successful retrieval, else empty
*/
public abstract Optional<MantisServerSubscriptionEnvelope> fetchSubscriptions(String jobCluster);
/**
* Determines which job clusters (source jobs) are currently mapped to the
* specified application.
*
* @param streamJobClusterMap A {@link Map} of stream name to job cluster.
* @param registeredStreams A {@link Set} of registered streams.
*
* @return A {@link Set} of job clusters relevant to this application.
* */
private Set<String> getRelevantJobClusters(Map<String, String> streamJobClusterMap, Set<String> registeredStreams) {
Set<String> jobClustersToFetch = new HashSet<>();
for (Map.Entry<String, String> e : streamJobClusterMap.entrySet()) {
String streamName = e.getKey();
LOG.debug("processing stream {} and currently registered Streams {}", streamName, registeredStreams);
if (registeredStreams.contains(streamName)
|| StreamJobClusterMap.DEFAULT_STREAM_KEY.equals(streamName)) {
jobClustersToFetch.add(e.getValue());
} else {
LOG.debug("No server side mappings found for one or more streams {} ", registeredStreams);
LOG.debug("will not fetch subscriptions for un-registered stream {}", streamName);
}
}
return jobClustersToFetch;
}
private ConcurrentHashMap<String, SubscriptionCacheEntry> subsciptionCache = new ConcurrentHashMap<>();
private class SubscriptionCacheEntry {
public final long timestamp;
public final String sourceJob;
public final MantisServerSubscription sub;
public SubscriptionCacheEntry(long timestamp, String sourceJob, MantisServerSubscription sub) {
this.timestamp = timestamp;
this.sourceJob = sourceJob;
this.sub = sub;
}
}
@Override
public void refreshSubscriptions() {
refreshSubscriptionInvokedCount.increment();
boolean mantisPublishEnabled = mrePublishConfiguration.isMREClientEnabled();
final Set<String> registeredStreams = streamManager.getRegisteredStreams();
if (mantisPublishEnabled && !registeredStreams.isEmpty()) {
final Map<String, String> streamJobClusterMap =
jobDiscovery.getStreamNameToJobClusterMapping(mrePublishConfiguration.appName());
Set<String> jobClustersToFetch = getRelevantJobClusters(streamJobClusterMap, registeredStreams);
Set<MantisServerSubscription> allSubscriptions = new HashSet<>();
Set<String> failedJobClusters = new HashSet<>();
final long currentTimestamp = System.currentTimeMillis();
for (String jobCluster : jobClustersToFetch) {
try {
Optional<MantisServerSubscriptionEnvelope> subsEnvelopeO = fetchSubscriptions(jobCluster);
if (subsEnvelopeO.isPresent()) {
MantisServerSubscriptionEnvelope subsEnvelope = subsEnvelopeO.get();
for (MantisServerSubscription sub : subsEnvelope.getSubscriptions()) {
subsciptionCache.put(sub.getSubscriptionId(), new SubscriptionCacheEntry(currentTimestamp, jobCluster, sub));
}
allSubscriptions.addAll(subsEnvelope.getSubscriptions());
refreshSubscriptionSuccessCount.increment();
} else {
failedJobClusters.add(jobCluster);
refreshSubscriptionFailedCount.increment();
}
} catch (Exception ex) {
failedJobClusters.add(jobCluster);
LOG.info("refresh subscriptions failed for {}", jobCluster, ex);
refreshSubscriptionFailedCount.increment();
}
}
Set<MantisServerSubscription> subscriptionsToExtend = subsciptionCache.entrySet().stream()
.filter(es -> failedJobClusters.contains(es.getValue().sourceJob))
.filter(es -> currentTimestamp - es.getValue().timestamp < mrePublishConfiguration.subscriptionExpiryIntervalSec() * 1000)
.map(es -> es.getValue().sub)
.collect(Collectors.toSet());
propagateSubscriptionChanges(allSubscriptions, subscriptionsToExtend);
// Cache Eviction
subsciptionCache.entrySet().stream()
.filter(es -> currentTimestamp - es.getValue().timestamp > mrePublishConfiguration.subscriptionExpiryIntervalSec() * 1000 * 10)
.forEach(es -> subsciptionCache.remove(es.getKey()));
} else {
LOG.debug("subscription refresh skipped (client enabled {} registered streams {})",
mantisPublishEnabled, registeredStreams);
}
}
protected Set<Subscription> getCurrentSubscriptions() {
return streamManager
.getRegisteredStreams()
.stream()
.flatMap(streamName -> streamManager.getStreamSubscriptions(streamName).stream())
.collect(Collectors.toSet());
}
}
| 8,310 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/StreamManager.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import io.mantisrx.publish.internal.metrics.StreamMetrics;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StreamManager {
private static final Logger LOG = LoggerFactory.getLogger(StreamManager.class);
private final Registry registry;
private final MrePublishConfiguration config;
private final Counter mantisStreamCreateFailed;
private final ConcurrentMap<String, ConcurrentSkipListSet<Subscription>> streamSubscriptionsMap;
private final ConcurrentMap<String, List<String>> subscriptionIdToStreamsMap;
private final ConcurrentMap<String, BlockingQueue<Event>> streamQueuesMap;
private final ConcurrentMap<String, StreamMetrics> streamMetricsMap;
public StreamManager(Registry registry, MrePublishConfiguration mrePublishConfiguration) {
this.registry = registry;
this.config = mrePublishConfiguration;
this.mantisStreamCreateFailed =
SpectatorUtils.buildAndRegisterCounter(this.registry, "mantisStreamCreateFailed");
this.streamSubscriptionsMap = new ConcurrentHashMap<>();
this.subscriptionIdToStreamsMap = new ConcurrentHashMap<>();
this.streamQueuesMap = new ConcurrentHashMap<>();
this.streamMetricsMap = new ConcurrentHashMap<>();
}
synchronized Optional<BlockingQueue<Event>> registerStream(
final String streamName) {
if (!streamQueuesMap.containsKey(streamName)) {
cleanupInactiveStreamQueues();
if (streamQueuesMap.keySet().size() >= config.maxNumStreams()) {
LOG.debug("failed to create queue for stream {} (MAX_NUM_STREAMS {} exceeded)",
streamName,
config.maxNumStreams());
mantisStreamCreateFailed.increment();
return Optional.empty();
}
int qSize = config.streamQueueSize(streamName);
LOG.info("creating queue for stream {} (size: {})", streamName, qSize);
streamQueuesMap.putIfAbsent(streamName, new LinkedBlockingQueue<>(qSize));
// Stream metrics are created and registered only after
// an app tries to emit an event to that stream.
// Having a subscription for a stream does not create the StreamMetrics.
streamMetricsMap.putIfAbsent(streamName, new StreamMetrics(registry, streamName));
}
return Optional.ofNullable(streamQueuesMap.get(streamName));
}
private boolean isStreamInactive(long lastEventTs) {
// Consider Stream inactive if no events seen on the stream
// for over 1 day (default FP value).
long secondsSinceLastEvent = TimeUnit.SECONDS.convert(
System.nanoTime() - lastEventTs,
TimeUnit.NANOSECONDS);
return secondsSinceLastEvent > config.streamInactiveDurationThreshold();
}
private void cleanupInactiveStreamQueues() {
List<String> streamsToRemove = new ArrayList<>(5);
streamQueuesMap.keySet().stream()
.forEach(streamName ->
getStreamMetrics(streamName).ifPresent(m -> {
long lastEventTs = m.getLastEventOnStreamTimestamp();
if (lastEventTs != 0 && isStreamInactive(lastEventTs)) {
streamsToRemove.add(streamName);
}
})
);
streamsToRemove.stream().forEach(stream -> {
streamQueuesMap.remove(stream);
streamMetricsMap.remove(stream);
});
}
Optional<BlockingQueue<Event>> getQueueForStream(final String streamName) {
return Optional.ofNullable(streamQueuesMap.get(streamName));
}
Optional<StreamMetrics> getStreamMetrics(final String streamName) {
return Optional.ofNullable(streamMetricsMap.get(streamName));
}
boolean hasSubscriptions(final String streamName) {
return Optional.ofNullable(streamSubscriptionsMap.get(streamName))
.map(subs -> !subs.isEmpty())
.orElse(false);
}
private List<String> sanitizeStreamSubjects(final List<String> subjects) {
return subjects.stream()
.map(s -> {
if (s.toLowerCase().equals("observable") ||
s.toLowerCase().equals("stream")) {
// Translate the legacy default stream names to map to the default stream.
return StreamType.DEFAULT_EVENT_STREAM;
} else {
return s;
}
}).collect(Collectors.toList());
}
private void handleDuplicateSubscriptionId(final Subscription sub) {
String subId = sub.getSubscriptionId();
Optional.ofNullable(subscriptionIdToStreamsMap.get(subId))
.ifPresent(streams -> removeSubscriptionId(streams, subId));
}
synchronized void addStreamSubscription(final Subscription sub) {
List<String> streams = sanitizeStreamSubjects(sub.getSubjects());
LOG.info("adding subscription {} with streams {}", sub, streams);
handleDuplicateSubscriptionId(sub);
for (String stream : streams) {
streamSubscriptionsMap.putIfAbsent(stream, new ConcurrentSkipListSet<>());
ConcurrentSkipListSet<Subscription> subs = streamSubscriptionsMap.get(stream);
int maxSubs = config.maxSubscriptions(stream);
// Remove any existing subs with same subscriptionId (if any).
subs.removeIf(s -> s.getSubscriptionId().equals(sub.getSubscriptionId()));
subs.add(sub);
int numSubs = subs.size();
if (numSubs > maxSubs) {
// Cleanup any subscriptions we might have added to another stream before hitting
// the limit on subs for this stream.
removeStreamSubscription(sub);
LOG.warn("QUERY SUBSCRIPTION REJECTED: Number of subscriptions for stream {} exceeded max {}. " +
"Increase (default mre.publish.max.subscriptions.per.stream.default or " +
" mre.publish.max.subscriptions.stream.<streamName>) to allow more queries. Removed {}",
stream, maxSubs, sub);
getStreamMetrics(stream).ifPresent(m ->
m.getMantisQueryRejectedCounter().increment());
}
getStreamMetrics(stream).ifPresent(m ->
m.getMantisActiveQueryCountGauge().set((double) numSubs));
}
subscriptionIdToStreamsMap.put(sub.getSubscriptionId(), streams);
}
private void removeSubscriptionId(final List<String> streams, final String subscriptionId) {
for (String stream : streams) {
if (streamSubscriptionsMap.containsKey(stream)) {
final ConcurrentSkipListSet<Subscription> subs =
streamSubscriptionsMap.get(stream);
if (subs != null) {
subs.removeIf(sub -> sub.getSubscriptionId().equals(subscriptionId));
getStreamMetrics(stream).ifPresent(m ->
m.getMantisActiveQueryCountGauge().set((double) subs.size()));
if (subs.isEmpty()) {
streamSubscriptionsMap.remove(stream);
}
}
}
}
}
synchronized boolean removeStreamSubscription(final String subscriptionId) {
LOG.info("removing subscription {}", subscriptionId);
List<String> streams =
subscriptionIdToStreamsMap.getOrDefault(subscriptionId, Collections.emptyList());
removeSubscriptionId(streams, subscriptionId);
subscriptionIdToStreamsMap.remove(subscriptionId);
return true;
}
synchronized boolean removeStreamSubscription(final Subscription sub) {
LOG.info("removing subscription {}", sub);
final List<String> streams = sanitizeStreamSubjects(sub.getSubjects());
removeSubscriptionId(streams, sub.getSubscriptionId());
subscriptionIdToStreamsMap.remove(sub.getSubscriptionId());
return true;
}
/**
* List of the all the subscriptions for a stream name regardless of whether events are published to it or not
*
* @param streamName
*
* @return
*/
Set<Subscription> getStreamSubscriptions(final String streamName) {
return streamSubscriptionsMap.getOrDefault(streamName, new ConcurrentSkipListSet<>());
}
/**
* Returns a list of all stream names registered from MantisEventPublisher
*
* @return
*/
Set<String> getRegisteredStreams() {
return streamQueuesMap.keySet();
}
}
| 8,311 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/DefaultObjectMapper.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
public class DefaultObjectMapper {
private static final ObjectMapper mapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
public static final ObjectMapper getInstance() {
return mapper;
}
}
| 8,312 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/SubscriptionTracker.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
public interface SubscriptionTracker {
/**
* Refresh the current set of active subscriptions for this app's streams.
*/
void refreshSubscriptions();
}
| 8,313 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/EventProcessor.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.api.StreamType;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.core.Subscription;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class processes a {@link Event} for a specific stream. Semantics of event processing are defined by
* {@link EventProcessor#process(String, Event)}.
* <p>
* Default streams are defined in {@link StreamType}.
*/
class EventProcessor {
private static final Logger LOG = LoggerFactory.getLogger(EventProcessor.class);
private final MrePublishConfiguration config;
private final StreamManager streamManager;
private final Tee tee;
private final Random randomGenerator;
private final AtomicBoolean errorLogEnabled;
EventProcessor(MrePublishConfiguration config, StreamManager streamManager, Tee tee) {
this.config = config;
this.streamManager = streamManager;
this.tee = tee;
this.randomGenerator = new Random();
this.errorLogEnabled = new AtomicBoolean(true);
}
/**
* Processes an event for a stream.
* <p>
* Event Processing:
* <p>
* 1. Mask sensitive fields in the event as defined by {@link MrePublishConfiguration#blackListedKeysCSV()}.
* 2. Check in-memory cache of {@link Subscription}s to find subscriptions whose query match the event.
* 3. Build a *superset* of fields from *all* matching subscriptions into a single event.o
*
* @return a Mantis {@link Event}.
*/
public Event process(String stream, Event event) {
LOG.debug("Entering EventProcessor#onNext: {}", event);
boolean isEnabled = config.isMREClientEnabled();
if (!isEnabled) {
LOG.debug("Mantis Realtime Events Publisher is disabled."
+ "Set the property defined in your MrePublishConfiguration object to true to enable.");
return null;
}
// make a deep copy before proceeding to avoid altering the user provided map.
if (config.isDeepCopyEventMapEnabled()) {
event = new Event(event.getMap(), true);
}
maskSensitiveFields(event);
if (config.isTeeEnabled()) {
tee.tee(config.teeStreamName(), event);
}
List<Subscription> matchingSubscriptions = new ArrayList<>();
if (streamManager.hasSubscriptions(stream)) {
final Set<Subscription> streamSubscriptions = streamManager.getStreamSubscriptions(stream);
for (Subscription s : streamSubscriptions) {
try {
if (s.matches(event)) {
matchingSubscriptions.add(s);
}
} catch (Exception e) {
streamManager.getStreamMetrics(stream)
.ifPresent(m -> m.getMantisQueryFailedCounter().increment());
// Send errors only for a sample of events.
int rndNo = randomGenerator.nextInt(1_000_000);
if (rndNo < 10) {
sendError(s, e.getMessage());
}
}
}
}
Event projectedEvent = null;
if (!matchingSubscriptions.isEmpty()) {
projectedEvent = projectSupersetEvent(stream, matchingSubscriptions, event);
} else {
if (LOG.isTraceEnabled()) {
LOG.trace("no matching subscriptions");
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Exit EventProcessor#onNext: {}", event);
}
return projectedEvent;
}
/**
* Masks fields of an {@link Event} contained in a blacklist.
*/
void maskSensitiveFields(Event event) {
String blacklistKeys = config.blackListedKeysCSV();
List<String> blacklist =
Arrays.stream(blacklistKeys.split(","))
.map(String::trim)
.collect(Collectors.toList());
blacklist.stream()
.filter(key -> event.get(key) != null)
.forEach(key -> event.set(key, "***"));
}
private void sendError(Subscription subscription, String errorMessage) {
// TODO
// String clientId = subIdToClientIdMap.get(subscription.getSubscriptionId());
// final List<String> subscriptionIds = Collections.singletonList(subscription.getSubscriptionId());
//
// final Event errorEvent = new Event();
// errorEvent.set("msg", errorMessage);
// errorEvent.set("matched-clients", subscriptionIds.toString());
//
// PublishSubject<Event> subject = clientIdToClientSessionMap.get(clientId);
// if (subject != null) {
// subject.onNext(errorEvent);
// } else {
// if (LOG.isDebugEnabled()) {
// LOG.debug("no client session for client {}", clientId);
// }
// }
}
private Event projectSupersetEvent(final String streamName,
final List<Subscription> matchingSubscriptions,
final Event event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Enter EventProcessor#projectSupersetEvent {} event: {}", matchingSubscriptions, event);
}
Event projectedEvent = null;
try {
if (!matchingSubscriptions.isEmpty()) {
projectedEvent = matchingSubscriptions.get(0).projectSuperset(matchingSubscriptions, event);
}
} catch (Exception e) {
// Log only the first error so as to avoid flooding the log files.
if (errorLogEnabled.get()) {
String queries = matchingSubscriptions.stream()
.map(Subscription::getRawQuery)
.collect(Collectors.joining(", "));
LOG.error("Failed to project Event {} for queries: {}", event, queries);
errorLogEnabled.set(false);
}
streamManager.getStreamMetrics(streamName).ifPresent(m ->
m.getMantisQueryProjectionFailedCounter().increment());
}
Event augmentedEvent = null;
if (projectedEvent != null && !projectedEvent.isEmpty()) {
augmentedEvent = enrich(projectedEvent, streamName, matchingSubscriptions);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Projected event is empty. skipping");
}
}
return augmentedEvent;
}
private Event enrich(Event projectedEvent,
String streamName,
List<Subscription> matchingSubscriptions) {
projectedEvent.set("type", "EVENT");
projectedEvent.set("mantisStream", streamName);
List<String> subIdList = new ArrayList<>(matchingSubscriptions.size());
for (Subscription res : matchingSubscriptions) {
subIdList.add(res.getSubscriptionId());
}
projectedEvent.set("matched-clients", subIdList);
if (LOG.isDebugEnabled()) {
LOG.debug("Generated event string: {}", projectedEvent);
}
return projectedEvent;
}
}
| 8,314 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/Tee.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.publish.api.Event;
public interface Tee {
void tee(String streamName, Event event);
}
| 8,315 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/ConsoleEventChannel.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.publish.api.Event;
import java.io.PrintStream;
import java.util.concurrent.CompletableFuture;
/**
* An {@link EventChannel} that prints its output to stdout.
*/
public class ConsoleEventChannel implements EventChannel {
private final PrintStream printStream;
/**
* Creates a new instance.
*
* @param printStream the output stream of where to send events,
* for example, {@code System.out}.
*/
public ConsoleEventChannel(PrintStream printStream) {
this.printStream = printStream;
}
/**
* Writes the event to {@code stdout} on localhost.
*
* @param worker a {@link MantisWorker} representing localhost for this class.
* @param event the output to write to console.
*/
@Override
public CompletableFuture<Void> send(MantisWorker worker, Event event) {
printStream.println(event.toJsonString());
return CompletableFuture.completedFuture(null);
}
/**
* This {@link EventChannel} doesn't use a buffer, so default the size to 0 to represent 0% utilization.
*/
@Override
public double bufferSize(MantisWorker worker) {
return 0;
}
@Override
public void close(MantisWorker worker) {
// NOOP
}
}
| 8,316 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/NoOpTee.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.api.Event;
import javax.inject.Singleton;
@Singleton
public class NoOpTee implements Tee {
private final Registry registry;
private final Counter noOpTeeInvoked;
public NoOpTee(Registry registry) {
this.registry = registry;
this.noOpTeeInvoked = registry.counter("noOpTeeInvoked");
}
@Override
public void tee(String streamName, Event event) {
// increment a counter for operational visibility,
// as this usually indicates the Tee was enabled but a more concrete implementation
// was not bound to the Tee interface during the mantis publish client initialization
noOpTeeInvoked.increment();
}
} | 8,317 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/EventTransmitter.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.publish.api.Event;
public interface EventTransmitter {
/**
* Send an event to a stream.
*
* Implementations are free to determine how the events are routed to the stream.
*/
void send(Event event, String stream);
}
| 8,318 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/MantisEventPublisher.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.api.EventPublisher;
import io.mantisrx.publish.api.PublishStatus;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.metrics.StreamMetrics;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An {@link EventPublisher} that publishes events into Mantis.
*/
public class MantisEventPublisher implements EventPublisher {
private static final Logger LOG = LoggerFactory.getLogger(MantisEventPublisher.class);
private final MrePublishConfiguration mrePublishConfiguration;
private final StreamManager streamManager;
public MantisEventPublisher(MrePublishConfiguration mrePublishConfiguration,
StreamManager streamManager) {
this.mrePublishConfiguration = mrePublishConfiguration;
this.streamManager = streamManager;
}
@Override
public CompletionStage<PublishStatus> publish(final String streamName, final Event event) {
if (!isEnabled()) {
return CompletableFuture.completedFuture(PublishStatus.SKIPPED_CLIENT_NOT_ENABLED);
}
if (event == null || event.isEmpty()) {
return CompletableFuture.completedFuture(PublishStatus.SKIPPED_INVALID_EVENT);
}
final Optional<BlockingQueue<Event>> streamQ = streamManager.registerStream(streamName);
if (streamQ.isPresent()) {
final Optional<StreamMetrics> streamMetricsO = streamManager.getStreamMetrics(streamName);
if (hasSubscriptions(streamName) || isTeeEnabled()) {
boolean success = streamQ.get().offer(event);
if (!success) {
streamMetricsO.ifPresent(m -> m.getMantisEventsDroppedCounter().increment());
return CompletableFuture.completedFuture(PublishStatus.FAILED_QUEUE_FULL);
} else {
streamMetricsO.ifPresent(m -> m.getMantisEventsProcessedCounter().increment());
// TODO - propagate a Promise of PublishStatus with the Event and update status async after network send to Mantis
return CompletableFuture.completedFuture(PublishStatus.ENQUEUED);
}
} else {
// Don't enqueue the event if there are no active subscriptions for this stream.
streamMetricsO.ifPresent(m -> {
m.getMantisActiveQueryCountGauge().set(0.0);
m.getMantisEventsSkippedCounter().increment();
});
return CompletableFuture.completedFuture(PublishStatus.SKIPPED_NO_SUBSCRIPTIONS);
}
} else {
// failed to register stream, this could happen if max stream limit is exceeded
return CompletableFuture.completedFuture(PublishStatus.FAILED_STREAM_NOT_REGISTERED);
}
}
@Override
public boolean hasSubscriptions(final String streamName) {
if (!isEnabled()) {
LOG.debug("Mantis publish client is not enabled");
return false;
}
// register this stream for tracking subscriptions
streamManager.registerStream(streamName);
return streamManager.hasSubscriptions(streamName);
}
private boolean isEnabled() {
return mrePublishConfiguration.isMREClientEnabled();
}
private boolean isTeeEnabled() {
return mrePublishConfiguration.isTeeEnabled();
}
}
| 8,319 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/MrePublishClientInitializer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.api.EventPublisher;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Initializes the Mantis Realtime Events Publisher and its internal components.
* <p>
* Components:
* <p>
* 1. {@link MantisEventPublisher} is the user-facing object for publishing events into Mantis.
* 2. {@link SubscriptionTracker} maintains and updates a list of subscriptions.
* 3. {@link MantisJobDiscovery} maintains and updates a list of Mantis Jobs and their workers.
* <p>
* This class has several configuration options. See {@link MrePublishConfiguration} for more information on
* how to set configuration options and defaults.
*/
public class MrePublishClientInitializer {
private static final Logger LOG = LoggerFactory.getLogger(MrePublishClientInitializer.class);
private final MrePublishConfiguration config;
private final Registry registry;
private final StreamManager streamManager;
private final EventPublisher eventPublisher;
private final SubscriptionTracker subscriptionsTracker;
private final EventTransmitter eventTransmitter;
private final Tee tee;
private final List<ScheduledFuture<?>> scheduledFutures = new ArrayList<>();
private static final ScheduledThreadPoolExecutor DRAINER_EXECUTOR =
new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "MantisDrainer"));
private static final ScheduledThreadPoolExecutor SUBSCRIPTIONS_EXECUTOR =
new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "MantisSubscriptionsTracker"));
static {
DRAINER_EXECUTOR.setRemoveOnCancelPolicy(true);
SUBSCRIPTIONS_EXECUTOR.setRemoveOnCancelPolicy(true);
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
DRAINER_EXECUTOR.shutdown();
SUBSCRIPTIONS_EXECUTOR.shutdown();
}));
}
public MrePublishClientInitializer(
MrePublishConfiguration config,
Registry registry,
StreamManager streamManager,
EventPublisher eventPublisher,
SubscriptionTracker subscriptionsTracker,
EventTransmitter eventTransmitter,
Tee tee) {
this.config = config;
this.registry = registry;
this.streamManager = streamManager;
this.eventPublisher = eventPublisher;
this.subscriptionsTracker = subscriptionsTracker;
this.eventTransmitter = eventTransmitter;
this.tee = tee;
}
/**
* Starts internal components for the Mantis Realtime Events Publisher.
*/
public void start() {
this.scheduledFutures.add(setupSubscriptionTracker(subscriptionsTracker));
this.scheduledFutures.add(setupDrainer(streamManager, eventTransmitter, tee));
}
/**
* Safely shuts down internal components for the Mantis Realtime Events Publisher.
*/
public void stop() {
Iterator<ScheduledFuture<?>> iterator = scheduledFutures.iterator();
while (iterator.hasNext()) {
ScheduledFuture<?> next = iterator.next();
if (next != null && !next.isCancelled()) {
next.cancel(false);
}
}
scheduledFutures.clear();
}
public EventPublisher getEventPublisher() {
return eventPublisher;
}
private ScheduledFuture<?> setupDrainer(StreamManager streamManager, EventTransmitter transmitter, Tee tee) {
EventProcessor eventProcessor = new EventProcessor(config, streamManager, tee);
EventDrainer eventDrainer =
new EventDrainer(config, streamManager, registry, eventProcessor, transmitter, Clock.systemUTC());
return DRAINER_EXECUTOR.scheduleAtFixedRate(() -> {
try {
eventDrainer.run();
} catch (Throwable t) {
if (LOG.isDebugEnabled()) {
LOG.debug("event drainer caught exception", t);
}
}
}, 0, config.drainerIntervalMsec(), TimeUnit.MILLISECONDS);
}
private ScheduledFuture<?> setupSubscriptionTracker(SubscriptionTracker subscriptionsTracker) {
return SUBSCRIPTIONS_EXECUTOR.scheduleAtFixedRate(() -> {
try {
subscriptionsTracker.refreshSubscriptions();
} catch (Throwable t) {
if (LOG.isDebugEnabled()) {
LOG.debug("failed to refresh subscriptions", t);
}
}
}, 1, config.subscriptionRefreshIntervalSec(), TimeUnit.SECONDS);
}
}
| 8,320 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/EventChannel.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.publish.api.Event;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* A transport that lets users publish events into Mantis.
* <p>
* All I/O operations are asynchronous. This means calls to {@link EventChannel#send(MantisWorker, Event)} will
* return immediately without guarantee that the operation has completed. It is up to the caller to react to the
* resulting {@link Future<Void>}.
*/
public interface EventChannel {
/**
* Asynchronous API to send an event to a given destination.
*
* @param worker a {@link MantisWorker} which represents a destination for the event.
* @param event a {@link Event} which represents a set of key-value pairs with
* additional context.
*
* @return a {@link Future<Void>} which represents the action of sending an event.
* The caller is responsible for reacting to this future.
*/
CompletableFuture<Void> send(MantisWorker worker, Event event);
/**
* Returns the buffer size as a percentage utilization of the channel's internal transport.
* <p>
* An {@link EventChannel} may have many underlying connections which implement the same transport,
* each of which could have their own buffers.
*
* @param worker a {@link MantisWorker} which is used to query for the buffer size of a specific internal transport.
*/
double bufferSize(MantisWorker worker);
/**
* Asynchronous API to close the underlying channel for a given {@link MantisWorker}.
*
* @param worker a {@link MantisWorker} which is used to query for the buffer size of a specific internal transport.
*/
void close(MantisWorker worker);
}
| 8,321 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/EventDrainer.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
class EventDrainer implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(EventDrainer.class);
public static final String LOGGING_CONTEXT_KEY = "mantisLogCtx";
static final String DEFAULT_THREAD_NAME = "mantisDrainer";
public static final String LOGGING_CONTEXT_VALUE = DEFAULT_THREAD_NAME;
private final MrePublishConfiguration config;
private final Timer mantisEventDrainTimer;
private final StreamManager streamManager;
private final EventProcessor eventProcessor;
private final EventTransmitter eventTransmitter;
private final Clock clock;
EventDrainer(MrePublishConfiguration config,
StreamManager streamManager,
Registry registry,
EventProcessor eventProcessor,
EventTransmitter eventTransmitter,
Clock clock) {
this.config = config;
this.mantisEventDrainTimer =
SpectatorUtils.buildAndRegisterTimer(registry, "mrePublishEventDrainTime");
this.streamManager = streamManager;
this.eventProcessor = eventProcessor;
this.eventTransmitter = eventTransmitter;
this.clock = clock;
if (LOG.isDebugEnabled()) {
LOG.debug("Starting drainer thread.");
}
}
@Override
public void run() {
try {
MDC.put(LOGGING_CONTEXT_KEY, LOGGING_CONTEXT_VALUE);
final long startTime = clock.millis();
Set<String> streams = streamManager.getRegisteredStreams();
for (String stream : streams) {
final List<Event> streamEventList = new ArrayList<>();
int queueDepth = 0;
try {
final Optional<BlockingQueue<Event>> streamQueueO = streamManager.getQueueForStream(stream);
if (streamQueueO.isPresent()) {
BlockingQueue<Event> streamEventQ = streamQueueO.get();
streamEventQ.drainTo(streamEventList);
queueDepth = streamEventList.size();
if (LOG.isTraceEnabled()) {
LOG.trace("Queue drained size: {} for stream {}", queueDepth, stream);
}
final int finalQueueDepth = queueDepth;
streamManager.getStreamMetrics(stream)
.ifPresent(m -> {
m.getMantisEventsQueuedGauge().set((double) finalQueueDepth);
if (finalQueueDepth > 0) {
m.updateLastEventOnStreamTimestamp();
}
});
streamEventList.stream()
.map(e -> process(stream, e))
.filter(Objects::nonNull)
.forEach(e -> eventTransmitter.send(e, stream));
streamEventList.clear();
}
} catch (Exception e) {
LOG.warn("Exception processing events for stream {}", stream, e);
final int finalQueueDepth = queueDepth;
streamManager.getStreamMetrics(stream)
.ifPresent(m -> {
m.getMantisEventsDroppedProcessingExceptionCounter().increment(finalQueueDepth);
});
}
}
final long processingTime = clock.millis() - startTime;
mantisEventDrainTimer.record(processingTime, TimeUnit.MILLISECONDS);
} finally {
MDC.remove(LOGGING_CONTEXT_KEY);
}
}
private Event process(String stream, Event event) {
final long startTime = clock.millis();
Event processedEvent = eventProcessor.process(stream, event);
final long processingTime = clock.millis() - startTime;
streamManager.getStreamMetrics(stream)
.ifPresent(m -> m.getMantisEventsProcessTimeTimer().record(processingTime, TimeUnit.MILLISECONDS));
return processedEvent;
}
}
| 8,322 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/DefaultSubscriptionTracker.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.ipc.http.HttpClient;
import com.netflix.spectator.ipc.http.HttpResponse;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.discovery.proto.StageWorkers;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import io.mantisrx.publish.proto.MantisServerSubscriptionEnvelope;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultSubscriptionTracker extends AbstractSubscriptionTracker {
private static final Logger LOG = LoggerFactory.getLogger(DefaultSubscriptionTracker.class);
private static final String SUBSCRIPTIONS_URL_FORMAT = "http://%s:%d?jobId=%s";
private final MrePublishConfiguration mrePublishConfiguration;
private final String subscriptionsFetchQueryParamString;
private final Counter fetchSubscriptionsFailedCount;
private final Counter fetchSubscriptionsNon200Count;
private final HttpClient httpClient;
private final MantisJobDiscovery jobDiscovery;
private final Random random = new Random();
public DefaultSubscriptionTracker(
MrePublishConfiguration mrePublishConfiguration,
Registry registry,
MantisJobDiscovery jobDiscovery,
StreamManager streamManager,
HttpClient httpClient) {
super(mrePublishConfiguration, registry, jobDiscovery, streamManager);
this.mrePublishConfiguration = mrePublishConfiguration;
this.jobDiscovery = jobDiscovery;
this.subscriptionsFetchQueryParamString = mrePublishConfiguration.subscriptionFetchQueryParams();
this.httpClient = httpClient;
this.fetchSubscriptionsFailedCount = SpectatorUtils.buildAndRegisterCounter(registry, "fetchSubscriptionsFailedCount");
this.fetchSubscriptionsNon200Count = SpectatorUtils.buildAndRegisterCounter(registry, "fetchSubscriptionsNon200Count");
}
private Optional<MantisServerSubscriptionEnvelope> fetchSubscriptions(String jobId, MantisWorker worker) {
try {
String uri;
if (!subscriptionsFetchQueryParamString.isEmpty()) {
uri = String.format(SUBSCRIPTIONS_URL_FORMAT, worker.getHost(), worker.getPort(), jobId + "&" + subscriptionsFetchQueryParamString);
} else {
uri = String.format(SUBSCRIPTIONS_URL_FORMAT, worker.getHost(), worker.getPort(), jobId);
}
LOG.trace("Subscription fetch URL: {}", uri);
HttpResponse response = httpClient
.get(URI.create(uri))
.withConnectTimeout(1000)
.withReadTimeout(1000)
.send();
if (response.status() == 200) {
MantisServerSubscriptionEnvelope subscriptionEnvelope =
DefaultObjectMapper.getInstance().readValue(response.entityAsString(), MantisServerSubscriptionEnvelope.class);
LOG.debug("got subs {} from Mantis worker {}", subscriptionEnvelope, worker);
return Optional.ofNullable(subscriptionEnvelope);
} else {
LOG.info("got {} {} response from Mantis worker {}", response.status(), response.entityAsString(), worker);
fetchSubscriptionsNon200Count.increment();
return Optional.empty();
}
} catch (Exception e) {
LOG.info("caught exception fetching subs from {}", worker, e);
fetchSubscriptionsFailedCount.increment();
return Optional.empty();
}
}
private List<MantisWorker> randomSubset(List<MantisWorker> workers, int subsetSize) {
int size = workers.size();
if (subsetSize < 0 || subsetSize >= size) {
return workers;
}
for (int idx = 0; idx < subsetSize; idx++) {
int randomWorkerIdx = random.nextInt(size);
MantisWorker tmp = workers.get(idx);
workers.set(idx, workers.get(randomWorkerIdx));
workers.set(randomWorkerIdx, tmp);
}
return workers.subList(0, subsetSize);
}
private Optional<MantisServerSubscriptionEnvelope> subsetSubscriptionsResolver(String jobId, List<MantisWorker> workers) {
Map<MantisServerSubscriptionEnvelope, Integer> subCount = new HashMap<>();
int numWorkers = workers.size();
int maxWorkersToFetchSubsFrom = Math.min(mrePublishConfiguration.maxNumWorkersToFetchSubscriptionsFrom(), numWorkers);
int threshold = maxWorkersToFetchSubsFrom / 2;
List<MantisWorker> subset = randomSubset(workers, maxWorkersToFetchSubsFrom);
for (final MantisWorker mantisWorker : subset) {
Optional<MantisServerSubscriptionEnvelope> subscriptionsO = fetchSubscriptions(jobId, mantisWorker);
if (subscriptionsO.isPresent()) {
Integer prevCount;
MantisServerSubscriptionEnvelope subscriptions = subscriptionsO.get();
if ((prevCount = subCount.putIfAbsent(subscriptions, 0)) != null) {
subCount.put(subscriptions, prevCount + 1);
if (prevCount >= threshold) {
return Optional.ofNullable(subscriptions);
}
}
}
}
return subCount.entrySet().stream().max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey);
}
@Override
public Optional<MantisServerSubscriptionEnvelope> fetchSubscriptions(String jobCluster) {
Optional<JobDiscoveryInfo> jobDiscoveryInfo = jobDiscovery.getCurrentJobWorkers(jobCluster);
if (jobDiscoveryInfo.isPresent()) {
JobDiscoveryInfo jdi = jobDiscoveryInfo.get();
StageWorkers workers = jdi.getIngestStageWorkers();
if (workers != null) {
return subsetSubscriptionsResolver(jdi.getJobId(), workers.getWorkers());
} else {
LOG.info("Subscription refresh failed, workers null for {}", jobCluster);
}
} else {
LOG.info("Subscription refresh failed, job discovery info not found for {}", jobCluster);
}
return Optional.empty();
}
}
| 8,323 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/core/SubscriptionFactory.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.core;
import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;
import io.mantisrx.publish.MantisEventPublisher;
import io.mantisrx.publish.internal.mql.MQLSubscription;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A factory that creates a subscription type based on {@link MQLSubscription ).
*/
public class SubscriptionFactory {
private static final Logger LOG = LoggerFactory.getLogger(SubscriptionFactory.class);
/**
* Selects the correct implementation of {@link Subscription}.
*
* @param id A string representing the query ids, usually {@code clientId_subscriptionId}.
* @param criterion The query string
*
* @return An Optional instance implementing {@link Subscription} for use with the {@link MantisEventPublisher}, empty Optional if the criterion is invalid.
*/
public static Optional<Subscription> getSubscription(String id, String criterion) {
try {
MQLSubscription mqlSubscription = new MQLSubscription(id, criterion);
return ofNullable(mqlSubscription);
} catch (Throwable t) {
LOG.info("Failed to get Subscription object for {} {}", id, criterion, t);
return empty();
}
}
}
| 8,324 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/core/Subscription.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.core;
import io.mantisrx.mql.jvm.core.Query;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.internal.mql.MQLSubscription;
import java.util.List;
public interface Subscription {
/**
* See {@link MQLSubscription#matches(Event)}.
*/
boolean matches(Event event) throws Exception;
/**
* See {@link MQLSubscription#projectSuperset(List, Event)}.
*/
Event projectSuperset(List<Subscription> subscriptions, Event event);
/**
* See {@link MQLSubscription#getQuery()}.
*/
Query getQuery();
/**
* See {@link MQLSubscription#getSubscriptionId()}.
*/
String getSubscriptionId();
/**
* See {@link MQLSubscription#getRawQuery()}.
*/
String getRawQuery();
/**
* See {@link MQLSubscription#getSubjects()}.
*/
List<String> getSubjects();
}
| 8,325 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/proto/InstanceInfo.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.proto;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InstanceInfo {
private static final Logger LOG = LoggerFactory.getLogger(InstanceInfo.class);
private final String applicationName;
private final String zone;
private final String clusterName;
private final String autoScalingGroupName;
private volatile InstanceStatus instanceStatus = InstanceStatus.UNKNOWN;
public InstanceInfo(String applicationName, String zone, String clusterName, String autoScalingGroupName) {
this.applicationName = applicationName;
this.zone = zone;
this.clusterName = clusterName;
this.autoScalingGroupName = autoScalingGroupName;
}
public String getApplicationName() {
return applicationName;
}
public String getZone() {
return zone;
}
public String getClusterName() {
return clusterName;
}
public String getAutoScalingGroupName() {
return autoScalingGroupName;
}
public InstanceStatus getInstanceStatus() {
return this.instanceStatus;
}
public void setInstanceStatus(InstanceStatus status) {
this.instanceStatus = status;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InstanceInfo that = (InstanceInfo) o;
return Objects.equals(getApplicationName(), that.getApplicationName()) &&
Objects.equals(getZone(), that.getZone()) &&
Objects.equals(getClusterName(), that.getClusterName()) &&
Objects.equals(getAutoScalingGroupName(), that.getAutoScalingGroupName());
}
@Override
public int hashCode() {
return Objects.hash(getApplicationName(), getZone(), getClusterName(), getAutoScalingGroupName());
}
@Override
public String toString() {
return "InstanceInfo{" +
"applicationName='" + applicationName + '\'' +
", zone='" + zone + '\'' +
", clusterName='" + clusterName + '\'' +
", autoScalingGroupName='" + autoScalingGroupName + '\'' +
", instanceStatus=" + instanceStatus +
'}';
}
public enum InstanceStatus {
UP, // Ready to receive traffic
DOWN, // Do not send traffic- healthcheck callback failed
STARTING, // Just about starting- initializations to be done - do not
// send traffic
OUT_OF_SERVICE, // Intentionally shutdown for traffic
UNKNOWN;
public static InstanceStatus toEnum(String s) {
if (s != null) {
try {
return InstanceStatus.valueOf(s.toUpperCase());
} catch (IllegalArgumentException e) {
// ignore and fall through to unknown
LOG.debug("illegal argument supplied to InstanceStatus.valueOf: {}, defaulting to {}", s, UNKNOWN);
}
}
return UNKNOWN;
}
}
}
| 8,326 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/proto/MantisServerSubscription.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.proto;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MantisServerSubscription {
private final String query;
private final String subscriptionId;
private final Map<String, String> additionalParams;
public MantisServerSubscription(String subId, String query) {
this(subId, query, new HashMap<>());
}
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public MantisServerSubscription(@JsonProperty("subscriptionId") String subId,
@JsonProperty("query") String query,
@JsonProperty("additionalParams") Map<String, String> additionalParams) {
this.query = query;
this.additionalParams = additionalParams;
this.subscriptionId = subId;
}
public String getQuery() {
return query;
}
public Map<String, String> getAdditionalParams() {
return additionalParams;
}
public String getSubscriptionId() {
return subscriptionId;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MantisServerSubscription that = (MantisServerSubscription) o;
return Objects.equals(query, that.query) &&
Objects.equals(subscriptionId, that.subscriptionId) &&
Objects.equals(additionalParams, that.additionalParams);
}
@Override
public int hashCode() {
return Objects.hash(query, subscriptionId, additionalParams);
}
@Override
public String toString() {
return "MantisServerSubscription{"
+ " query='" + query + '\''
+ ", subscriptionId='" + subscriptionId + '\''
+ ", additionalParams=" + additionalParams
+ '}';
}
}
| 8,327 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/proto/MantisServerSubscriptionEnvelope.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.proto;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public class MantisServerSubscriptionEnvelope {
private final List<MantisServerSubscription> subscriptionList;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public MantisServerSubscriptionEnvelope(@JsonProperty("subscriptionList") List<MantisServerSubscription> subList) {
this.subscriptionList = subList;
}
public List<MantisServerSubscription> getSubscriptionList() {
return subscriptionList;
}
public Set<MantisServerSubscription> getSubscriptions() {
return new HashSet<>(subscriptionList);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MantisServerSubscriptionEnvelope that = (MantisServerSubscriptionEnvelope) o;
return Objects.equals(getSubscriptionList(), that.getSubscriptionList());
}
@Override
public int hashCode() {
return Objects.hash(getSubscriptionList());
}
@Override
public String toString() {
return "MantisServerSubscriptionEnvelope{"
+ " subscriptionList=" + subscriptionList
+ '}';
}
}
| 8,328 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/config/MrePublishConfiguration.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.config;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import java.util.Map;
public interface MrePublishConfiguration {
/**
* Determine if event processing is enabled.
* <p>
* Property: <code>mantis.publish.enabled</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MRE_CLIENT_ENABLED_PROP
*/
boolean isMREClientEnabled();
/**
* Allows events to simultaneously be sent to an external system outside of Mantis.
* <p>
* Property: <code>mantis.publish.tee.enabled</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MRE_CLIENT_TEE_ENABLED_PROP
*/
boolean isTeeEnabled();
/**
* Specifies which external stream name tee will write to.
* <p>
* Property: <code>mantis.publish.tee.stream</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MRE_CLIENT_TEE_STREAM_NAME_PROP
*/
String teeStreamName();
/**
* Specifies the deployed name of the app or microservice running this client
* <p>
* Property: <code>mantis.publish.app.name</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MRE_CLIENT_APP_NAME_PROP
*/
String appName();
/**
* Comma separated list of field names where the value will be obfuscated.
* <p>
* Property: <code>mantis.publish.blacklist</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MRE_CLIENT_BLACKLIST_KEYS_PROP
*/
String blackListedKeysCSV();
/**
* Maximum number of streams this application can create.
* <p>
* Property: <code>mantis.publish.max.num.streams</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MAX_NUM_STREAMS_NAME
*/
int maxNumStreams();
/**
* Maximum duration in seconds for the stream to be considered inactive if there are no events.
* <p>
* Property: <code>mantis.publish.stream.inactive.duration.threshold.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#STREAM_INACTIVE_DURATION_THRESHOLD_NAME
*/
long streamInactiveDurationThreshold();
/**
* Default maximum number of subscriptions per stream. After the limit is reached, further subscriptions on that
* stream are rejected.
* <p>
* Property: <code>mantis.publish.max.subscriptions.per.stream.default</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MAX_SUBSCRIPTIONS_COUNT_PROP
*/
int maxSubscriptionCount();
/**
* Size of the blocking queue to hold events to be pushed for the specific stream.
* <p>
* Property: <code>mantis.publish.{stream_name}.stream.queue.size</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#PER_STREAM_QUEUE_SIZE_FORMAT
*/
int streamQueueSize(String streamName);
/**
* Overrides the default maximum number of subscriptions for the specific stream.
* <p>
* Property: <code>mantis.publish.max.subscriptions.stream.{stream_name}</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MAX_SUBS_PER_STREAM_FORMAT
* @see #maxSubscriptionCount()
*/
int maxSubscriptions(String streamName);
/**
* List of Mantis Job clusters per stream configured to receive data for this app
*
* @return streamName to Job cluster mapping
*
* @deprecated Use {@link MantisJobDiscovery#getStreamNameToJobClusterMapping(String)} instead.
*/
@Deprecated
Map<String, String> streamNameToJobClusterMapping();
/**
* @deprecated Use {@link MantisJobDiscovery#getJobCluster(String, String)} instead.
*/
@Deprecated
String mantisJobCluster(String streamName);
/**
* Interval in milliseconds when events are drained from the stream queue and delegated to underlying transmitter
* for sending.
* <p>
* Property: <code>mantis.publish.drainer.interval.msec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#DRAINER_INTERVAL_MSEC_PROP
*/
int drainerIntervalMsec();
/**
* Interval in seconds when subscriptions are fetched. In the default implementation, subscriptions are fetched
* over http from the workers returned by Discovery API.
* <p>
* Property: <code>mantis.publish.subs.refresh.interval.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#SUBS_REFRESH_INTERVAL_SEC_PROP
*/
int subscriptionRefreshIntervalSec();
/**
* Duration in seconds between a subscription is last fetched and when it is removed.
* <p>
* Property: <code>mantis.publish.subs.expiry.interval.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#SUBS_EXPIRY_INTERVAL_SEC_PROP
*/
int subscriptionExpiryIntervalSec();
/**
* Duration in seconds between workers are refreshed for a job cluster.
* <p>
* Property: <code>mantis.publish.jobdiscovery.refresh.interval.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP
*/
int jobDiscoveryRefreshIntervalSec();
/**
* Duration in seconds between job cluster mapping is refreshed for the current application.
* <p>
* Property: <code>mantis.publish.jobcluster.mapping.refresh.interval.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#JOB_CLUSTER_MAPPING_REFRESH_INTERVAL_SEC_PROP
*/
int jobClusterMappingRefreshIntervalSec();
/**
* Determine if event processing should operate on a deep copy of the event. Otherwise the event object is processed directly.
* <p>
* Property: <code>mantis.publish.deepcopy.eventmap.enabled</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#DEEPCOPY_EVENT_MAP_ENABLED_PROP
*/
boolean isDeepCopyEventMapEnabled();
/**
* Discovery API hostname to
* - retrieve Job Cluster configured to receive events from this MRE publish client
* - retrieve Mantis Workers for a Job Cluster
* <p>
* Property: <code>mantis.publish.discovery.api.hostname</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#DISCOVERY_API_HOSTNAME_PROP
*/
String discoveryApiHostname();
/**
* Discovery API port to
* - retrieve Job Cluster configured to receive events from this MRE publish client
* - retrieve Mantis Workers for a Job Cluster
* <p>
* Property: <code>mantis.publish.discovery.api.port</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#DISCOVERY_API_PORT_PROP
*/
int discoveryApiPort();
/**
* Maximum number of mantis workers to fetch subscription from. Workers are randomly chosen from the list returned
* by Discovery API.
* <p>
* Property: <code>mantis.publish.subs.refresh.max.num.workers</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#MAX_NUM_WORKERS_FOR_SUB_REFRESH
*/
default int maxNumWorkersToFetchSubscriptionsFrom() {
return 3;
}
/**
* Additional query params to pass to the api call to fetch subscription. It should be of the form "param1=value1¶m2=value2".
* <p>
* Property: <code>mantis.publish.subs.fetch.query.params.string</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#SUBS_FETCH_QUERY_PARAMS_STR_PROP
*/
default String subscriptionFetchQueryParams() {
return "";
}
/**
* Netty channel configuration for pushing events. Determine if events should be gzip encoded when send over the channel.
* <p>
* Property: <code>mantis.publish.channel.gzip.enabled</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_GZIP_ENABLED_PROP
*/
boolean getGzipEnabled();
/**
* Netty channel configuration for pushing events. Write idle timeout in seconds for the channel.
* <p>
* Property: <code>mantis.publish.channel.idleTimeout.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_IDLE_TIMEOUT_SEC_PROP
*/
int getIdleTimeoutSeconds();
/**
* Netty channel configuration for pushing events. Chunked size in bytes of the channel content. It is used by
* HttpObjectAggregator.
* <p>
* Property: <code>mantis.publish.channel.httpChunkSize.bytes</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_HTTP_CHUNK_SIZE_BYTES_PROP
* @see io.netty.handler.codec.http.HttpObjectAggregator
*/
int getHttpChunkSize();
/**
* Netty channel configuration for pushing events. Write timeout in seconds for the channel.
* <p>
* Property: <code>mantis.publish.channel.writeTimeout.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_WRITE_TIMEOUT_SEC_PROP
*/
int getWriteTimeoutSeconds();
/**
* Netty channel configuration for pushing events. Maximum duration in milliseconds between content flushes.
* <p>
* Property: <code>mantis.publish.channel.flushInterval.msec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_FLUSH_INTERVAL_MSEC
*/
long getFlushIntervalMs();
/**
* Netty channel configuration for pushing events. Content is flushed when aggregated event size is above this threshold.
* <p>
* Property: <code>mantis.publish.channel.flushInterval.bytes</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_FLUSH_INTERVAL_BYTES
*/
int getFlushIntervalBytes();
/**
* Netty channel configuration for pushing events. Used for setting write buffer watermark.
* <p>
* Property: <code>mantis.publish.channel.lowWriteBufferWatermark.bytes</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_LOW_WRITE_BUFFER_WATERMARK_BYTES
* @see io.netty.channel.WriteBufferWaterMark
*/
int getLowWriteBufferWatermark();
/**
* Netty channel configuration for pushing events. Used for setting write buffer watermark.
* <p>
* Property: <code>mantis.publish.channel.lowWriteBufferWatermark.bytes</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_LOW_WRITE_BUFFER_WATERMARK_BYTES
* @see io.netty.channel.WriteBufferWaterMark
*/
int getHighWriteBufferWatermark();
/**
* Netty channel configuration for pushing events. Number of threads in the eventLoopGroup.
* <p>
* Property: <code>mantis.publish.channel.ioThreads</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_IO_THREADS
*/
int getIoThreads();
/**
* Netty channel configuration for pushing events. Number of threads in the encoderEventLoopGroup when gzip is
* enabled.
* <p>
* Property: <code>mantis.publish.channel.compressionThreads</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#CHANNEL_COMPRESSION_THREADS
*/
int getCompressionThreads();
/**
* Size of the pool of Mantis workers to push events to.
* <p>
* Property: <code>mantis.publish.workerpool.capacity</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#WORKER_POOL_CAPACITY_PROP
*/
int getWorkerPoolCapacity();
/**
* Duration in seconds between Mantis workers are refreshed in the pool.
* <p>
* Property: <code>mantis.publish.workerpool.refresh.internal.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#WORKER_POOL_REFRESH_INTERVAL_SEC_PROP
*/
int getWorkerPoolRefreshIntervalSec();
/**
* Number of errors to receive from a Mantis worker before it is blacklisted in the pool.
* <p>
* Property: <code>mantis.publish.workerpool.worker.error.quota</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#WORKER_POOL_WORKER_ERROR_QUOTA_PROP
*/
int getWorkerPoolWorkerErrorQuota();
/**
* Duration in seconds after which a blacklisted Mantis worker may be reconsidered for selection.
* <p>
* Property: <code>mantis.publish.workerpool.worker.error.timeout.sec</code>
* <p>
* @see SampleArchaiusMrePublishConfiguration#WORKER_POOL_WORKER_ERROR_TIMEOUT_SEC
*/
int getWorkerPoolWorkerErrorTimeoutSec();
}
| 8,329 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/config/SampleArchaiusMrePublishConfiguration.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.config;
import com.netflix.archaius.api.Property;
import com.netflix.archaius.api.PropertyRepository;
import io.mantisrx.publish.api.StreamType;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SampleArchaiusMrePublishConfiguration implements MrePublishConfiguration {
public static final String PROP_PREFIX = "mantis.publish";
public static final String PUBLISH_JOB_CLUSTER_PROP_PREFIX = PROP_PREFIX + ".jobcluster.";
public static final String DEEPCOPY_EVENT_MAP_ENABLED_PROP = PROP_PREFIX + ".deepcopy.eventmap.enabled";
public static final String MRE_CLIENT_ENABLED_PROP = PROP_PREFIX + ".enabled";
public static final String MRE_CLIENT_APP_NAME_PROP = PROP_PREFIX + ".app.name";
public static final String MRE_CLIENT_TEE_ENABLED_PROP = PROP_PREFIX + ".tee.enabled";
public static final String MRE_CLIENT_TEE_STREAM_NAME_PROP = PROP_PREFIX + ".tee.stream";
public static final String MRE_CLIENT_BLACKLIST_KEYS_PROP = PROP_PREFIX + ".blacklist";
public static final String MAX_SUBSCRIPTIONS_COUNT_PROP = PROP_PREFIX + ".max.subscriptions.per.stream.default";
public static final String DRAINER_INTERVAL_MSEC_PROP = PROP_PREFIX + ".drainer.interval.msec";
public static final String JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP = PROP_PREFIX + ".jobdiscovery.refresh.interval.sec";
public static final String JOB_CLUSTER_MAPPING_REFRESH_INTERVAL_SEC_PROP = PROP_PREFIX + ".jobcluster.mapping.refresh.interval.sec";
public static final String SUBS_REFRESH_INTERVAL_SEC_PROP = PROP_PREFIX + ".subs.refresh.interval.sec";
public static final String SUBS_EXPIRY_INTERVAL_SEC_PROP = PROP_PREFIX + ".subs.expiry.interval.sec";
public static final String SUBS_FETCH_QUERY_PARAMS_STR_PROP = PROP_PREFIX + ".subs.fetch.query.params.string";
public static final String DISCOVERY_API_HOSTNAME_PROP = PROP_PREFIX + ".discovery.api.hostname";
public static final String DISCOVERY_API_PORT_PROP = PROP_PREFIX + ".discovery.api.port";
public static final String MAX_NUM_WORKERS_FOR_SUB_REFRESH = PROP_PREFIX + ".subs.refresh.max.num.workers";
public static final String MAX_SUBS_PER_STREAM_FORMAT = PROP_PREFIX + ".max.subscriptions.stream.%s";
public static final String PER_STREAM_QUEUE_SIZE_FORMAT = PROP_PREFIX + ".%s.stream.queue.size";
public static final String MAX_NUM_STREAMS_NAME = PROP_PREFIX + ".max.num.streams";
public static final String STREAM_INACTIVE_DURATION_THRESHOLD_NAME = PROP_PREFIX + ".stream.inactive.duration.threshold.sec";
// Worker Pool properties.
public static final String WORKER_POOL_PROP_PREFIX = PROP_PREFIX + ".workerpool.";
public static final String WORKER_POOL_CAPACITY_PROP = WORKER_POOL_PROP_PREFIX + "capacity";
public static final String WORKER_POOL_REFRESH_INTERVAL_SEC_PROP = WORKER_POOL_PROP_PREFIX + "refresh.interval.sec";
public static final String WORKER_POOL_WORKER_ERROR_QUOTA_PROP = WORKER_POOL_PROP_PREFIX + "worker.error.quota";
public static final String WORKER_POOL_WORKER_ERROR_TIMEOUT_SEC = WORKER_POOL_PROP_PREFIX + "worker.error.timeout.sec";
// Event Channel properties.
public static final String CHANNEL_PROP_PREFIX = PROP_PREFIX + ".channel.";
public static final String CHANNEL_GZIP_ENABLED_PROP = CHANNEL_PROP_PREFIX + "gzip.enabled";
public static final String CHANNEL_IDLE_TIMEOUT_SEC_PROP = CHANNEL_PROP_PREFIX + "idleTimeout.sec";
public static final String CHANNEL_HTTP_CHUNK_SIZE_BYTES_PROP = CHANNEL_PROP_PREFIX + "httpChunkSize.bytes";
public static final String CHANNEL_WRITE_TIMEOUT_SEC_PROP = CHANNEL_PROP_PREFIX + "writeTimeout.sec";
public static final String CHANNEL_FLUSH_INTERVAL_MSEC = CHANNEL_PROP_PREFIX + "flushInterval.msec";
public static final String CHANNEL_FLUSH_INTERVAL_BYTES = CHANNEL_PROP_PREFIX + "flushInterval.bytes";
public static final String CHANNEL_LOW_WRITE_BUFFER_WATERMARK_BYTES = CHANNEL_PROP_PREFIX + "lowWriteBufferWatermark.bytes";
public static final String CHANNEL_HIGH_WRITE_BUFFER_WATERMARK_BYTES = CHANNEL_PROP_PREFIX + "highWriteBufferWatermark.bytes";
public static final String CHANNEL_IO_THREADS = CHANNEL_PROP_PREFIX + "ioThreads";
public static final String CHANNEL_COMPRESSION_THREADS = CHANNEL_PROP_PREFIX + "compressionThreads";
private final PropertyRepository propRepo;
private final Property<Boolean> gzipEnabled;
private final Property<Integer> idleTimeoutSeconds;
private final Property<Integer> httpChunkSize;
private final Property<Integer> writeTimeoutSeconds;
private final Property<Long> flushIntervalMs;
private final Property<Integer> flushIntervalBytes;
private final Property<Integer> lowWriteBufferWatermark;
private final Property<Integer> highWriteBufferWatermark;
private final Property<Integer> ioThreads;
private final Property<Integer> compressionThreads;
private final Property<Boolean> deepCopyEventMapEnabled;
private final Property<Boolean> mreClientEnabled;
private final Property<String> appName;
private final Property<Boolean> mreClientTeeEnabled;
private final Property<String> mreClientTeeStreamName;
private final Property<String> blacklistedKeys;
private final Property<Integer> maxNumWorkersForSubsRefresh;
private final Property<Integer> maxNumStreams;
private final Property<Long> streamInactiveDurationThreshold;
private final Property<Integer> maxSubscriptionCount;
private final Map<String, Property<Integer>> maxSubsByStreamType = new HashMap<>();
private final Map<String, Property<Integer>> queueSizeByStreamType = new HashMap<>();
private final Map<String, Property<String>> jobClusterByStreamType = new HashMap<>();
private final Property<String> subsFetchQueryParamStr;
private final Property<String> discoveryApiHostnameProp;
private final Property<Integer> discoveryApiPortProp;
private final Property<Integer> drainerIntervalMSecProp;
private final Property<Integer> jobDiscoveryRefreshIntervalSecProp;
private final Property<Integer> jobClusterMappingRefreshIntervalSecProp;
private final Property<Integer> subscriptionRefreshIntervalSecProp;
private final Property<Integer> subscriptionExpiryIntervalSecProp;
private final Property<Integer> workerPoolRefreshIntervalSec;
private final Property<Integer> workerPoolCapacity;
private final Property<Integer> workerPoolWorkerErrorQuota;
private final Property<Integer> workerPoolWorkerErrorTimeoutSec;
private static final Logger LOG = LoggerFactory.getLogger(SampleArchaiusMrePublishConfiguration.class);
public SampleArchaiusMrePublishConfiguration(final PropertyRepository propertyRepository) {
this.propRepo = propertyRepository;
this.mreClientEnabled =
propertyRepository.get(MRE_CLIENT_ENABLED_PROP, Boolean.class)
.orElse(true);
this.appName =
propertyRepository.get(MRE_CLIENT_APP_NAME_PROP, String.class)
.orElse("unknownApp");
this.mreClientTeeEnabled =
propertyRepository.get(MRE_CLIENT_TEE_ENABLED_PROP, Boolean.class)
.orElse(false);
this.mreClientTeeStreamName =
propertyRepository.get(MRE_CLIENT_TEE_STREAM_NAME_PROP, String.class)
.orElse("default_stream");
this.blacklistedKeys =
propertyRepository.get(MRE_CLIENT_BLACKLIST_KEYS_PROP, String.class)
.orElse("param.password");
this.maxNumWorkersForSubsRefresh =
propertyRepository.get(MAX_NUM_WORKERS_FOR_SUB_REFRESH, Integer.class)
.orElse(3);
this.maxNumStreams =
propertyRepository.get(MAX_NUM_STREAMS_NAME, Integer.class)
.orElse(5);
this.streamInactiveDurationThreshold =
propertyRepository.get(STREAM_INACTIVE_DURATION_THRESHOLD_NAME, Long.class)
.orElse(24L * 60L * 60L);
this.maxSubscriptionCount =
propertyRepository.get(MAX_SUBSCRIPTIONS_COUNT_PROP, Integer.class)
.orElse(20);
this.deepCopyEventMapEnabled =
propertyRepository.get(DEEPCOPY_EVENT_MAP_ENABLED_PROP, Boolean.class)
.orElse(true);
jobClusterByStreamType.put(StreamType.DEFAULT_EVENT_STREAM, propRepo.get(PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.DEFAULT_EVENT_STREAM, String.class)
.orElse("SharedMrePublishEventSource"));
jobClusterByStreamType.put(StreamType.LOG_EVENT_STREAM, propRepo.get(PUBLISH_JOB_CLUSTER_PROP_PREFIX + StreamType.LOG_EVENT_STREAM, String.class)
.orElse("SharedPushLogEventSource"));
this.drainerIntervalMSecProp = propRepo.get(DRAINER_INTERVAL_MSEC_PROP, Integer.class)
.orElse(100);
this.jobDiscoveryRefreshIntervalSecProp = propRepo.get(JOB_DISCOVERY_REFRESH_INTERVAL_SEC_PROP, Integer.class)
.orElse(10);
this.jobClusterMappingRefreshIntervalSecProp = propRepo.get(JOB_CLUSTER_MAPPING_REFRESH_INTERVAL_SEC_PROP, Integer.class)
.orElse(60);
this.subscriptionRefreshIntervalSecProp = propRepo.get(SUBS_REFRESH_INTERVAL_SEC_PROP, Integer.class)
.orElse(1);
this.subscriptionExpiryIntervalSecProp = propRepo.get(SUBS_EXPIRY_INTERVAL_SEC_PROP, Integer.class)
.orElse(5 * 60);
this.subsFetchQueryParamStr = propRepo.get(SUBS_FETCH_QUERY_PARAMS_STR_PROP, String.class)
.orElse("");
this.discoveryApiHostnameProp = propRepo.get(DISCOVERY_API_HOSTNAME_PROP, String.class)
.orElse("127.0.0.1");
this.discoveryApiPortProp = propRepo.get(DISCOVERY_API_PORT_PROP, Integer.class)
.orElse(80);
this.gzipEnabled =
propRepo.get(CHANNEL_GZIP_ENABLED_PROP, Boolean.class)
.orElse(true);
this.idleTimeoutSeconds =
propRepo.get(CHANNEL_IDLE_TIMEOUT_SEC_PROP, Integer.class)
.orElse(300); // 5 minutes
this.httpChunkSize =
propRepo.get(CHANNEL_HTTP_CHUNK_SIZE_BYTES_PROP, Integer.class)
.orElse(32768); // 32 KiB
this.writeTimeoutSeconds =
propRepo.get(CHANNEL_WRITE_TIMEOUT_SEC_PROP, Integer.class)
.orElse(1);
this.flushIntervalMs =
propRepo.get(CHANNEL_FLUSH_INTERVAL_MSEC, Long.class)
.orElse(50L);
this.flushIntervalBytes =
propRepo.get(CHANNEL_FLUSH_INTERVAL_BYTES, Integer.class)
.orElse(512 * 1024); // 500 KiB
this.lowWriteBufferWatermark =
propRepo.get(CHANNEL_LOW_WRITE_BUFFER_WATERMARK_BYTES, Integer.class)
.orElse(1572864); // 1.5 MiB
this.highWriteBufferWatermark =
propRepo.get(CHANNEL_HIGH_WRITE_BUFFER_WATERMARK_BYTES, Integer.class)
.orElse(2097152); // 2 MiB
this.ioThreads =
propRepo.get(CHANNEL_IO_THREADS, Integer.class)
.orElse(1);
this.compressionThreads =
propRepo.get(CHANNEL_COMPRESSION_THREADS, Integer.class)
.orElse(1);
this.workerPoolCapacity =
propRepo.get(WORKER_POOL_CAPACITY_PROP, Integer.class)
.orElse(1000);
this.workerPoolRefreshIntervalSec =
propRepo.get(WORKER_POOL_REFRESH_INTERVAL_SEC_PROP, Integer.class)
.orElse(10);
this.workerPoolWorkerErrorQuota =
propRepo.get(WORKER_POOL_WORKER_ERROR_QUOTA_PROP, Integer.class)
.orElse(60);
this.workerPoolWorkerErrorTimeoutSec =
propRepo.get(WORKER_POOL_WORKER_ERROR_TIMEOUT_SEC, Integer.class)
.orElse(300);
}
@Override
public boolean isMREClientEnabled() {
return mreClientEnabled.get();
}
@Override
public String appName() {
return appName.get();
}
@Override
public boolean isTeeEnabled() {
return mreClientTeeEnabled.get();
}
@Override
public String teeStreamName() {
return mreClientTeeStreamName.get();
}
@Override
public String blackListedKeysCSV() {
return blacklistedKeys.get();
}
@Override
public int maxNumStreams() {
return maxNumStreams.get();
}
@Override
public long streamInactiveDurationThreshold() {
return streamInactiveDurationThreshold.get();
}
@Override
public int maxSubscriptionCount() {
return maxSubscriptionCount.get();
}
@Override
public boolean isDeepCopyEventMapEnabled() {
return deepCopyEventMapEnabled.get();
}
@Override
public int streamQueueSize(final String streamName) {
queueSizeByStreamType.putIfAbsent(streamName,
propRepo.get(String.format(PER_STREAM_QUEUE_SIZE_FORMAT, streamName), Integer.class)
.orElse(1000));
Property<Integer> streamQueueSizeProp = queueSizeByStreamType.get(streamName);
return streamQueueSizeProp.get();
}
@Override
public int maxSubscriptions(final String streamName) {
maxSubsByStreamType.putIfAbsent(streamName,
propRepo.get(String.format(MAX_SUBS_PER_STREAM_FORMAT, streamName), Integer.class)
.orElse(maxSubscriptionCount()));
Property<Integer> maxSubsProp = maxSubsByStreamType.get(streamName);
return maxSubsProp.get();
}
@Override
public Map<String, String> streamNameToJobClusterMapping() {
Map<String, String> mapping = new HashMap<>();
// TBD: call discovery api to fetch mappings from stream to job cluster for current app
mapping.put(StreamType.DEFAULT_EVENT_STREAM, mantisJobCluster(StreamType.DEFAULT_EVENT_STREAM));
mapping.put(StreamType.LOG_EVENT_STREAM, mantisJobCluster(StreamType.LOG_EVENT_STREAM));
mapping.put(StreamType.REQUEST_EVENT_STREAM, mantisJobCluster(StreamType.DEFAULT_EVENT_STREAM));
// mapping.put(StreamJobClusterMap.DEFAULT_STREAM_KEY,mantisJobCluster(StreamType.DEFAULT_EVENT_STREAM));
return mapping;
}
@Override
public String mantisJobCluster(final String streamName) {
jobClusterByStreamType.putIfAbsent(streamName,
propRepo.get(PUBLISH_JOB_CLUSTER_PROP_PREFIX + streamName, String.class)
.orElse("JobClusterNotConfiguredFor" + streamName));
Property<String> jobClusterProp = jobClusterByStreamType.get(streamName);
return jobClusterProp.get();
}
@Override
public int drainerIntervalMsec() {
return drainerIntervalMSecProp.get();
}
@Override
public int subscriptionRefreshIntervalSec() {
return subscriptionRefreshIntervalSecProp.get();
}
@Override
public int subscriptionExpiryIntervalSec() {
return subscriptionExpiryIntervalSecProp.get();
}
@Override
public int jobDiscoveryRefreshIntervalSec() {
return jobDiscoveryRefreshIntervalSecProp.get();
}
@Override
public int jobClusterMappingRefreshIntervalSec() {
return jobClusterMappingRefreshIntervalSecProp.get();
}
@Override
public String discoveryApiHostname() {
return discoveryApiHostnameProp.get();
}
@Override
public int discoveryApiPort() {
return discoveryApiPortProp.get();
}
@Override
public int maxNumWorkersToFetchSubscriptionsFrom() {
return maxNumWorkersForSubsRefresh.get();
}
@Override
public String subscriptionFetchQueryParams() {
return subsFetchQueryParamStr.get();
}
@Override
public boolean getGzipEnabled() {
return gzipEnabled.get();
}
@Override
public int getIdleTimeoutSeconds() {
return idleTimeoutSeconds.get();
}
@Override
public int getHttpChunkSize() {
return httpChunkSize.get();
}
@Override
public int getWriteTimeoutSeconds() {
return writeTimeoutSeconds.get();
}
@Override
public long getFlushIntervalMs() {
return flushIntervalMs.get();
}
@Override
public int getFlushIntervalBytes() {
return flushIntervalBytes.get();
}
@Override
public int getLowWriteBufferWatermark() {
return lowWriteBufferWatermark.get();
}
@Override
public int getHighWriteBufferWatermark() {
return highWriteBufferWatermark.get();
}
@Override
public int getIoThreads() {
return ioThreads.get();
}
@Override
public int getCompressionThreads() {
return compressionThreads.get();
}
@Override
public int getWorkerPoolCapacity() {
return workerPoolCapacity.get();
}
@Override
public int getWorkerPoolRefreshIntervalSec() {
return workerPoolRefreshIntervalSec.get();
}
@Override
public int getWorkerPoolWorkerErrorQuota() {
return workerPoolWorkerErrorQuota.get();
}
@Override
public int getWorkerPoolWorkerErrorTimeoutSec() {
return workerPoolWorkerErrorTimeoutSec.get();
}
}
| 8,330 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/providers/StreamManagerProvider.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.providers;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.StreamManager;
import io.mantisrx.publish.config.MrePublishConfiguration;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Provides an instance of a Mantis {@link StreamManager}.
*
* This class can be created standalone via its constructor or created with any injector implementation.
*/
@Singleton
public class StreamManagerProvider implements Provider<StreamManager> {
private final MrePublishConfiguration configuration;
private final Registry registry;
@Inject
public StreamManagerProvider(MrePublishConfiguration configuration, Registry registry) {
this.configuration = configuration;
this.registry = registry;
}
@Override
@Singleton
public StreamManager get() {
return new StreamManager(registry, configuration);
}
}
| 8,331 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/providers/EventPublisherProvider.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.providers;
import io.mantisrx.publish.MantisEventPublisher;
import io.mantisrx.publish.StreamManager;
import io.mantisrx.publish.api.EventPublisher;
import io.mantisrx.publish.config.MrePublishConfiguration;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Provides an instance of a Mantis {@link EventPublisher}.
*
* This class can be created standalone via its constructor or created with any injector implementation.
*/
@Singleton
public class EventPublisherProvider implements Provider<EventPublisher> {
private final MrePublishConfiguration config;
private final StreamManager streamManager;
@Inject
public EventPublisherProvider(MrePublishConfiguration config, StreamManager streamManager) {
this.config = config;
this.streamManager = streamManager;
}
@Override
@Singleton
public EventPublisher get() {
return new MantisEventPublisher(config, streamManager);
}
}
| 8,332 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/providers/MrePublishClientInitializerProvider.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.providers;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.EventTransmitter;
import io.mantisrx.publish.MrePublishClientInitializer;
import io.mantisrx.publish.StreamManager;
import io.mantisrx.publish.SubscriptionTracker;
import io.mantisrx.publish.Tee;
import io.mantisrx.publish.api.EventPublisher;
import io.mantisrx.publish.config.MrePublishConfiguration;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Provides an instance of a Mantis {@link MrePublishClientInitializer}.
*
* This class can be created standalone via its constructor or created with any injector implementation.
*/
@Singleton
public class MrePublishClientInitializerProvider implements Provider<MrePublishClientInitializer> {
private final MrePublishConfiguration config;
private final Registry registry;
private final StreamManager streamManager;
private final EventPublisher eventPublisher;
private final SubscriptionTracker subscriptionTracker;
private final EventTransmitter eventTransmitter;
private final Tee tee;
@Inject
public MrePublishClientInitializerProvider(
MrePublishConfiguration config,
Registry registry,
StreamManager streamManager,
EventPublisher eventPublisher,
SubscriptionTracker subscriptionTracker,
EventTransmitter eventTransmitter,
Tee tee) {
this.config = config;
this.registry = registry;
this.streamManager = streamManager;
this.eventPublisher = eventPublisher;
this.subscriptionTracker = subscriptionTracker;
this.eventTransmitter = eventTransmitter;
this.tee = tee;
}
@Override
@Singleton
public MrePublishClientInitializer get() {
MrePublishClientInitializer clientInitializer =
new MrePublishClientInitializer(
config,
registry,
streamManager,
eventPublisher,
subscriptionTracker,
eventTransmitter,
tee);
clientInitializer.start();
return clientInitializer;
}
}
| 8,333 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/providers/MantisJobDiscoveryProvider.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.providers;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.ipc.http.HttpClient;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.MantisJobDiscovery;
import io.mantisrx.publish.internal.discovery.MantisJobDiscoveryCachingImpl;
import io.mantisrx.publish.internal.discovery.mantisapi.DefaultMantisApiClient;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Provides an instance of a Mantis {@link MantisJobDiscovery}.
*
* This class can be created standalone via its constructor or created with any injector implementation.
*/
@Singleton
public class MantisJobDiscoveryProvider implements Provider<MantisJobDiscovery> {
private final MrePublishConfiguration configuration;
private final Registry registry;
@Inject
public MantisJobDiscoveryProvider(MrePublishConfiguration configuration, Registry registry) {
this.configuration = configuration;
this.registry = registry;
}
@Override
@Singleton
public MantisJobDiscovery get() {
return new MantisJobDiscoveryCachingImpl(configuration, registry,
new DefaultMantisApiClient(configuration, HttpClient.create(registry)));
}
}
| 8,334 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/providers/TeeProvider.java | /*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.providers;
import com.netflix.spectator.api.Registry;
import io.mantisrx.publish.NoOpTee;
import io.mantisrx.publish.Tee;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
/**
* Provides an instance of a Mantis {@link Tee}.
*
* This class can be created standalone via its constructor or created with any injector implementation.
*/
@Singleton
public class TeeProvider implements Provider<Tee> {
private final Registry registry;
@Inject
public TeeProvider(Registry registry) {
this.registry = registry;
}
@Override
@Singleton
public Tee get() {
return new NoOpTee(registry);
}
}
| 8,335 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/metrics/StreamMetrics.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.metrics;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.impl.AtomicDouble;
import java.util.concurrent.atomic.AtomicLong;
public class StreamMetrics {
private final String streamName;
private final Counter mantisEventsDroppedCounter;
private final Counter mantisEventsDroppedProcessingExceptionCounter;
private final Counter mantisEventsProcessedCounter;
private final Counter mantisEventsSkippedCounter;
private final Counter mantisQueryRejectedCounter;
private final Counter mantisQueryFailedCounter;
private final Counter mantisQueryProjectionFailedCounter;
private final AtomicDouble mantisEventsQueuedGauge;
private final AtomicDouble mantisActiveQueryCountGauge;
private final Timer mantisEventsProcessTimeTimer;
private final AtomicLong lastEventOnStreamTimestamp = new AtomicLong(0L);
public StreamMetrics(Registry registry, final String streamName) {
this.streamName = streamName;
this.mantisEventsDroppedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisEventsDropped", "stream", streamName, "reason", "publisherQueueFull");
this.mantisEventsDroppedProcessingExceptionCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisEventsDropped", "stream", streamName, "reason", "processingException");
this.mantisEventsProcessedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisEventsProcessed", "stream", streamName);
this.mantisEventsSkippedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisEventsSkipped", "stream", streamName);
this.mantisQueryRejectedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisQueryRejected", "stream", streamName);
this.mantisQueryFailedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisQueryFailed", "stream", streamName);
this.mantisQueryProjectionFailedCounter = SpectatorUtils.buildAndRegisterCounter(
registry, "mantisQueryProjectionFailed", "stream", streamName);
this.mantisEventsQueuedGauge = SpectatorUtils.buildAndRegisterGauge(
registry, "mantisEventsQueued", "stream", streamName);
this.mantisActiveQueryCountGauge = SpectatorUtils.buildAndRegisterGauge(
registry, "mantisActiveQueryCount", "stream", streamName);
this.mantisEventsProcessTimeTimer = SpectatorUtils.buildAndRegisterTimer(
registry, "mantisEventsProcessTime", "stream", streamName);
updateLastEventOnStreamTimestamp();
}
public String getStreamName() {
return streamName;
}
public Counter getMantisEventsDroppedCounter() {
return mantisEventsDroppedCounter;
}
public Counter getMantisEventsDroppedProcessingExceptionCounter() {
return mantisEventsDroppedProcessingExceptionCounter;
}
public Counter getMantisEventsProcessedCounter() {
return mantisEventsProcessedCounter;
}
public Counter getMantisEventsSkippedCounter() {
return mantisEventsSkippedCounter;
}
public Counter getMantisQueryRejectedCounter() {
return mantisQueryRejectedCounter;
}
public Counter getMantisQueryFailedCounter() {
return mantisQueryFailedCounter;
}
public Counter getMantisQueryProjectionFailedCounter() {
return mantisQueryProjectionFailedCounter;
}
public AtomicDouble getMantisEventsQueuedGauge() {
return mantisEventsQueuedGauge;
}
public AtomicDouble getMantisActiveQueryCountGauge() {
return mantisActiveQueryCountGauge;
}
public Timer getMantisEventsProcessTimeTimer() {
return mantisEventsProcessTimeTimer;
}
public void updateLastEventOnStreamTimestamp() {
lastEventOnStreamTimestamp.set(System.nanoTime());
}
public long getLastEventOnStreamTimestamp() {
return lastEventOnStreamTimestamp.get();
}
}
| 8,336 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/metrics/SpectatorUtils.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.metrics;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.Timer;
import com.netflix.spectator.api.patterns.PolledMeter;
import com.netflix.spectator.impl.AtomicDouble;
public class SpectatorUtils {
public static Counter buildAndRegisterCounter(Registry registry, String name) {
Id id = registry.createId(name);
return registry.counter(id);
}
public static AtomicDouble buildAndRegisterGauge(Registry registry, String name) {
Id id = registry.createId(name);
return PolledMeter.using(registry).withId(id).monitorValue(new AtomicDouble());
}
public static Timer buildAndRegisterTimer(Registry registry, String name) {
Id id = registry.createId(name);
return registry.timer(id);
}
public static Counter buildAndRegisterCounter(Registry registry, String name, String... tags) {
Id id = registry.createId(name).withTags(tags);
return registry.counter(id);
}
public static AtomicDouble buildAndRegisterGauge(Registry registry, String name, String... tags) {
Id id = registry.createId(name).withTags(tags);
return PolledMeter.using(registry).withId(id).monitorValue(new AtomicDouble());
}
public static Timer buildAndRegisterTimer(Registry registry, String name, String... tags) {
Id id = registry.createId(name).withTags(tags);
return registry.timer(id);
}
}
| 8,337 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/mql/MQL.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.mql;
import io.mantisrx.mql.jvm.core.Query;
import io.mantisrx.mql.shaded.clojure.java.api.Clojure;
import io.mantisrx.mql.shaded.clojure.lang.IFn;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MQL {
private static final Logger LOG = LoggerFactory.getLogger(MQL.class);
private static IFn require = Clojure.var("io.mantisrx.mql.shaded.clojure.core", "require");
private static IFn cljMakeQuery = Clojure.var("io.mantisrx.mql.jvm.interfaces.server", "make-query");
private static IFn cljSuperset = Clojure.var("io.mantisrx.mql.jvm.interfaces.core", "queries->superset-projection");
static {
require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.server"));
require.invoke(Clojure.read("io.mantisrx.mql.jvm.interfaces.core"));
}
public static void init() {
LOG.info("Initializing MQL Runtime.");
}
public static Query query(String subscriptionId, String query) {
return (Query) cljMakeQuery.invoke(subscriptionId, query.trim());
}
@SuppressWarnings("unchecked")
public static Function<Map<String, Object>, Map<String, Object>> makeSupersetProjector(
HashSet<Query> queries) {
ArrayList<String> qs = new ArrayList<>(queries.size());
for (Query query : queries) {
qs.add(query.getRawQuery());
}
IFn ssProjector = (IFn) cljSuperset.invoke(new ArrayList(qs));
return (datum) -> (Map<String, Object>) (ssProjector.invoke(datum));
}
public static String preprocess(String criterion) {
return criterion.toLowerCase().equals("true") ? "select * where true" :
criterion.toLowerCase().equals("false") ? "select * where false" :
criterion;
}
public static boolean isContradictionQuery(String query) {
return query.equals("false") ||
query.equals("select * where false") ||
query.equals("select * from stream where false");
}
}
| 8,338 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/mql/MQLSubscription.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.mql;
import io.mantisrx.mql.jvm.core.Query;
import io.mantisrx.publish.api.Event;
import io.mantisrx.publish.core.Subscription;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A {@link Subscription} based on the Mantis Query Language (MQL).
*/
public class MQLSubscription implements Subscription, Comparable {
private static final Logger LOG = LoggerFactory.getLogger(MQLSubscription.class);
protected final Query query;
private AtomicBoolean matcherErrorLoggingEnabled;
private AtomicBoolean projectorErrorLoggingEnabled;
private ConcurrentHashMap<
HashSet<Query>,
Function<
Map<String, Object>,
Map<String, Object>>> superSetProjectorCache;
public MQLSubscription(String subId, String criterion) {
this.superSetProjectorCache = new ConcurrentHashMap<>();
this.matcherErrorLoggingEnabled = new AtomicBoolean(true);
this.projectorErrorLoggingEnabled = new AtomicBoolean(true);
this.query = MQL.query(subId, MQL.preprocess(criterion));
}
private Map<String, Object> projectSuperSet(
Collection<Query> queries, Map<String, Object> datum) {
Function<Map<String, Object>, Map<String, Object>> superSetProjector =
superSetProjectorCache.computeIfAbsent(
new HashSet<>(queries), MQL::makeSupersetProjector);
return superSetProjector.apply(datum);
}
public Query getQuery() {
return query;
}
public String getRawQuery() {
return this.query.getRawQuery();
}
public String getSubscriptionId() {
return this.query.getSubscriptionId();
}
public Event projectSuperset(List<Subscription> subscriptions, Event event) {
List<Query> queries = new ArrayList<>(subscriptions.size());
for (Subscription sub : subscriptions) {
queries.add(sub.getQuery());
}
try {
return new Event(projectSuperSet(queries, event.getMap()));
} catch (Exception e) {
if (projectorErrorLoggingEnabled.get()) {
LOG.error("MQL projector produced an exception on queries: {}\ndatum: {}.",
queries, event.getMap());
projectorErrorLoggingEnabled.set(false);
}
Event error = new Event();
error.set("message", e.getMessage());
error.set("queries",
queries.stream()
.map(Query::getRawQuery)
.collect(Collectors.joining(", ")));
return error;
}
}
public boolean matches(Event event) {
try {
return this.query.matches(event.getMap());
} catch (Exception ex) {
if (matcherErrorLoggingEnabled.get()) {
LOG.error("MQL matcher produced an exception on query: {}\ndatum: {}.",
this.query.getRawQuery(), event.getMap());
matcherErrorLoggingEnabled.set(false);
}
return false;
}
}
@SuppressWarnings("unchecked")
public List<String> getSubjects() {
return this.query.getSubjects();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((this.query == null) ? 0 : this.query.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MQLSubscription other = (MQLSubscription) obj;
if (this.query == null) {
if (other.query != null)
return false;
} else if (!query.equals(other.query))
return false;
return true;
}
@Override
public int compareTo(final Object o) {
MQLSubscription other = (MQLSubscription) o;
if (this.equals(other)) {
return 0;
}
if (other != null) {
if (this.query.equals(other.query)) {
return 0;
} else {
int result = this.getSubscriptionId().compareTo(other.getSubscriptionId());
result = result == 0 ? this.getRawQuery().compareTo(other.getRawQuery()) : result;
// compareTo should confirm with equals,
// so return non-zero result if the subIds/query are same for the two queries
return result == 0 ? -1 : result;
}
} else {
return -1;
}
}
@Override
public String toString() {
return "MQLSubscription [subId=" + this.query.getSubscriptionId() +
", criterion=" + this.query.getRawQuery() + "]";
}
}
| 8,339 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/MantisJobDiscovery.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import java.util.Map;
import java.util.Optional;
public interface MantisJobDiscovery {
/**
* Look up streamName to Mantis Job Cluster mappings for an app.
*
* @param app name of application
*
* @return AppJobClustersMap stream name to job cluster mappings
*/
Optional<AppJobClustersMap> getJobClusterMappings(String app);
/**
* Look up the current set of Mantis Workers for given Mantis Job Cluster.
*
* @param jobCluster name of job cluster
*
* @return JobDiscoveryInfo worker locations for the most recent JobID of the job cluster
*/
Optional<JobDiscoveryInfo> getCurrentJobWorkers(String jobCluster);
/**
* List of Job Clusters per stream configured to receive data for an app.
*
* @return Stream name to Job cluster mapping
*/
Map<String, String> getStreamNameToJobClusterMapping(String app);
/**
* Look up the job cluster for a given app and stream.
*
* @param app upstream application which is producing events
* @param stream the stream which the upstream application is producing to
*
* @return Job Cluster string
*/
String getJobCluster(String app, String stream);
}
| 8,340 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/MantisJobDiscoveryStaticImpl.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.discovery.proto.StageWorkers;
import io.mantisrx.discovery.proto.StreamJobClusterMap;
import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Use for local testing. Returns a static JobDiscoveryInfo configuration.
*/
public class MantisJobDiscoveryStaticImpl implements MantisJobDiscovery {
private static final Logger logger = LoggerFactory.getLogger(MantisJobDiscoveryCachingImpl.class);
private static final ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module()).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
private static final String DEFAULT_JOB_CLUSTER = "SharedPushEventSource";
private static final String JOB_CLUSTER_LOOKUP_FAILED = "JobClusterLookupFailed";
String mreAppJobClusterMapStr="{\"version\": \"1\", "
+ "\"timestamp\": 12345, "
+ "\"mappings\": "
+ "{\"__default__\": {\"requestEventStream\": \"SharedPushRequestEventSource\","
+ "\"__default__\": \"" + DEFAULT_JOB_CLUSTER + "\"}}}";
private AppJobClustersMap appJobClustersMap;
private String workerHost;
private int workerPort;
/**
* For connecting to locally running source jobs
* use localhost:9090
* @param host
* @param port
*/
public MantisJobDiscoveryStaticImpl(String host, int port) {
try {
this.workerHost = host;
this.workerPort = port;
appJobClustersMap = mapper.readValue(mreAppJobClusterMapStr, AppJobClustersMap.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Override
public Optional<AppJobClustersMap> getJobClusterMappings(String app) {
return Optional.of(appJobClustersMap);
}
@Override
public Optional<JobDiscoveryInfo> getCurrentJobWorkers(String jobCluster) {
Map<Integer, StageWorkers> stageWorkersMap = new HashMap<>();
List<MantisWorker> workerList = new ArrayList<>();
MantisWorker mantisWorker = new MantisWorker(workerHost, workerPort);
workerList.add(mantisWorker);
stageWorkersMap.put(1, new StageWorkers(jobCluster, jobCluster + "-1",1, workerList));
JobDiscoveryInfo jobDiscoveryInfo = new JobDiscoveryInfo(jobCluster, jobCluster + "-1",stageWorkersMap);
return Optional.of(jobDiscoveryInfo);
}
@Override
public Map<String, String> getStreamNameToJobClusterMapping(String app) {
String appName = DEFAULT_JOB_CLUSTER;
Optional<AppJobClustersMap> jobClusterMappingsO = getJobClusterMappings(appName);
if (jobClusterMappingsO.isPresent()) {
AppJobClustersMap appJobClustersMap = jobClusterMappingsO.get();
StreamJobClusterMap streamJobClusterMap = appJobClustersMap.getStreamJobClusterMap(appName);
return streamJobClusterMap.getStreamJobClusterMap();
} else {
logger.info("Failed to lookup stream to job cluster mapping for app {}", appName);
return Collections.emptyMap();
}
}
@Override
public String getJobCluster(String app, String stream) {
String appName = DEFAULT_JOB_CLUSTER;
Optional<AppJobClustersMap> jobClusterMappingsO = getJobClusterMappings(appName);
if (jobClusterMappingsO.isPresent()) {
AppJobClustersMap appJobClustersMap = jobClusterMappingsO.get();
StreamJobClusterMap streamJobClusterMap = appJobClustersMap.getStreamJobClusterMap(appName);
return streamJobClusterMap.getJobCluster(stream);
} else {
logger.info("Failed to lookup job cluster for app {} stream {}", appName, stream);
return JOB_CLUSTER_LOOKUP_FAILED;
}
}
}
| 8,341 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/MantisJobDiscoveryCachingImpl.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery;
import static io.mantisrx.discovery.proto.AppJobClustersMap.DEFAULT_APP_KEY;
import com.netflix.spectator.api.Counter;
import com.netflix.spectator.api.Registry;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.StreamJobClusterMap;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.mantisapi.MantisApiClient;
import io.mantisrx.publish.internal.exceptions.NonRetryableException;
import io.mantisrx.publish.internal.metrics.SpectatorUtils;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MantisJobDiscoveryCachingImpl implements MantisJobDiscovery {
private static final Logger logger = LoggerFactory.getLogger(MantisJobDiscoveryCachingImpl.class);
private static final String JOB_CLUSTER_LOOKUP_FAILED = "JobClusterLookupFailed";
private final MantisApiClient mantisApiClient;
private final MrePublishConfiguration configuration;
private final ConcurrentMap<String, AtomicLong> lastFetchTimeMs = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Optional<JobDiscoveryInfo>> jobClusterDiscoveryInfoMap = new ConcurrentHashMap<>();
private final ConcurrentMap<String, AppJobClustersMap> appJobClusterMapping = new ConcurrentHashMap<>();
private final Counter jobDiscoveryRefreshSuccess;
private final Counter jobDiscoveryRefreshFailed;
private final Counter jobClusterMappingRefreshSuccess;
private final Counter jobClusterMappingRefreshFailed;
public MantisJobDiscoveryCachingImpl(MrePublishConfiguration configuration,
Registry registry,
MantisApiClient mantisApiClient) {
this.configuration = configuration;
this.mantisApiClient = mantisApiClient;
this.jobDiscoveryRefreshSuccess = SpectatorUtils.buildAndRegisterCounter(registry, "jobDiscoveryRefreshSuccess");
this.jobDiscoveryRefreshFailed = SpectatorUtils.buildAndRegisterCounter(registry, "jobDiscoveryRefreshFailed");
this.jobClusterMappingRefreshSuccess = SpectatorUtils.buildAndRegisterCounter(registry, "jobClusterMappingRefreshSuccess");
this.jobClusterMappingRefreshFailed = SpectatorUtils.buildAndRegisterCounter(registry, "jobClusterMappingRefreshFailed");
}
void refreshDiscoveryInfo(String jobClusterName) {
CompletableFuture<JobDiscoveryInfo> jobDiscoveryInfoF = mantisApiClient.jobDiscoveryInfo(jobClusterName);
if (jobClusterDiscoveryInfoMap.containsKey(jobClusterName)) {
// We retrieved discovery info for this job cluster before, allow this refresh to finish async.
jobDiscoveryInfoF.whenCompleteAsync((jdi, t) -> {
if (jdi != null) {
jobClusterDiscoveryInfoMap.put(jobClusterName, Optional.ofNullable(jdi));
jobDiscoveryRefreshSuccess.increment();
} else {
// on failure to refresh job discovery info, continue to serve previous job discovery info
logger.info("failed to refresh job discovery info, will serve old job discovery info");
jobDiscoveryRefreshFailed.increment();
}
});
} else {
// We haven't seen discovery info for this job cluster before, block till we have a response.
try {
// Synchronously await Job Discovery info first time we get a job discovery request for a job cluster.
JobDiscoveryInfo jobDiscoveryInfo = jobDiscoveryInfoF.get(1, TimeUnit.SECONDS);
jobClusterDiscoveryInfoMap.put(jobClusterName, Optional.ofNullable(jobDiscoveryInfo));
jobDiscoveryRefreshSuccess.increment();
} catch (InterruptedException e) {
logger.warn("interrupted on job discovery fetch {}", jobClusterName, e);
jobDiscoveryRefreshFailed.increment();
} catch (ExecutionException e) {
jobDiscoveryRefreshFailed.increment();
if (e.getCause() instanceof NonRetryableException) {
logger.warn("non retryable exception on job discovery fetch {}, update cache to avoid blocking refresh in future", jobClusterName, e.getCause());
jobClusterDiscoveryInfoMap.put(jobClusterName, Optional.empty());
} else {
logger.warn("caught exception on job discovery fetch {}", jobClusterName, e.getCause());
}
} catch (TimeoutException e) {
jobDiscoveryRefreshFailed.increment();
logger.warn("timed out on job discovery fetch {}", jobClusterName, e);
}
}
}
private boolean shouldRefreshWorkers(String jobCluster) {
lastFetchTimeMs.putIfAbsent(jobCluster, new AtomicLong(0));
long lastFetchMs = lastFetchTimeMs.get(jobCluster).get();
return (System.currentTimeMillis() - lastFetchMs) > (configuration.jobDiscoveryRefreshIntervalSec() * 1000);
}
@Override
public Optional<JobDiscoveryInfo> getCurrentJobWorkers(String jobClusterName) {
if (shouldRefreshWorkers(jobClusterName)) {
refreshDiscoveryInfo(jobClusterName);
lastFetchTimeMs.get(jobClusterName).set(System.currentTimeMillis());
}
return jobClusterDiscoveryInfoMap.getOrDefault(jobClusterName, Optional.empty());
}
@Override
public Map<String, String> getStreamNameToJobClusterMapping(String app) {
String appName = configuration.appName();
Optional<AppJobClustersMap> jobClusterMappingsO = getJobClusterMappings(appName);
if (jobClusterMappingsO.isPresent()) {
AppJobClustersMap appJobClustersMap = jobClusterMappingsO.get();
StreamJobClusterMap streamJobClusterMap = appJobClustersMap.getStreamJobClusterMap(appName);
return streamJobClusterMap.getStreamJobClusterMap();
} else {
logger.info("Failed to lookup stream to job cluster mapping for app {}", appName);
return Collections.emptyMap();
}
}
@Override
public String getJobCluster(String app, String stream) {
String appName = configuration.appName();
Optional<AppJobClustersMap> jobClusterMappingsO = getJobClusterMappings(appName);
if (jobClusterMappingsO.isPresent()) {
AppJobClustersMap appJobClustersMap = jobClusterMappingsO.get();
StreamJobClusterMap streamJobClusterMap = appJobClustersMap.getStreamJobClusterMap(appName);
return streamJobClusterMap.getJobCluster(stream);
} else {
logger.info("Failed to lookup job cluster for app {} stream {}", appName, stream);
return JOB_CLUSTER_LOOKUP_FAILED;
}
}
private boolean shouldRefreshJobClusterMapping(String appName) {
lastFetchTimeMs.putIfAbsent(appName, new AtomicLong(0));
long lastFetchMs = lastFetchTimeMs.get(appName).get();
return (System.currentTimeMillis() - lastFetchMs) > (configuration.jobClusterMappingRefreshIntervalSec() * 1000);
}
void refreshJobClusterMapping(String app) {
CompletableFuture<AppJobClustersMap> jobClusterMappingF = mantisApiClient.getJobClusterMapping(Optional.ofNullable(app));
AppJobClustersMap cachedMapping = appJobClusterMapping.get(app);
if (cachedMapping != null) {
// We retrieved job cluster mapping info for this app before, allow this refresh to finish async.
jobClusterMappingF.whenCompleteAsync((mapping, t) -> {
if (mapping != null) {
long recvTimestamp = mapping.getTimestamp();
if (recvTimestamp >= cachedMapping.getTimestamp()) {
appJobClusterMapping.put(app, mapping);
jobClusterMappingRefreshSuccess.increment();
} else {
logger.info("ignoring job cluster mapping refresh with older timestamp {} than cached {}", recvTimestamp, cachedMapping.getTimestamp());
jobClusterMappingRefreshFailed.increment();
}
} else {
// On failure to refresh job discovery info, continue to serve previous job discovery info.
logger.info("failed to refresh job cluster mapping info, will serve old job cluster mapping");
jobClusterMappingRefreshFailed.increment();
}
});
} else {
// We haven't seen job cluster mapping for this app before, synchronously await job cluster mapping info.
try {
AppJobClustersMap appJobClustersMap = jobClusterMappingF.get(1, TimeUnit.SECONDS);
appJobClusterMapping.put(app, appJobClustersMap);
jobClusterMappingRefreshSuccess.increment();
} catch (Exception e) {
logger.warn("exception getting job cluster mapping {}", app, e);
jobClusterMappingRefreshFailed.increment();
}
}
}
private String appWithFallback(String app) {
return (app == null) ? DEFAULT_APP_KEY : app;
}
@Override
public Optional<AppJobClustersMap> getJobClusterMappings(String app) {
String appName = appWithFallback(app);
if (shouldRefreshJobClusterMapping(appName)) {
refreshJobClusterMapping(appName);
lastFetchTimeMs.get(appName).set(System.currentTimeMillis());
}
return Optional.ofNullable(appJobClusterMapping.get(appName));
}
}
| 8,342 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/proto/WorkerHost.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.proto;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* TODO: Duplicate WorkerHost from mantis-server-core lib, move to a common proto lib
*/
public class WorkerHost {
private final MantisJobState state;
private final int workerNumber;
private final int workerIndex;
private final String host;
private final List<Integer> port;
private final int metricsPort;
private final int customPort;
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public WorkerHost(@JsonProperty("host") String host, @JsonProperty("workerIndex") int workerIndex,
@JsonProperty("port") List<Integer> port, @JsonProperty("state") MantisJobState state,
@JsonProperty("workerNumber") int workerNumber, @JsonProperty("metricsPort") int metricsPort,
@JsonProperty("customPort") int customPort) {
this.host = host;
this.workerIndex = workerIndex;
this.port = port;
this.state = state;
this.workerNumber = workerNumber;
this.metricsPort = metricsPort;
this.customPort = customPort;
}
public int getWorkerNumber() {
return workerNumber;
}
public MantisJobState getState() {
return state;
}
public String getHost() {
return host;
}
public List<Integer> getPort() {
return port;
}
public int getWorkerIndex() {
return workerIndex;
}
public int getMetricsPort() {
return metricsPort;
}
public int getCustomPort() {
return customPort;
}
@Override
public String toString() {
return "WorkerHost [state=" + state + ", workerIndex=" + workerIndex
+ ", host=" + host + ", port=" + port + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((host == null) ? 0 : host.hashCode());
for (int p : port)
result = prime * result + p;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WorkerHost other = (WorkerHost) obj;
if (host == null) {
if (other.host != null)
return false;
} else if (!host.equals(other.host))
return false;
if (port == null) {
if (other.port != null)
return false;
} else {
if (other.port == null)
return false;
if (port.size() != other.port.size())
return false;
for (int p = 0; p < port.size(); p++)
if (port.get(p) != other.port.get(p))
return false;
}
return true;
}
}
| 8,343 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/proto/JobSchedulingInfo.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.proto;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/**
* TODO: Duplicate JobSchedulingInfo from mantis-server-core lib, move to a common proto lib
*/
public class JobSchedulingInfo {
public static final String HB_JobId = "HB_JobId";
public static final String SendHBParam = "sendHB";
private String jobId;
private Map<Integer, WorkerAssignments> workerAssignments; // index by stage num
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public JobSchedulingInfo(@JsonProperty("jobId") String jobId,
@JsonProperty("workerAssignments")
Map<Integer, WorkerAssignments> workerAssignments) {
this.jobId = jobId;
this.workerAssignments = workerAssignments;
}
public String getJobId() {
return jobId;
}
public Map<Integer, WorkerAssignments> getWorkerAssignments() {
return workerAssignments;
}
@Override
public String toString() {
return "SchedulingChange [jobId=" + jobId + ", workerAssignments="
+ workerAssignments + "]";
}
}
| 8,344 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/proto/MantisJobState.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.proto;
import java.util.HashMap;
import java.util.Map;
/**
* TODO: Duplicate MantisJobState from mantis-runtime lib, move to a common proto lib
*/
public enum MantisJobState {
Accepted,
Launched, // scheduled and sent to slave
StartInitiated, // initial message from slave worker, about to start
Started, // actually started running
Failed, // OK to handle as a resubmit
Completed, // terminal state, not necessarily successful
Noop; // internal use only
private static final Map<MantisJobState, MantisJobState[]> validChanges;
private static final Map<MantisJobState, MetaState> metaStates;
static {
validChanges = new HashMap<>();
validChanges.put(Accepted, new MantisJobState[] {Launched, Failed, Completed});
validChanges.put(Launched, new MantisJobState[] {StartInitiated, Started, Failed, Completed});
validChanges.put(StartInitiated, new MantisJobState[] {StartInitiated, Started, Completed, Failed});
validChanges.put(Started, new MantisJobState[] {Started, Completed, Failed});
validChanges.put(Failed, new MantisJobState[] {});
validChanges.put(Completed, new MantisJobState[] {});
metaStates = new HashMap<>();
metaStates.put(Accepted, MetaState.Active);
metaStates.put(Launched, MetaState.Active);
metaStates.put(StartInitiated, MetaState.Active);
metaStates.put(Started, MetaState.Active);
metaStates.put(Failed, MetaState.Terminal);
metaStates.put(Completed, MetaState.Terminal);
}
public static MetaState toMetaState(MantisJobState state) {
return metaStates.get(state);
}
public static boolean isTerminalState(MantisJobState state) {
switch (state) {
case Failed:
case Completed:
return true;
default:
return false;
}
}
public static boolean isErrorState(MantisJobState started) {
switch (started) {
case Failed:
return true;
default:
return false;
}
}
public static boolean isRunningState(MantisJobState state) {
switch (state) {
case Launched:
case StartInitiated:
case Started:
return true;
default:
return false;
}
}
public static boolean isOnSlaveState(MantisJobState state) {
switch (state) {
case StartInitiated:
case Started:
return true;
default:
return false;
}
}
public boolean isValidStateChgTo(MantisJobState newState) {
for (MantisJobState validState : validChanges.get(this))
if (validState == newState)
return true;
return false;
}
public enum MetaState {
Active,
Terminal
}
}
| 8,345 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/proto/WorkerAssignments.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.proto;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonCreator;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
/**
* TODO: Duplicate WorkerAssignments from mantis-server-core lib, move to a common proto lib
*/
public class WorkerAssignments {
private int stage;
private int numWorkers;
private int activeWorkers;
private Map<Integer, WorkerHost> hosts; // lookup by workerNumber
@JsonCreator
@JsonIgnoreProperties(ignoreUnknown = true)
public WorkerAssignments(@JsonProperty("stage") Integer stage,
@JsonProperty("numWorkers") Integer numWorkers,
@JsonProperty("hosts") Map<Integer, WorkerHost> hosts) {
this.stage = stage;
this.numWorkers = numWorkers;
this.hosts = hosts;
}
public int getStage() {
return stage;
}
public int getNumWorkers() {
return numWorkers;
}
public void setNumWorkers(int numWorkers) {
this.numWorkers = numWorkers;
}
public int getActiveWorkers() {
return activeWorkers;
}
public void setActiveWorkers(int activeWorkers) {
this.activeWorkers = activeWorkers;
}
public Map<Integer, WorkerHost> getHosts() {
return hosts;
}
@Override
public String toString() {
return "WorkerAssignments [stage=" + stage + ", numWorkers=" + numWorkers + ", hosts=" + hosts + "]";
}
}
| 8,346 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/mantisapi/DefaultMantisApiClient.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.mantisapi;
import com.netflix.spectator.ipc.http.HttpClient;
import com.netflix.spectator.ipc.http.HttpResponse;
import io.mantisrx.common.JsonSerializer;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import io.mantisrx.discovery.proto.MantisWorker;
import io.mantisrx.discovery.proto.StageWorkers;
import io.mantisrx.publish.config.MrePublishConfiguration;
import io.mantisrx.publish.internal.discovery.proto.JobSchedulingInfo;
import io.mantisrx.publish.internal.discovery.proto.MantisJobState;
import io.mantisrx.publish.internal.discovery.proto.WorkerAssignments;
import io.mantisrx.publish.internal.discovery.proto.WorkerHost;
import io.mantisrx.publish.internal.exceptions.NonRetryableException;
import io.mantisrx.publish.internal.exceptions.RetryableException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultMantisApiClient implements MantisApiClient {
private static final int CONNECT_TIMEOUT_MS = 1_000;
private static final int READ_TIMEOUT_MS = 1_000;
private static final Logger logger = LoggerFactory.getLogger(DefaultMantisApiClient.class);
private static final String JOB_CLUSTER_MAPPING_URL_FORMAT = "http://%s:%d/api/v1/mantis/publish/streamJobClusterMap";
private static final String JOB_DISCOVERY_URL_FORMAT = "http://%s:%d/jobClusters/discoveryInfo/%s";
private static final String JOB_DISCOVERY_STREAM_URL_FORMAT = "http://%s:%d/assignmentresults/%s";
private final JsonSerializer serializer = new JsonSerializer();
private final MrePublishConfiguration mrePublishConfiguration;
private final HttpClient httpClient;
public DefaultMantisApiClient(MrePublishConfiguration mrePublishConfiguration, HttpClient client) {
this.mrePublishConfiguration = mrePublishConfiguration;
this.httpClient = client;
}
@Override
public CompletableFuture<AppJobClustersMap> getJobClusterMapping(final Optional<String> app) {
return CompletableFuture.supplyAsync(() -> {
StringBuilder uriBuilder = new StringBuilder(String.format(JOB_CLUSTER_MAPPING_URL_FORMAT, mrePublishConfiguration.discoveryApiHostname(), mrePublishConfiguration.discoveryApiPort()));
app.ifPresent(appName -> uriBuilder.append("?app=").append(appName));
String uri = uriBuilder.toString();
logger.debug("job cluster mapping fetch url {}", uri);
try {
HttpResponse response = httpClient.get(URI.create(uri))
.withConnectTimeout(CONNECT_TIMEOUT_MS)
.withReadTimeout(READ_TIMEOUT_MS)
.send();
int status = response.status();
if (status >= 200 && status < 300) {
AppJobClustersMap appJobClustersMap = serializer.fromJSON(response.entityAsString(), AppJobClustersMap.class);
logger.debug(appJobClustersMap.toString());
return appJobClustersMap;
} else if (status >= 300 && status < 500) {
// TODO: handle redirects
logger.warn("got {} response from api on Job cluster mapping request for {}", status, app);
throw new CompletionException(new NonRetryableException("Failed to get job cluster mapping info for " + app + " status " + status));
} else {
logger.warn("got {} response from api on Job cluster mapping request for {}", status, app);
throw new CompletionException(new RetryableException("Failed to get job job cluster mapping info for " + app + " status " + status));
}
} catch (IOException e) {
logger.warn("caught exception", e);
throw new CompletionException(e);
}
});
}
@Override
public CompletableFuture<JobDiscoveryInfo> jobDiscoveryInfo(final String jobClusterName) {
return CompletableFuture.supplyAsync(() -> {
String uri = String.format(JOB_DISCOVERY_URL_FORMAT, mrePublishConfiguration.discoveryApiHostname(), mrePublishConfiguration.discoveryApiPort(), jobClusterName);
logger.debug("discovery info fetch url {}", uri);
try {
HttpResponse response = httpClient.get(URI.create(uri))
.withConnectTimeout(CONNECT_TIMEOUT_MS)
.withReadTimeout(READ_TIMEOUT_MS)
.send();
int status = response.status();
if (status >= 200 && status < 300) {
JobSchedulingInfo jobSchedulingInfo = serializer.fromJSON(response.entityAsString(), JobSchedulingInfo.class);
JobDiscoveryInfo jobDiscoveryInfo = convertJobSchedInfo(jobSchedulingInfo, jobClusterName);
logger.debug(jobDiscoveryInfo.toString());
return jobDiscoveryInfo;
} else if (status >= 300 && status < 500) {
// TODO: handle redirects
logger.warn("got {} response from api on Job Discovery request for {}", status, jobClusterName);
throw new CompletionException(new NonRetryableException("Failed to get job discovery info for " + jobClusterName + " status " + status));
} else {
logger.warn("got {} response from api on Job Discovery request for {}", status, jobClusterName);
throw new CompletionException(new RetryableException("Failed to get job discovery info for " + jobClusterName + " status " + status));
}
} catch (IOException e) {
logger.warn("caught exception", e);
throw new CompletionException(e);
}
});
}
private JobDiscoveryInfo convertJobSchedInfo(JobSchedulingInfo jobSchedulingInfo, String jobClusterName) {
Map<Integer, StageWorkers> jobWorkers = new HashMap<>();
for (Map.Entry<Integer, WorkerAssignments> e : jobSchedulingInfo.getWorkerAssignments().entrySet()) {
Integer stageNum = e.getKey();
WorkerAssignments workerAssignments = e.getValue();
List<MantisWorker> workerList = new ArrayList<>(workerAssignments.getHosts().size());
for (WorkerHost w : workerAssignments.getHosts().values()) {
if (MantisJobState.Started.equals(w.getState())) {
workerList.add(new MantisWorker(w.getHost(), w.getCustomPort()));
}
}
jobWorkers.put(stageNum, new StageWorkers(jobClusterName, jobSchedulingInfo.getJobId(), stageNum, workerList));
}
return new JobDiscoveryInfo(jobClusterName, jobSchedulingInfo.getJobId(), jobWorkers);
}
}
| 8,347 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/discovery/mantisapi/MantisApiClient.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.discovery.mantisapi;
import io.mantisrx.discovery.proto.AppJobClustersMap;
import io.mantisrx.discovery.proto.JobDiscoveryInfo;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
public interface MantisApiClient {
CompletableFuture<AppJobClustersMap> getJobClusterMapping(final Optional<String> app);
CompletableFuture<JobDiscoveryInfo> jobDiscoveryInfo(final String jobClusterName);
}
| 8,348 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/exceptions/NonRetryableException.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.exceptions;
public class NonRetryableException extends Exception {
public NonRetryableException(final String message) {
super(message);
}
}
| 8,349 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/internal/exceptions/RetryableException.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.internal.exceptions;
public class RetryableException extends Exception {
public RetryableException(final String message) {
super(message);
}
}
| 8,350 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/api/StreamType.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.api;
public class StreamType {
/**
* Default Stream name for emitting events.
*/
public static final String DEFAULT_EVENT_STREAM = "defaultStream";
/**
* Stream name for emitting request events.
*/
public static final String REQUEST_EVENT_STREAM = "requestEventStream";
/**
* Stream name for emitting log4j events by using the Mantis Log4J appender.
*/
public static final String LOG_EVENT_STREAM = "logEventStream";
}
| 8,351 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/api/Event.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.api;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonIgnore;
import io.mantisrx.shaded.com.fasterxml.jackson.annotation.JsonValue;
import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.SerializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Event {
private static final Logger LOG = LoggerFactory.getLogger(Event.class);
private static final AtomicBoolean ERROR_LOG_ENABLED = new AtomicBoolean(true);
private static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();
static {
JACKSON_MAPPER
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule());
}
private final Map<String, Object> attributes;
public Event() {
this(null);
}
public Event(Map<String, Object> attributes) {
this(attributes, true);
}
/**
* @deprecated
* Use {@link #Event(Map)} instead where <code>deepCopy</code> is default to true. Always creates a new top level
* Map to avoid any exceptions due to immutable map.
*/
@Deprecated
public Event(Map<String, Object> attributes, boolean deepCopy) {
if (attributes == null || deepCopy) {
this.attributes = new HashMap<>();
if (attributes != null) {
this.attributes.putAll(attributes);
}
} else {
this.attributes = attributes;
}
}
public Event set(String key, Object value) {
attributes.put(key, value);
return this;
}
public Object get(String key) {
return attributes.get(key);
}
public boolean has(String key) {
return attributes.containsKey(key);
}
public Iterator<String> keys() {
return attributes.keySet().iterator();
}
public Set<Map.Entry<String, Object>> entries() {
return attributes.entrySet();
}
@JsonValue
public Map<String, Object> getMap() {
return attributes;
}
@JsonIgnore
public boolean isEmpty() {
return attributes.isEmpty();
}
public String toJsonString() {
try {
return JACKSON_MAPPER.writeValueAsString(attributes);
} catch (JsonProcessingException e) {
if (ERROR_LOG_ENABLED.get()) {
LOG.error("failed to serialize Event to json {}", attributes.toString(), e);
ERROR_LOG_ENABLED.set(false);
}
LOG.debug("failed to serialize Event to json {}", attributes.toString(), e);
return "";
}
}
public Map<String, String> toStringMap() {
final Map<String, String> m = new HashMap<>();
for (Map.Entry<String, Object> entry : this.entries()) {
final Object val = entry.getValue();
if (val != null) {
m.put(entry.getKey(), String.valueOf(val));
}
}
return m;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Event event = (Event) o;
return Objects.equals(attributes, event.attributes);
}
@Override
public int hashCode() {
return Objects.hash(attributes);
}
@Override
public String toString() {
return String.format("%s%s", this.getClass().getSimpleName(), toJsonString());
}
}
| 8,352 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/api/EventPublisher.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.api;
import io.mantisrx.publish.core.Subscription;
import java.util.concurrent.CompletionStage;
public interface EventPublisher {
/**
* Publishes an event on the given stream.
*
* @param streamName name of the stream to publish the event to
* @param event event data to publish to Mantis
* @return {@link CompletionStage<PublishStatus>} status of publishing the message
*/
CompletionStage<PublishStatus> publish(String streamName, Event event);
/**
* Publishes an event on the {@value StreamType#DEFAULT_EVENT_STREAM} stream.
* <p>To publish an Event, use the following code:
* <pre> {@code
* eventPublisher.publish(new Event(attr))
* .whenComplete((s, t) -> {
* if (t != null) {
* LOG.error("caught exception processing event", t);
* } else {
* switch (s.getStatus()) {
* case SENDING:
* case SENT:
* // success
* break;
* case PRECONDITION_FAILED:
* // message was skipped due to client being disabled, no active MQL subs etc,increment a counter for visibility
* break;
* case FAILED:
* // error sending message, increment a counter and raise an alarm if too many failures
* LOG.error("failed to send event", s);
* break;
* default:
* }
* }
* });</pre>
* @param event event data to publish to Mantis
* @return {@link CompletionStage<PublishStatus>} status of publishing the message
*/
default CompletionStage<PublishStatus> publish(Event event) {
return publish(StreamType.DEFAULT_EVENT_STREAM, event);
}
/**
* Returns whether or not this event publisher has active {@link Subscription}s on
* {@value StreamType#DEFAULT_EVENT_STREAM}
* <p>
* This method is useful for checking for the existence of a stream before
* calling {@link EventPublisher#publish(Event)} to avoid the performance penalty when there
* are no active subscriptions for the stream.
*
*/
default boolean hasSubscriptions() {
return hasSubscriptions(StreamType.DEFAULT_EVENT_STREAM);
}
/**
* Returns whether or not this event publisher has active {@link Subscription}s.
* <p>
* This method is useful for checking for the existence of a stream before
* calling {@link EventPublisher#publish(Event)} to avoid the performance penalty when there
* are no active subscriptions for the stream.
*
* @param streamName name of the event stream
*/
boolean hasSubscriptions(String streamName);
}
| 8,353 |
0 | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish | Create_ds/mantis/mantis-publish/mantis-publish-core/src/main/java/io/mantisrx/publish/api/PublishStatus.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.publish.api;
/**
* Indicates the result of publishing an Event to Mantis.
*/
public enum PublishStatus {
/**
* Successfully enqueued the message for further MQL processing.
* This only indicates enqueue success and does not indicate the message was successfully MQL processed and sent to Mantis
*/
ENQUEUED(Status.SENDING),
// Skipped events due to precondition failures like no active subscriptions, publishing not enabled in configuration
/**
* Event was not enqueued since there are no active MQL subscriptions for the streamName
*/
SKIPPED_NO_SUBSCRIPTIONS(Status.PRECONDITION_FAILED),
/**
* Event was not enqueued since the Mantis Publish client is not enabled in configuration
*/
SKIPPED_CLIENT_NOT_ENABLED(Status.PRECONDITION_FAILED),
/**
* Event was not enqueued since the event was invalid (either null or empty)
*/
SKIPPED_INVALID_EVENT(Status.PRECONDITION_FAILED),
// Events dropped due to failures like burst in incoming traffic, too many stream queues created, transport issues
/**
* Event enqueue failed due to stream queue being full
*/
FAILED_QUEUE_FULL(Status.FAILED),
/**
* Event enqueue failed as the stream could not be registered, this could happen if max number of streams allowed per config is exceeded
*/
FAILED_STREAM_NOT_REGISTERED(Status.FAILED),
/**
* Event could not be sent as the Mantis Worker Info is unavailable for configured Mantis Job Cluster
*/
FAILED_WORKER_INFO_UNAVAILABLE(Status.FAILED),
/**
* Event processing failed to project superset
*/
FAILED_SUPERSET_PROJECTION(Status.FAILED);
public enum Status {
/**
* Indicates the event was skipped as expected due to a precondition failure
*/
PRECONDITION_FAILED,
/**
* Indicates the event is being sent (considered a successful send until {@link Status#SENT} is implemented).
* Clients should consider either a {@link Status#SENDING} or {@link Status#SENT} status as a Success to stay forward compatible.
*/
SENDING,
/**
* Not currently implemented but in future would indicate an event was successfully sent over the network to Mantis for further propagation
*/
SENT,
/**
* Failed to send the event
*/
FAILED
}
private final Status status;
PublishStatus(Status status) {
this.status = status;
}
public Status getStatus() {
return status;
}
@Override
public String toString() {
return super.toString() + "(" + status + ')';
}
}
| 8,354 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/WorkerConfigurationWritableTest.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import io.mantisrx.common.JsonSerializer;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.runtime.loader.config.WorkerConfigurationUtils;
import io.mantisrx.runtime.loader.config.WorkerConfigurationWritable;
import io.mantisrx.server.worker.config.StaticPropertiesConfigurationFactory;
import java.io.IOException;
import java.util.Properties;
import org.junit.Test;
public class WorkerConfigurationWritableTest {
static String ConfigWritableToString(WorkerConfigurationWritable configurationWritable) throws IOException {
JsonSerializer ser = new JsonSerializer();
return ser.toJson(configurationWritable);
}
@Test
public void testWorkerConfigurationConversion() throws IOException {
final Properties props = new Properties();
props.setProperty("mantis.zookeeper.root", "");
props.setProperty("mantis.taskexecutor.cluster.storage-dir", "");
props.setProperty("mantis.taskexecutor.local.storage-dir", "");
props.setProperty("mantis.taskexecutor.cluster-id", "default");
props.setProperty("mantis.taskexecutor.heartbeats.interval", "100");
props.setProperty("mantis.taskexecutor.metrics.collector", "io.mantisrx.server.agent.DummyMetricsCollector");
props.setProperty("mantis.taskexecutor.id", "testId1");
props.setProperty("mantis.taskexecutor.heartbeats.interval", "999");
props.setProperty("mantis.agent.mesos.slave.port", "998");
WorkerConfiguration configSource = new StaticPropertiesConfigurationFactory(props).getConfig();
WorkerConfigurationWritable configurationWritable = WorkerConfigurationUtils.toWritable(configSource);
assertNotNull(configurationWritable);
assertEquals("testId1", configurationWritable.getTaskExecutorId());
assertEquals(999, configurationWritable.getHeartbeatInternalInMs());
assertEquals(998, configurationWritable.getMesosSlavePort());
assertNotNull(configurationWritable.getUsageSupplier());
String configStr = ConfigWritableToString(configurationWritable);
WorkerConfigurationWritable configurationWritable2 =
WorkerConfigurationUtils.stringToWorkerConfiguration(configStr);
assertNotNull(configurationWritable);
assertEquals("testId1", configurationWritable2.getTaskExecutorId());
assertEquals(999, configurationWritable2.getHeartbeatInternalInMs());
assertEquals(998, configurationWritable2.getMesosSlavePort());
assertNull(configurationWritable2.getUsageSupplier());
}
}
| 8,355 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/Point.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import lombok.Value;
@Value
public class Point {
private double x;
private double y;
}
| 8,356 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/TestHadoopFileSystemBlobStore.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.net.URI;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import org.mockito.Matchers;
public class TestHadoopFileSystemBlobStore {
@Test
public void test() throws Exception {
FileSystem fileSystem = mock(FileSystem.class);
File localStoreDir = new File("/mnt/data/mantis-artifacts");
HadoopFileSystemBlobStore blobStore =
new HadoopFileSystemBlobStore(fileSystem, localStoreDir);
URI src =
new URI(
"s3://netflix.s3.genpop.prod/mantis/jobs/sananthanarayanan-mantis-jobs-sine-function-thin-0.1.0.zip");
URI dst =
new URI(
"/mnt/data/mantis-artifacts/sananthanarayanan-mantis-jobs-sine-function-thin-0.1.0.zip");
blobStore.get(src);
verify(fileSystem, times(1)).copyToLocalFile(Matchers.eq(new Path(src)),
Matchers.eq(new Path(dst)));
}
}
| 8,357 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/SineFunctionJobProvider.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.runtime.Context;
import io.mantisrx.runtime.Job;
import io.mantisrx.runtime.MantisJob;
import io.mantisrx.runtime.MantisJobProvider;
import io.mantisrx.runtime.Metadata;
import io.mantisrx.runtime.ScalarToScalar;
import io.mantisrx.runtime.codec.JacksonCodecs;
import io.mantisrx.runtime.computation.ScalarComputation;
import io.mantisrx.runtime.parameter.type.BooleanParameter;
import io.mantisrx.runtime.parameter.type.DoubleParameter;
import io.mantisrx.runtime.parameter.type.IntParameter;
import io.mantisrx.runtime.parameter.validator.Validators;
import io.mantisrx.runtime.sink.SelfDocumentingSink;
import io.mantisrx.runtime.sink.ServerSentEventsSink;
import io.mantisrx.runtime.sink.predicate.Predicate;
import io.mantisrx.runtime.source.Index;
import io.mantisrx.runtime.source.Source;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class SineFunctionJobProvider extends MantisJobProvider<Point> {
public static final String INTERVAL_MSEC = "intervalMSec";
public static final String RANGE_MAX = "max";
public static final String RANGE_MIN = "min";
public static final String AMPLITUDE = "amplitude";
public static final String FREQUENCY = "frequency";
public static final String PHASE = "phase";
public static final String RANDOM_RATE = "randomRate";
public static final String USE_RANDOM_FLAG = "useRandom";
private final SelfDocumentingSink<Point> sseSink = new ServerSentEventsSink.Builder<Point>()
.withEncoder(point -> String.format("{\"x\": %f, \"y\": %f}", point.getX(), point.getY()))
.withPredicate(new Predicate<>(
"filter=even, returns even x parameters; filter=odd, returns odd x parameters.",
parameters -> {
Func1<Point, Boolean> filter = point -> {
return true;
};
if (parameters != null && parameters.containsKey("filter")) {
String filterBy = parameters.get("filter").get(0);
// create filter function based on parameter value
filter = point -> {
// filter by evens or odds for x values
if ("even".equalsIgnoreCase(filterBy)) {
return (point.getX() % 2 == 0);
} else if ("odd".equalsIgnoreCase(filterBy)) {
return (point.getX() % 2 != 0);
}
return true; // if not even/odd
};
}
return filter;
}
))
.build();
public Job<Point> getJobInstance() {
return MantisJob
// Define the data source for this job.
.source(new TimerSource())
// Add stages to transform the event stream received from the Source.
.stage(new SinePointGeneratorStage(), stageConfig())
// Define a sink to output the transformed stream over SSE or an external system like Cassandra, etc.
.sink(sseSink)
// Add Job parameters that can be passed in by the user when submitting a job.
.parameterDefinition(new BooleanParameter()
.name(USE_RANDOM_FLAG)
.defaultValue(false)
.description("If true, produce a random sequence of integers. If false,"
+ " produce a sequence of integers starting at 0 and increasing by 1.")
.build())
.parameterDefinition(new DoubleParameter()
.name(RANDOM_RATE)
.defaultValue(1.0)
.description("The chance a random integer is generated, for the given period")
.validator(Validators.range(0, 1))
.build())
.parameterDefinition(new IntParameter()
.name(INTERVAL_MSEC)
.defaultValue(1)
.description("Period at which to generate a random integer value to send to sine function")
.validator(Validators.range(1, 60))
.build())
.parameterDefinition(new IntParameter()
.name(RANGE_MIN)
.defaultValue(0)
.description("Minimun of random integer value")
.validator(Validators.range(0, 100))
.build())
.parameterDefinition(new IntParameter()
.name(RANGE_MAX)
.defaultValue(100)
.description("Maximum of random integer value")
.validator(Validators.range(1, 100))
.build())
.parameterDefinition(new DoubleParameter()
.name(AMPLITUDE)
.defaultValue(10.0)
.description("Amplitude for sine function")
.validator(Validators.range(1, 100))
.build())
.parameterDefinition(new DoubleParameter()
.name(FREQUENCY)
.defaultValue(1.0)
.description("Frequency for sine function")
.validator(Validators.range(1, 100))
.build())
.parameterDefinition(new DoubleParameter()
.name(PHASE)
.defaultValue(0.0)
.description("Phase for sine function")
.validator(Validators.range(0, 100))
.build())
.metadata(new Metadata.Builder()
.name("Sine function")
.description("Produces an infinite stream of points, along the sine function, using the"
+ " following function definition: f(x) = amplitude * sin(frequency * x + phase)."
+ " The input to the function is either random between [min, max], or an integer sequence starting "
+ " at 0. The output is served via HTTP server using SSE protocol.")
.build())
.create();
}
/**
* This source generates a monotonically increasingly value per tick as per INTERVAL_SEC Job parameter.
* If USE_RANDOM_FLAG is set, the source generates a random value per tick.
*/
class TimerSource implements Source<Integer> {
private Subscription totalNumWorkersSubscription;
@Override
public Observable<Observable<Integer>> call(Context context, Index index) {
// If you want to be informed of scaleup/scale down of the source stage of this job you can subscribe
// to getTotalNumWorkersObservable like the following.
totalNumWorkersSubscription =
index
.getTotalNumWorkersObservable()
.subscribeOn(Schedulers.io()).subscribe((workerCount) -> {
System.out.println("Total worker count changed to -> " + workerCount);
});
final int period = (int)
context.getParameters().get(INTERVAL_MSEC);
final int max = (int)
context.getParameters().get(RANGE_MAX);
final int min = (int)
context.getParameters().get(RANGE_MIN);
final double randomRate = (double)
context.getParameters().get(RANDOM_RATE);
final boolean useRandom = (boolean)
context.getParameters().get(USE_RANDOM_FLAG);
final Random randomNumGenerator = new Random();
final Random randomRateVariable = new Random();
return Observable.just(
Observable.interval(0, period, TimeUnit.MILLISECONDS)
.map(time -> {
if (useRandom) {
return randomNumGenerator.nextInt((max - min) + 1) + min;
} else {
return (int) (long) time;
}
})
.filter(x -> {
double value = randomRateVariable.nextDouble();
return (value <= randomRate);
})
);
}
@Override
public void close() throws IOException {
}
}
class SinePointGeneratorStage implements ScalarComputation<Integer, Point> {
@Override
public Observable<Point> call(Context context, Observable<Integer> o) {
final double amplitude = (double)
context.getParameters().get(AMPLITUDE);
final double frequency = (double)
context.getParameters().get(FREQUENCY);
final double phase = (double)
context.getParameters().get(PHASE);
return
o
.filter(x -> x % 2 == 0)
.map(x -> new Point(x, amplitude * Math.sin((frequency * x) + phase)));
}
}
ScalarToScalar.Config<Integer, Point> stageConfig() {
return new ScalarToScalar.Config<Integer, Point>()
.codec(JacksonCodecs.pojo(Point.class));
}
}
| 8,358 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/BlobStoreTest.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.net.URI;
import org.junit.Test;
import org.mockito.Matchers;
public class BlobStoreTest {
@Test
public void testPrefixedBlobStore() throws Exception {
final BlobStore blobStore = mock(BlobStore.class);
final File file = mock(File.class);
when(blobStore.get(any())).thenReturn(file);
final BlobStore prefixedBlobStpre =
new BlobStore.PrefixedBlobStore(new URI("s3://mantisrx.s3.store/mantis/jobs/"), blobStore);
prefixedBlobStpre.get(new URI("http://sananthanarayanan-mantis-jobs-sine-function-thin-0.1.0.zip"));
final URI expectedUri =
new URI("s3://mantisrx.s3.store/mantis/jobs/sananthanarayanan-mantis-jobs-sine-function-thin-0.1.0.zip");
verify(blobStore, times(1)).get(Matchers.eq(expectedUri));
prefixedBlobStpre.get(new URI(
"https://mantisrx.region.prod.io.net/mantis-artifacts/sananthanarayanan-mantis-jobs-sine-function-thin-0.1.0.zip"));
verify(blobStore, times(2)).get(Matchers.eq(expectedUri));
}
}
| 8,359 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/RuntimeTaskImplExecutorTest.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.spotify.futures.CompletableFutures;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import io.mantisrx.common.Ack;
import io.mantisrx.common.JsonSerializer;
import io.mantisrx.common.WorkerPorts;
import io.mantisrx.runtime.MachineDefinition;
import io.mantisrx.runtime.MantisJobDurationType;
import io.mantisrx.runtime.MantisJobState;
import io.mantisrx.runtime.descriptor.SchedulingInfo;
import io.mantisrx.runtime.loader.ClassLoaderHandle;
import io.mantisrx.runtime.loader.RuntimeTask;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.runtime.source.http.HttpServerProvider;
import io.mantisrx.runtime.source.http.HttpSources;
import io.mantisrx.runtime.source.http.impl.HttpClientFactories;
import io.mantisrx.runtime.source.http.impl.HttpRequestFactories;
import io.mantisrx.server.agent.TaskExecutor.Listener;
import io.mantisrx.server.core.ExecuteStageRequest;
import io.mantisrx.server.core.JobSchedulingInfo;
import io.mantisrx.server.core.PostJobStatusRequest;
import io.mantisrx.server.core.Status;
import io.mantisrx.server.core.TestingRpcService;
import io.mantisrx.server.core.WorkerAssignments;
import io.mantisrx.server.core.WorkerHost;
import io.mantisrx.server.core.domain.WorkerId;
import io.mantisrx.server.master.client.HighAvailabilityServices;
import io.mantisrx.server.master.client.MantisMasterGateway;
import io.mantisrx.server.master.client.ResourceLeaderConnection;
import io.mantisrx.server.master.resourcecluster.RequestThrottledException;
import io.mantisrx.server.master.resourcecluster.ResourceClusterGateway;
import io.mantisrx.server.master.resourcecluster.TaskExecutorReport;
import io.mantisrx.server.master.resourcecluster.TaskExecutorStatusChange;
import io.mantisrx.server.worker.config.StaticPropertiesConfigurationFactory;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.com.google.common.base.Preconditions;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.collect.Lists;
import io.mantisrx.shaded.com.google.common.util.concurrent.MoreExecutors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import mantis.io.reactivex.netty.client.RxClient.ServerInfo;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.rpc.RpcService;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import rx.Observable;
import rx.Subscription;
@Slf4j
public class RuntimeTaskImplExecutorTest {
private WorkerConfiguration workerConfiguration;
private RpcService rpcService;
private MantisMasterGateway masterClientApi;
private HighAvailabilityServices highAvailabilityServices;
private HttpServer localApiServer;
private ClassLoaderHandle classLoaderHandle;
private TaskExecutor taskExecutor;
private CountDownLatch startedSignal;
private CountDownLatch doneSignal;
private CountDownLatch terminatedSignal;
private Status finalStatus;
private ResourceClusterGateway resourceManagerGateway;
private SimpleResourceLeaderConnection<ResourceClusterGateway> resourceManagerGatewayCxn;
private final ObjectMapper objectMapper = new ObjectMapper();
private CollectingTaskLifecycleListener listener;
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setUp() throws IOException {
final Properties props = new Properties();
props.setProperty("mantis.zookeeper.root", "");
props.setProperty("mantis.taskexecutor.cluster.storage-dir", "");
props.setProperty("mantis.taskexecutor.registration.store", tempFolder.newFolder().getAbsolutePath());
props.setProperty("mantis.taskexecutor.cluster-id", "default");
props.setProperty("mantis.taskexecutor.heartbeats.interval", "100");
props.setProperty("mantis.taskexecutor.metrics.collector", "io.mantisrx.server.agent.DummyMetricsCollector");
props.setProperty("mantis.taskexecutor.registration.retry.initial-delay.ms", "10");
props.setProperty("mantis.taskexecutor.registration.retry.mutliplier", "1");
props.setProperty("mantis.taskexecutor.registration.retry.randomization-factor", "0.5");
props.setProperty("mantis.taskexecutor.heartbeats.retry.initial-delay.ms", "100");
props.setProperty("mantis.taskexecutor.heartbeats.retry.max-delay.ms", "500");
props.setProperty("mantis.localmode", "true");
props.setProperty("mantis.zookeeper.connectString", "localhost:8100");
startedSignal = new CountDownLatch(1);
doneSignal = new CountDownLatch(1);
terminatedSignal = new CountDownLatch(1);
workerConfiguration = new StaticPropertiesConfigurationFactory(props).getConfig();
rpcService = new TestingRpcService();
masterClientApi = mock(MantisMasterGateway.class);
classLoaderHandle = ClassLoaderHandle.fixed(getClass().getClassLoader());
resourceManagerGateway = getHealthyGateway("gateway1");
resourceManagerGatewayCxn = new SimpleResourceLeaderConnection<>(resourceManagerGateway);
// worker and task executor do not share the same HA instance.
highAvailabilityServices = mock(HighAvailabilityServices.class);
when(highAvailabilityServices.getMasterClientApi()).thenReturn(masterClientApi);
when(highAvailabilityServices.connectWithResourceManager(any())).thenReturn(resourceManagerGatewayCxn);
when(highAvailabilityServices.startAsync()).thenReturn(highAvailabilityServices);
setupLocalControl(8100);
}
private void start() throws Exception {
listener = new CollectingTaskLifecycleListener();
taskExecutor =
new TestingTaskExecutor(
rpcService,
workerConfiguration,
highAvailabilityServices,
classLoaderHandle
);
taskExecutor.addListener(listener, MoreExecutors.directExecutor());
taskExecutor.start();
taskExecutor.awaitRunning().get(2, TimeUnit.SECONDS);
}
@After
public void tearDown() throws Exception {
taskExecutor.close();
this.localApiServer.stop(0);
}
@Ignore
@Test
public void testTaskExecutorEndToEndWithASingleStageJobByLoadingFromClassLoader()
throws Exception {
start();
List<Integer> ports = ImmutableList.of(100);
double threshold = 5000.0;
WorkerHost host = new WorkerHost("host0", 0, ports, MantisJobState.Started, 1, 8080, 8081);
Map<Integer, WorkerAssignments> stageAssignmentMap =
ImmutableMap.<Integer, WorkerAssignments>builder()
.put(1, new WorkerAssignments(1, 1,
ImmutableMap.<Integer, WorkerHost>builder().put(0, host).build()))
.build();
when(masterClientApi.schedulingChanges("jobId-0")).thenReturn(
Observable.just(new JobSchedulingInfo("jobId-0", stageAssignmentMap)));
WorkerId workerId = new WorkerId("jobId-0", 0, 1);
CompletableFuture<Ack> wait = taskExecutor.callInMainThread(() -> taskExecutor.submitTask(
new ExecuteStageRequest("jobName", "jobId-0", 0, 1,
new URL("https://www.google.com/"),
1, 1,
ports, 100L, 1, ImmutableList.of(),
new SchedulingInfo.Builder().numberOfStages(1)
.singleWorkerStageWithConstraints(new MachineDefinition(1, 10, 10, 10, 2),
Lists.newArrayList(), Lists.newArrayList()).build(),
MantisJobDurationType.Transient,
0,
1000L,
1L,
new WorkerPorts(2, 3, 4, 5, 6),
Optional.of(SineFunctionJobProvider.class.getName()),
"user")), Time.seconds(1));
wait.get();
Assert.assertTrue(startedSignal.await(5, TimeUnit.SECONDS));
Subscription subscription = HttpSources.source(HttpClientFactories.sseClientFactory(),
HttpRequestFactories.createGetFactory("/"))
.withServerProvider(new HttpServerProvider() {
@Override
public Observable<ServerInfo> getServersToAdd() {
return Observable.just(new ServerInfo("localhost", ports.get(0)));
}
@Override
public Observable<ServerInfo> getServersToRemove() {
return Observable.empty();
}
})
.build()
.call(null, null)
.flatMap(obs -> obs)
.flatMap(sse -> {
try {
return Observable.just(objectMapper.readValue(sse.contentAsString(), Point.class));
} catch (Exception e) {
log.error("failed to deserialize", e);
return Observable.error(e);
}
})
.takeUntil(point -> point.getX() > threshold)
.subscribe(point -> log.info("point={}", point), error -> log.error("failed", error),
() -> doneSignal.countDown());
Assert.assertTrue(doneSignal.await(10, TimeUnit.SECONDS));
subscription.unsubscribe();
verify(resourceManagerGateway, times(1)).notifyTaskExecutorStatusChange(
new TaskExecutorStatusChange(taskExecutor.getTaskExecutorID(), taskExecutor.getClusterID(),
TaskExecutorReport.occupied(workerId)));
CompletableFuture<Ack> cancelFuture =
taskExecutor.callInMainThread(() -> taskExecutor.cancelTask(workerId), Time.seconds(1));
cancelFuture.get();
Thread.sleep(5000);
verify(resourceManagerGateway, times(1)).notifyTaskExecutorStatusChange(
new TaskExecutorStatusChange(taskExecutor.getTaskExecutorID(), taskExecutor.getClusterID(),
TaskExecutorReport.available()));
assertTrue(listener.isStartingCalled());
assertTrue(listener.isCancellingCalled());
assertTrue(listener.isCancelledCalled());
assertFalse(listener.isFailedCalled());
}
private void setupLocalControl(int port) throws IOException {
this.localApiServer = HttpServer.create(new InetSocketAddress("localhost", port), 0);
this.localApiServer.createContext(
"/",
new HttpHandler() {
private JsonSerializer jsonSerializer = new JsonSerializer();
@Override
public void handle(HttpExchange exchange) throws IOException {
if ("GET".equals(exchange.getRequestMethod())) {
log.warn("unexpect get request: {}", exchange.getRequestURI());
} else if ("POST".equals(exchange.getRequestMethod())) {
InputStreamReader isr = new InputStreamReader(exchange.getRequestBody());
BufferedReader br = new BufferedReader(isr);
String value = br.readLine();
log.info("post body: {}", value);
PostJobStatusRequest statusReq =
jsonSerializer.fromJSON(value, PostJobStatusRequest.class);
log.info("Job signal: {}", statusReq.getStatus());
if (statusReq.getStatus().getState() == MantisJobState.Started) {
log.info("Job start signal received");
startedSignal.countDown();
}
if (statusReq.getStatus().getState().isTerminalState()) {
log.info("Job terminate signal received");
terminatedSignal.countDown();
}
}
OutputStream outputStream = exchange.getResponseBody();
String payload = "";
exchange.sendResponseHeaders(200, payload.length());
outputStream.write(payload.getBytes());
outputStream.flush();
outputStream.close();
}
});
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
this.localApiServer.setExecutor(threadPoolExecutor);
this.localApiServer.start();
log.info("Local API Server started on port: {}", port);
}
@Test
public void testWhenSuccessiveHeartbeatsFail() throws Exception {
ResourceClusterGateway resourceManagerGateway = mock(ResourceClusterGateway.class, "gateway2");
when(resourceManagerGateway.registerTaskExecutor(any())).thenReturn(
CompletableFuture.completedFuture(null));
when(resourceManagerGateway.heartBeatFromTaskExecutor(any()))
.thenReturn(CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error1")))
.thenReturn(CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error2")))
.thenReturn(CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error3")))
.thenReturn(CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error4")))
.thenReturn(CompletableFuture.completedFuture(null));
when(resourceManagerGateway.disconnectTaskExecutor(any())).thenReturn(
CompletableFuture.completedFuture(null));
resourceManagerGatewayCxn.newLeaderIs(resourceManagerGateway);
start();
Thread.sleep(1000);
verify(resourceManagerGateway, times(1)).registerTaskExecutor(any());
Assert.assertTrue(taskExecutor.isRegistered(Time.seconds(1)).get());
}
@Test
public void testWhenResourceManagerLeaderChanges() throws Exception {
start();
// wait for a second
Thread.sleep(1000);
// change the leader
ResourceClusterGateway newResourceClusterGateway = getHealthyGateway("gateway 2");
resourceManagerGatewayCxn.newLeaderIs(newResourceClusterGateway);
// wait for a second for new connections
Thread.sleep(1000);
// check if the switch has been made
verify(resourceManagerGateway, times(1)).registerTaskExecutor(any());
verify(resourceManagerGateway, atLeastOnce()).heartBeatFromTaskExecutor(any());
verify(newResourceClusterGateway, atLeastOnce()).heartBeatFromTaskExecutor(any());
// check if the task executor is registered
Assert.assertTrue(taskExecutor.isRegistered(Time.seconds(1)).get());
}
@Test
public void testWhenReregistrationFails() throws Exception {
start();
// wait for a second
Thread.sleep(1000);
// change the leader
ResourceClusterGateway newResourceManagerGateway1 = getUnhealthyGateway("gateway 2");
resourceManagerGatewayCxn.newLeaderIs(newResourceManagerGateway1);
// wait for a second for new connections
Thread.sleep(1000);
// check if the switch has been made
verify(resourceManagerGateway, times(1)).registerTaskExecutor(any());
verify(resourceManagerGateway, atLeastOnce()).heartBeatFromTaskExecutor(any());
verify(newResourceManagerGateway1, atLeastOnce()).heartBeatFromTaskExecutor(any());
ResourceClusterGateway newResourceManagerGateway2 = getHealthyGateway("gateway 3");
resourceManagerGatewayCxn.newLeaderIs(newResourceManagerGateway2);
Thread.sleep(1000);
verify(newResourceManagerGateway2, never()).disconnectTaskExecutor(any());
verify(newResourceManagerGateway2, atLeastOnce()).heartBeatFromTaskExecutor(any());
// check if the task executor is registered
Assert.assertTrue(taskExecutor.isRegistered(Time.seconds(1)).get());
}
private static ResourceClusterGateway getHealthyGateway(String name) {
ResourceClusterGateway gateway = mock(ResourceClusterGateway.class, name);
when(gateway.registerTaskExecutor(any())).thenReturn(CompletableFuture.completedFuture(Ack.getInstance()));
when(gateway.heartBeatFromTaskExecutor(any())).thenReturn(
CompletableFuture.completedFuture(Ack.getInstance()));
when(gateway.notifyTaskExecutorStatusChange(any()))
.thenReturn(CompletableFuture.completedFuture(Ack.getInstance()));
when(gateway.disconnectTaskExecutor(any()))
.thenReturn(CompletableFuture.completedFuture(Ack.getInstance()));
return gateway;
}
private static ResourceClusterGateway getUnhealthyGateway(String name) throws RequestThrottledException {
ResourceClusterGateway gateway = mock(ResourceClusterGateway.class);
when(gateway.registerTaskExecutor(any())).thenReturn(
CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error")));
when(gateway.disconnectTaskExecutor(any())).thenReturn(
CompletableFutures.exceptionallyCompletedFuture(new UnknownError("error")));
when(gateway.toString()).thenReturn(name);
return gateway;
}
public static class SimpleResourceLeaderConnection<ResourceT> implements
ResourceLeaderConnection<ResourceT> {
private final AtomicReference<ResourceT> current;
private final AtomicReference<ResourceLeaderChangeListener<ResourceT>> listener = new AtomicReference<>();
public SimpleResourceLeaderConnection(ResourceT initial) {
this.current = new AtomicReference<>(initial);
}
@Override
public ResourceT getCurrent() {
return current.get();
}
@Override
public void register(ResourceLeaderChangeListener<ResourceT> changeListener) {
Preconditions.checkArgument(listener.compareAndSet(null, changeListener),
"changeListener already set");
}
public void newLeaderIs(ResourceT newLeader) {
ResourceT old = current.getAndSet(newLeader);
if (listener.get() != null) {
listener.get().onResourceLeaderChanged(old, newLeader);
}
}
}
private static class TestingTaskExecutor extends TaskExecutor {
public TestingTaskExecutor(RpcService rpcService,
WorkerConfiguration workerConfiguration,
HighAvailabilityServices highAvailabilityServices,
ClassLoaderHandle classLoaderHandle) {
super(rpcService, workerConfiguration, highAvailabilityServices, classLoaderHandle);
}
}
@Getter
private static class CollectingTaskLifecycleListener implements Listener {
boolean startingCalled = false;
boolean failedCalled = false;
boolean cancellingCalled = false;
boolean cancelledCalled = false;
@Override
public void onTaskStarting(RuntimeTask task) {
startingCalled = true;
}
@Override
public void onTaskFailed(RuntimeTask task, Throwable throwable) {
failedCalled = true;
}
@Override
public void onTaskCancelling(RuntimeTask task) {
cancellingCalled = true;
}
@Override
public void onTaskCancelled(RuntimeTask task, @Nullable Throwable throwable) {
cancelledCalled = true;
}
}
}
| 8,360 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/DummyMetricsCollector.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.runtime.loader.config.MetricsCollector;
import io.mantisrx.runtime.loader.config.Usage;
import java.io.IOException;
import java.util.Properties;
@SuppressWarnings("unused")
public class DummyMetricsCollector implements MetricsCollector {
@SuppressWarnings("unused")
public static DummyMetricsCollector valueOf(Properties properties) {
return new DummyMetricsCollector();
}
@Override
public Usage get() throws IOException {
return Usage.builder()
.cpusLimit(1)
.cpusSystemTimeSecs(100.)
.cpusUserTimeSecs(100.)
.networkWriteBytes(100.)
.networkReadBytes(100.)
.memAnonBytes(100.)
.memLimit(200.)
.memRssBytes(200.)
.build();
}
}
| 8,361 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/ResourceManagerGatewayCxnTest.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import static org.apache.flink.util.ExceptionUtils.stripExecutionException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.mantisrx.common.utils.Services;
import com.spotify.futures.CompletableFutures;
import io.mantisrx.common.WorkerPorts;
import io.mantisrx.runtime.MachineDefinition;
import io.mantisrx.server.agent.utils.DurableBooleanState;
import io.mantisrx.server.master.resourcecluster.ClusterID;
import io.mantisrx.server.master.resourcecluster.ResourceClusterGateway;
import io.mantisrx.server.master.resourcecluster.TaskExecutorDisconnection;
import io.mantisrx.server.master.resourcecluster.TaskExecutorHeartbeat;
import io.mantisrx.server.master.resourcecluster.TaskExecutorID;
import io.mantisrx.server.master.resourcecluster.TaskExecutorRegistration;
import io.mantisrx.server.master.resourcecluster.TaskExecutorReport;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.util.concurrent.Service.State;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.time.Time;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@Slf4j
public class ResourceManagerGatewayCxnTest {
private TaskExecutorRegistration registration;
private TaskExecutorDisconnection disconnection;
private TaskExecutorHeartbeat heartbeat;
private ResourceClusterGateway gateway;
private ResourceManagerGatewayCxn cxn;
private TaskExecutorReport report;
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void setup() throws IOException {
WorkerPorts workerPorts = new WorkerPorts(100, 101, 102, 103, 104);
TaskExecutorID taskExecutorID = TaskExecutorID.of("taskExecutor");
ClusterID clusterID = ClusterID.of("cluster");
registration =
TaskExecutorRegistration.builder()
.taskExecutorID(taskExecutorID)
.clusterID(clusterID)
.hostname("host")
.taskExecutorAddress("localhost")
.workerPorts(workerPorts)
.machineDefinition(new MachineDefinition(1, 1, 1, 1, 5))
.taskExecutorAttributes(ImmutableMap.of())
.build();
disconnection = new TaskExecutorDisconnection(taskExecutorID, clusterID);
gateway = mock(ResourceClusterGateway.class);
report = TaskExecutorReport.available();
heartbeat = new TaskExecutorHeartbeat(taskExecutorID, clusterID, report);
TaskExecutor taskExecutor = mock(TaskExecutor.class);
when(taskExecutor.getCurrentReport()).thenReturn(CompletableFuture.completedFuture(report));
cxn = new ResourceManagerGatewayCxn(0, registration, gateway, Time.milliseconds(100),
Time.milliseconds(100), taskExecutor, 3, 200,
1000, 50, 2, 0.5, 3, new DurableBooleanState(tempFolder.newFile().getAbsolutePath()));
}
@Test
public void testIfTaskExecutorRegistersItselfWithResourceManagerAndSendsHeartbeatsPeriodically()
throws Exception {
when(gateway.registerTaskExecutor(Matchers.eq(registration))).thenReturn(
CompletableFuture.completedFuture(null));
when(gateway.disconnectTaskExecutor(Matchers.eq(disconnection))).thenReturn(
CompletableFuture.completedFuture(null));
when(gateway.heartBeatFromTaskExecutor(Matchers.eq(heartbeat)))
.thenReturn(CompletableFuture.completedFuture(null));
cxn.startAsync().awaitRunning();
Thread.sleep(1000);
cxn.stopAsync().awaitTerminated();
verify(gateway, times(1)).disconnectTaskExecutor(disconnection);
verify(gateway, atLeastOnce()).heartBeatFromTaskExecutor(heartbeat);
}
@Test
public void testWhenRegistrationFailsIntermittently() throws Throwable {
when(gateway.heartBeatFromTaskExecutor(Matchers.eq(heartbeat)))
.thenReturn(CompletableFuture.completedFuture(null));
when(gateway.disconnectTaskExecutor(Matchers.eq(disconnection))).thenReturn(
CompletableFuture.completedFuture(null));
when(gateway.registerTaskExecutor(Matchers.eq(registration)))
.thenAnswer(new Answer<CompletableFuture<Void>>() {
private int count = 0;
@Override
public CompletableFuture<Void> answer(InvocationOnMock invocation) {
count++;
if (count % 2 == 0) {
return CompletableFuture.completedFuture(null);
} else {
return CompletableFutures.exceptionallyCompletedFuture(
new UnknownError("exception"));
}
}
});
cxn.startAsync().awaitRunning();
Thread.sleep(1000);
assertEquals(cxn.state(), State.RUNNING);
cxn.stopAsync().awaitTerminated();
}
@Test(expected = RuntimeException.class)
public void testWhenRegistrationFailsContinuously() throws Throwable {
when(gateway.heartBeatFromTaskExecutor(Matchers.eq(heartbeat)))
.thenReturn(CompletableFuture.completedFuture(null));
when(gateway.disconnectTaskExecutor(Matchers.eq(disconnection))).thenReturn(
CompletableFuture.completedFuture(null));
when(gateway.registerTaskExecutor(Matchers.eq(registration)))
.thenAnswer(new Answer<CompletableFuture<Void>>() {
private int count = 0;
@Override
public CompletableFuture<Void> answer(InvocationOnMock invocation) {
count++;
if (count >= 5) {
return CompletableFuture.completedFuture(null);
} else {
return CompletableFutures.exceptionallyCompletedFuture(
new UnknownError("exception"));
}
}
});
cxn.startAsync();
CompletableFuture<Void> result = Services.awaitAsync(cxn,
Executors.newSingleThreadExecutor());
try {
result.get();
} catch (Exception e) {
throw stripExecutionException(e);
}
}
@Test
public void testWhenHeartbeatFailsIntermittently() throws Exception {
when(gateway.registerTaskExecutor(Matchers.eq(registration))).thenReturn(
CompletableFuture.completedFuture(null));
when(gateway.heartBeatFromTaskExecutor(Matchers.eq(heartbeat)))
.thenAnswer(new Answer<CompletableFuture<Void>>() {
private int count = 0;
@Override
public CompletableFuture<Void> answer(InvocationOnMock invocation) {
count++;
if (count % 2 == 0) {
return CompletableFuture.completedFuture(null);
} else {
return CompletableFutures.exceptionallyCompletedFuture(
new Exception("error"));
}
}
});
cxn.startAsync();
Thread.sleep(1000);
assertEquals(cxn.state(), State.RUNNING);
assertTrue(cxn.isRegistered());
}
@Test
public void testWhenHeartbeatFailsContinuously() throws Exception {
when(gateway.registerTaskExecutor(Matchers.eq(registration))).thenReturn(
CompletableFuture.completedFuture(null));
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch isNotRegisteredSignal = new CountDownLatch(5);
when(gateway.heartBeatFromTaskExecutor(Matchers.eq(heartbeat)))
.thenAnswer(new Answer<CompletableFuture<Void>>() {
private int count = 0;
@Override
public CompletableFuture<Void> answer(InvocationOnMock invocation) {
count++;
startSignal.countDown();
isNotRegisteredSignal.countDown();
log.info("isNotRegistered {}", isNotRegisteredSignal.getCount());
log.info("count: {}", count);
return CompletableFutures.exceptionallyCompletedFuture(
new UnknownError("error"));
}
});
when(gateway.disconnectTaskExecutor(Matchers.eq(disconnection))).thenReturn(
CompletableFuture.completedFuture(null));
cxn.startAsync();
// wait for the heart beat failure
startSignal.await();
assertTrue(cxn.isRegistered());
// wait for the third heartbeat failure
isNotRegisteredSignal.await();
assertFalse(cxn.isRegistered());
Services.stopAsync(cxn, Executors.newSingleThreadExecutor()).join();
verify(gateway, times(1)).disconnectTaskExecutor(disconnection);
Assert.assertFalse(cxn.isRegistered());
}
}
| 8,362 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics/cgroups/TestNetworkSubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import static org.junit.Assert.assertEquals;
import io.mantisrx.runtime.loader.config.Usage;
import io.mantisrx.shaded.com.google.common.io.Resources;
import org.junit.Test;
public class TestNetworkSubsystemProcess {
@Test
public void testValidPath() throws Exception {
String path = Resources.getResource("example1/network/dev").getPath();
NetworkSubsystemProcess process = new NetworkSubsystemProcess(path, "eth0:");
final Usage.UsageBuilder usageBuilder = Usage.builder();
process.getUsage(usageBuilder);
final Usage usage = usageBuilder.build();
assertEquals(2861321009430L, (long) usage.getNetworkReadBytes());
assertEquals(2731791728959L, (long) usage.getNetworkWriteBytes());
}
}
| 8,363 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics/cgroups/TestCgroup.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.io.Resources;
import java.io.IOException;
import org.junit.Test;
public class TestCgroup {
private final Cgroup cgroup =
new CgroupImpl(Resources.getResource("example1").getPath());
@Test
public void testReadingStatFiles() throws IOException {
assertEquals(
ImmutableMap.of("user", 49692738L, "system", 4700825L),
cgroup.getStats("cpuacct", "cpuacct.stat"));
assertTrue(cgroup.isV1());
}
@Test
public void testReadingMetrics() throws IOException {
assertEquals(
400000L,
cgroup.getMetric("cpuacct", "cpu.cfs_quota_us").longValue()
);
}
@Test
public void testLongOverflow() throws IOException {
assertEquals(
Long.MAX_VALUE,
cgroup.getMetric("testlongoverflow", "verylongvalue").longValue()
);
}
}
| 8,364 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics/cgroups/TestMemorySubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import io.mantisrx.runtime.loader.config.Usage;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.io.Resources;
import java.io.IOException;
import org.junit.Test;
public class TestMemorySubsystemProcess {
private final Cgroup cgroup = mock(Cgroup.class);
private final MemorySubsystemProcess process = new MemorySubsystemProcess(cgroup);
@Test
public void testHappyPath() throws Exception {
when(cgroup.isV1()).thenReturn(true);
when(cgroup.getMetric("memory", "memory.limit_in_bytes"))
.thenReturn(17179869184L);
when(cgroup.getStats("memory", "memory.stat"))
.thenReturn(
ImmutableMap.<String, Long>builder()
.put("cache", 233472L)
.put("rss", 38641664L)
.put("rss_huge", 0L)
.put("shmem", 110592L)
.put("mapped_file", 0L)
.put("dirty", 0L)
.put("writeback", 0L)
.put("swap", 0L)
.put("pgpgin", 18329978L)
.put("pgpgout", 18320487L)
.put("pgfault", 20573333L)
.put("pgmajfault", 0L)
.put("inactive_anon", 36065280L)
.put("active_anon", 65536L)
.put("inactive_file", 2715648L)
.put("active_file", 28672L)
.put("unevictable", 0L)
.put("hierarchical_memory_limit", 17179869184L)
.put("hierarchical_memsw_limit", 34359738368L)
.put("total_cache", 1014173696L)
.put("total_rss", 14828109824L)
.put("total_rss_huge", 0L)
.put("total_shmem", 2998272L)
.put("total_mapped_file", 72470528L)
.put("total_dirty", 217088L)
.put("total_writeback", 0L)
.put("total_swap", 0L)
.put("total_pgpgin", 519970432L)
.put("total_pgpgout", 516102687L)
.put("total_pgfault", 1741668505L)
.put("total_pgmajfault", 34L)
.put("total_inactive_anon", 14828208128L)
.put("total_active_anon", 278528L)
.put("total_inactive_file", 972009472L)
.put("total_active_file", 41783296L)
.put("total_unevictable", 0L)
.build());
final Usage.UsageBuilder usageBuilder = Usage.builder();
process.getUsage(usageBuilder);
final Usage usage = usageBuilder.build();
assertEquals(17179869184L, (long) usage.getMemLimit());
assertEquals(14828109824L, (long) usage.getMemRssBytes());
assertEquals(14828109824L, (long) usage.getMemAnonBytes());
}
@Test
public void testCgroupv2() throws IOException {
final Cgroup cgroupv2 =
new CgroupImpl(Resources.getResource("example2").getPath());
final MemorySubsystemProcess process = new MemorySubsystemProcess(cgroupv2);
final Usage.UsageBuilder usageBuilder = Usage.builder();
process.getUsage(usageBuilder);
final Usage usage = usageBuilder.build();
assertEquals(2147483648L, (long) usage.getMemLimit());
assertEquals(1693843456L, (long) usage.getMemRssBytes());
assertEquals(945483776L, (long) usage.getMemAnonBytes());
}
}
| 8,365 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/metrics/cgroups/TestCpuAcctsSubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import io.mantisrx.runtime.loader.config.Usage;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.io.Resources;
import java.io.IOException;
import org.junit.Test;
public class TestCpuAcctsSubsystemProcess {
@Test
public void testWhenCgroupsReturnsCorrectData() throws Exception {
final Cgroup cgroup = mock(Cgroup.class);
final CpuAcctsSubsystemProcess process = new CpuAcctsSubsystemProcess(cgroup);
when(cgroup.isV1()).thenReturn(true);
when(cgroup.getStats("cpuacct", "cpuacct.stat"))
.thenReturn(ImmutableMap.<String, Long>of("user", 43873627L, "system", 4185541L));
when(cgroup.getStats("cpuacct", "cpuacct.stat"))
.thenReturn(ImmutableMap.<String, Long>of("user", 43873627L, "system", 4185541L));
when(cgroup.getMetric("cpuacct", "cpu.cfs_quota_us"))
.thenReturn(400000L);
when(cgroup.getMetric("cpuacct", "cpu.cfs_period_us"))
.thenReturn(100000L);
final Usage.UsageBuilder usageBuilder = Usage.builder();
process.getUsage(usageBuilder);
final Usage usage = usageBuilder.build();
assertEquals(4L, (long) usage.getCpusLimit());
assertEquals(438736L, (long) usage.getCpusUserTimeSecs());
assertEquals(41855L, (long) usage.getCpusSystemTimeSecs());
}
@Test
public void testCgroupsV2() throws IOException {
final Cgroup cgroupv2 =
new CgroupImpl(Resources.getResource("example2").getPath());
assertFalse(cgroupv2.isV1());
final CpuAcctsSubsystemProcess process = new CpuAcctsSubsystemProcess(cgroupv2);
final Usage.UsageBuilder usageBuilder = Usage.builder();
process.getUsage(usageBuilder);
final Usage usage = usageBuilder.build();
assertEquals(2L, (long) usage.getCpusLimit());
assertEquals(4231L, (long) usage.getCpusUserTimeSecs());
assertEquals(1277L, (long) usage.getCpusSystemTimeSecs());
}
}
| 8,366 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent | Create_ds/mantis/mantis-server/mantis-server-agent/src/test/java/io/mantisrx/server/agent/utils/DurableBooleanStateTest.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.utils;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class DurableBooleanStateTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void testFunctionality() throws Exception {
File tempFile = tempFolder.newFile("myTempFile.txt");
String absolutePath = tempFile.getAbsolutePath();
DurableBooleanState durableBooleanState = new DurableBooleanState(absolutePath);
assertFalse(durableBooleanState.getState());
durableBooleanState.setState(true);
boolean state = durableBooleanState.getState();
assertTrue(state);
durableBooleanState.setState(false);
assertFalse(durableBooleanState.getState());
durableBooleanState.setState(true);
assertTrue(durableBooleanState.getState());
DurableBooleanState anotherBooleanState = new DurableBooleanState(absolutePath);
assertTrue(anotherBooleanState.getState());
}
}
| 8,367 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/BlobStoreAwareClassLoaderHandle.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import com.mantisrx.common.utils.Closeables;
import io.mantisrx.runtime.loader.ClassLoaderHandle;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.WeakHashMap;
import java.util.function.Consumer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.flink.util.FlinkUserCodeClassLoader;
import org.apache.flink.util.SimpleUserCodeClassLoader;
import org.apache.flink.util.UserCodeClassLoader;
/**
* ClassLoader that gets created out of downloading blobs from the corresponding blob store.
*/
@Slf4j
@RequiredArgsConstructor
public class BlobStoreAwareClassLoaderHandle implements ClassLoaderHandle {
private final BlobStore blobStore;
private final WeakHashMap<URLClassLoader, Void> openedHandles = new WeakHashMap<>();
protected List<URL> getResolvedUrls(Collection<URI> requiredFiles, BlobStore blobStore)
throws IOException, URISyntaxException {
final List<URL> resolvedUrls = new ArrayList<>();
for (URI requiredFile : requiredFiles) {
// get a local version of the file that needs to be added to the classloader
final File file = blobStore.get(requiredFile);
log.info("Received file {} from blob store for creating class loader", file);
if (file.isDirectory()) {
// let's recursively add all jar files under this directory
final Collection<File> childJarFiles =
FileUtils.listFiles(file, new SuffixFileFilter("jar", IOCase.INSENSITIVE),
TrueFileFilter.INSTANCE);
log.info("Loading files {} into the class loader", childJarFiles);
for (File jarFile : childJarFiles) {
resolvedUrls.add(jarFile.toURI().toURL());
}
} else {
// let's assume that this is actually a jar file
resolvedUrls.add(file.toURI().toURL());
}
}
return resolvedUrls;
}
@Override
public UserCodeClassLoader getOrResolveClassLoader(Collection<URI> requiredFiles,
Collection<URL> requiredClasspaths) throws IOException {
final List<URL> resolvedUrls = new ArrayList<>();
try {
resolvedUrls.addAll(getResolvedUrls(requiredFiles, blobStore));
} catch (URISyntaxException e) {
throw new IOException(e);
}
resolvedUrls.addAll(requiredClasspaths);
final ParentFirstClassLoader classLoader = new ParentFirstClassLoader(resolvedUrls.toArray(new URL[0]), getClass().getClassLoader(),
error -> log.error("Failed to load class", error));
synchronized (openedHandles) {
openedHandles.put(classLoader, null);
}
return SimpleUserCodeClassLoader.create(classLoader);
}
@Override
public void cacheJobArtifacts(Collection<URI> artifacts) {
try {
getResolvedUrls(artifacts, blobStore);
} catch (IOException | URISyntaxException e) {
log.warn("Failed to download artifacts: {}", artifacts);
}
}
public static class ParentFirstClassLoader extends FlinkUserCodeClassLoader {
ParentFirstClassLoader(
URL[] urls, ClassLoader parent, Consumer<Throwable> classLoadingExceptionHandler) {
super(urls, parent, classLoadingExceptionHandler);
}
static {
ClassLoader.registerAsParallelCapable();
}
}
@Override
public void close() throws IOException {
synchronized (openedHandles) {
try {
Closeables.combine(openedHandles.keySet()).close();
} finally {
openedHandles.clear();
blobStore.close();
}
}
}
}
| 8,368 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/HadoopFileSystemBlobStore.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/**
* Blob store that uses the hadoop-filesystem base library to retrieve the requested resources.
* Hadoop FileSystem is a good abstraction as it can deal with a variety of cloud-native object stores
* such as s3, gfs, etc...
*/
@RequiredArgsConstructor
@Slf4j
public class HadoopFileSystemBlobStore implements BlobStore {
// The file system in which blobs are stored. */
private final FileSystem fileSystem;
private final File localStoreDir;
@Override
public File get(URI blobUrl) throws IOException {
final Path src = new Path(blobUrl);
final Path dest = new Path(getStorageLocation(blobUrl));
log.info("Getting file with path {}", dest);
File destFile = new File(dest.toUri().getPath());
if (!destFile.exists()) {
fileSystem.copyToLocalFile(src, dest);
}
return destFile;
}
@Override
public void close() throws IOException {
FileUtils.deleteDirectory(localStoreDir);
fileSystem.close();
}
private String getStorageLocation(URI blobUri) {
return String.format("%s/%s", localStoreDir, FilenameUtils.getName(blobUri.getPath()));
}
}
| 8,369 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/MantisAgent.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.server.core.Service;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MantisAgent implements Service {
private static final Logger logger = LoggerFactory.getLogger(MantisAgent.class);
private CountDownLatch blockUntilShutdown = new CountDownLatch(1);
public MantisAgent() {
Thread t = new Thread() {
@Override
public void run() {
shutdown();
}
};
t.setDaemon(true);
// shutdown hook
Runtime.getRuntime().addShutdownHook(t);
}
public static void main(String[] args) {
MantisAgent agent = new MantisAgent();
agent.start(); // block until shutdown hook (ctrl-c)
}
@Override
public void start() {
logger.info("Starting Mantis Agent");
try {
blockUntilShutdown.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public void shutdown() {
logger.info("Shutting down Mantis Agent");
blockUntilShutdown.countDown();
}
@Override
public void enterActiveMode() {}
}
| 8,370 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/SingleTaskOnlyFactory.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.runtime.loader.RuntimeTask;
import io.mantisrx.runtime.loader.TaskFactory;
import io.mantisrx.server.core.ExecuteStageRequest;
import java.util.ServiceLoader;
import lombok.extern.slf4j.Slf4j;
/**
* This factory is used when there is only 1 RuntimeTask implementation.
*/
@Slf4j
public class SingleTaskOnlyFactory implements TaskFactory {
@Override
public RuntimeTask getRuntimeTaskInstance(ExecuteStageRequest request, ClassLoader cl) {
ServiceLoader<RuntimeTask> loader = ServiceLoader.load(RuntimeTask.class, cl);
return loader.iterator().next();
}
}
| 8,371 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/AgentV2Main.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import com.sampullara.cli.Args;
import com.sampullara.cli.Argument;
import io.mantisrx.common.properties.DefaultMantisPropertiesLoader;
import io.mantisrx.common.properties.MantisPropertiesLoader;
import io.mantisrx.runtime.loader.RuntimeTask;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.server.agent.config.ConfigurationFactory;
import io.mantisrx.server.agent.config.StaticPropertiesConfigurationFactory;
import io.mantisrx.server.core.Service;
import io.mantisrx.shaded.com.google.common.util.concurrent.MoreExecutors;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AgentV2Main implements Service {
private static final Logger logger = LoggerFactory.getLogger(AgentV2Main.class);
@Argument(alias = "p", description = "Specify a configuration file", required = false)
private static String propFile = "agent.properties";
private final TaskExecutorStarter taskExecutorStarter;
private final AtomicBoolean stopping = new AtomicBoolean(false);
public AgentV2Main(ConfigurationFactory configFactory, MantisPropertiesLoader propertiesLoader) throws Exception {
WorkerConfiguration workerConfiguration = configFactory.getConfig();
this.taskExecutorStarter =
TaskExecutorStarter.builder(workerConfiguration)
.taskFactory(new SingleTaskOnlyFactory())
.propertiesLoader(propertiesLoader)
.addListener(
new TaskExecutor.Listener() {
@Override
public void onTaskStarting(RuntimeTask task) {}
@Override
public void onTaskFailed(RuntimeTask task, Throwable throwable) {
// Something failed, at this point we could log it and perform cleanup actions.
// For now we will just exit.
logger.error("Task {} failed", task, throwable);
if (!isStopping()) {
System.exit(1);
}
}
@Override
public void onTaskCancelling(RuntimeTask task) {}
@Override
public void onTaskCancelled(RuntimeTask task, @Nullable Throwable throwable) {
// Task got cancelled, at this point we could log it and perform cleanup
// actions.
// For now we will just exit.
if (throwable != null) {
logger.error("Task {} cancellation failed", task, throwable);
}
if (!isStopping()) {
System.exit(1);
}
}
},
MoreExecutors.directExecutor())
.build();
}
private boolean isStopping() {
return stopping.get();
}
public static void main(String[] args) {
try {
Args.parse(AgentV2Main.class, args);
} catch (IllegalArgumentException e) {
Args.usage(AgentV2Main.class);
System.exit(1);
}
try {
Properties props = new Properties();
props.putAll(System.getenv());
props.putAll(System.getProperties());
props.putAll(loadProperties(propFile));
StaticPropertiesConfigurationFactory factory = new StaticPropertiesConfigurationFactory(props);
DefaultMantisPropertiesLoader propertiesLoader = new DefaultMantisPropertiesLoader(props);
AgentV2Main agent = new AgentV2Main(factory, propertiesLoader);
agent.start(); // blocks until shutdown hook (ctrl-c)
} catch (Exception e) {
// unexpected to get a RuntimeException, will exit
logger.error("Unexpected error: " + e.getMessage(), e);
System.exit(2);
}
}
private static Properties loadProperties(String propFile) {
// config
Properties props = new Properties();
try (InputStream in = findResourceAsStream(propFile)) {
props.load(in);
} catch (IOException e) {
throw new RuntimeException(String.format("Can't load properties from the given property file %s: %s", propFile, e.getMessage()), e);
}
return props;
}
/**
* Finds the given resource and returns its input stream. This method seeks the file first from the current working directory,
* and then in the class path.
*
* @param resourceName the name of the resource. It can either be a file name, or a path.
*
* @return An {@link java.io.InputStream} instance that represents the found resource. Null otherwise.
*
* @throws FileNotFoundException
*/
private static InputStream findResourceAsStream(String resourceName) throws FileNotFoundException {
File resource = new File(resourceName);
if (resource.exists()) {
return new FileInputStream(resource);
}
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
if (is == null) {
throw new FileNotFoundException(String.format("Can't find property file %s. Make sure the property file is either in your path or in your classpath ", resourceName));
}
return is;
}
@Override
public void start() {
Runtime.getRuntime()
.addShutdownHook(
new Thread(() -> shutdown()));
try {
taskExecutorStarter.startAsync().awaitRunning(2, TimeUnit.MINUTES);
taskExecutorStarter.awaitTerminated();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void shutdown() {
stopping.set(true);
try {
logger.info("Received signal to shutdown; shutting down task executor");
taskExecutorStarter.stopAsync().awaitTerminated(2, TimeUnit.MINUTES);
} catch (Throwable e) {
logger.error("Failed to stop gracefully", e);
}
}
@Override
public void enterActiveMode() {
}
}
| 8,372 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/TaskExecutor.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import com.mantisrx.common.utils.ListenerCallQueue;
import com.mantisrx.common.utils.Services;
import com.spotify.futures.CompletableFutures;
import io.mantisrx.common.Ack;
import io.mantisrx.common.JsonSerializer;
import io.mantisrx.common.WorkerPorts;
import io.mantisrx.common.metrics.netty.MantisNettyEventsListenerFactory;
import io.mantisrx.common.properties.DefaultMantisPropertiesLoader;
import io.mantisrx.common.properties.MantisPropertiesLoader;
import io.mantisrx.runtime.MachineDefinition;
import io.mantisrx.runtime.MantisJobState;
import io.mantisrx.runtime.loader.ClassLoaderHandle;
import io.mantisrx.runtime.loader.RuntimeTask;
import io.mantisrx.runtime.loader.TaskFactory;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.runtime.loader.config.WorkerConfigurationUtils;
import io.mantisrx.server.agent.utils.DurableBooleanState;
import io.mantisrx.server.core.CacheJobArtifactsRequest;
import io.mantisrx.server.core.ExecuteStageRequest;
import io.mantisrx.server.core.Status;
import io.mantisrx.server.core.WrappedExecuteStageRequest;
import io.mantisrx.server.core.domain.WorkerId;
import io.mantisrx.server.master.client.HighAvailabilityServices;
import io.mantisrx.server.master.client.MantisMasterGateway;
import io.mantisrx.server.master.client.ResourceLeaderConnection;
import io.mantisrx.server.master.client.TaskStatusUpdateHandler;
import io.mantisrx.server.master.resourcecluster.ClusterID;
import io.mantisrx.server.master.resourcecluster.ResourceClusterGateway;
import io.mantisrx.server.master.resourcecluster.TaskExecutorID;
import io.mantisrx.server.master.resourcecluster.TaskExecutorRegistration;
import io.mantisrx.server.master.resourcecluster.TaskExecutorReport;
import io.mantisrx.server.master.resourcecluster.TaskExecutorStatusChange;
import io.mantisrx.server.worker.TaskExecutorGateway;
import io.mantisrx.shaded.com.google.common.base.Preconditions;
import io.mantisrx.shaded.com.google.common.collect.ImmutableMap;
import io.mantisrx.shaded.com.google.common.util.concurrent.Service;
import io.mantisrx.shaded.com.google.common.util.concurrent.Service.State;
import io.mantisrx.shaded.org.apache.curator.shaded.com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import mantis.io.reactivex.netty.RxNetty;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.rpc.RpcEndpoint;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcServiceUtils;
import org.apache.flink.util.UserCodeClassLoader;
import org.apache.flink.util.concurrent.ExecutorThreadFactory;
import rx.Subscription;
import rx.subjects.PublishSubject;
/**
* TaskExecutor implements the task executor gateway which provides capabilities to
* 1). start a stage task from the mantis master
* 2). cancel a stage task from the mantis master
* 3). take a thread dump to see which threads are active
*/
@Slf4j
public class TaskExecutor extends RpcEndpoint implements TaskExecutorGateway {
public static final Time DEFAULT_TIMEOUT = Time.seconds(5);
@Getter
private final TaskExecutorID taskExecutorID;
@Getter
private final ClusterID clusterID;
private final WorkerConfiguration workerConfiguration;
private final MantisPropertiesLoader dynamicPropertiesLoader;
private final HighAvailabilityServices highAvailabilityServices;
private final ClassLoaderHandle classLoaderHandle;
private final TaskExecutorRegistration taskExecutorRegistration;
private final CompletableFuture<Void> startFuture = new CompletableFuture<>();
private final ExecutorService ioExecutor;
private final ExecutorService runtimeTaskExecutor;
private final ListenerCallQueue<Listener> listeners = new ListenerCallQueue<>();
// the reason the MantisMasterGateway field is not final is because we expect the HighAvailabilityServices
// to be started before we can get the MantisMasterGateway
private MantisMasterGateway masterMonitor;
private ResourceLeaderConnection<ResourceClusterGateway> resourceClusterGatewaySupplier;
private TaskStatusUpdateHandler taskStatusUpdateHandler;
// represents the current connection to the resource manager.
private ResourceManagerGatewayCxn currentResourceManagerCxn;
private TaskExecutorReport currentReport;
private Subscription currentTaskStatusSubscription;
private int resourceManagerCxnIdx;
private Throwable previousFailure;
private final TaskFactory taskFactory;
private RuntimeTask currentTask;
private ExecuteStageRequest currentRequest;
private final DurableBooleanState registeredState;
@VisibleForTesting
public TaskExecutor(
RpcService rpcService,
WorkerConfiguration workerConfiguration,
HighAvailabilityServices highAvailabilityServices,
ClassLoaderHandle classLoaderHandle) {
this(rpcService,
workerConfiguration,
new DefaultMantisPropertiesLoader(System.getProperties()),
highAvailabilityServices,
classLoaderHandle,
null);
}
public TaskExecutor(
RpcService rpcService,
WorkerConfiguration workerConfiguration,
MantisPropertiesLoader propertiesLoader,
HighAvailabilityServices highAvailabilityServices,
ClassLoaderHandle classLoaderHandle,
@Nullable TaskFactory taskFactory) {
super(rpcService, RpcServiceUtils.createRandomName("worker"));
// this is the task executor ID that will be used for the rest of the JVM process
this.taskExecutorID =
Optional.ofNullable(workerConfiguration.getTaskExecutorId())
.map(TaskExecutorID::of)
.orElseGet(TaskExecutorID::generate);
this.clusterID = ClusterID.of(workerConfiguration.getClusterId());
this.workerConfiguration = workerConfiguration;
this.dynamicPropertiesLoader = propertiesLoader;
this.highAvailabilityServices = highAvailabilityServices;
this.classLoaderHandle = classLoaderHandle;
WorkerPorts workerPorts = new WorkerPorts(workerConfiguration.getMetricsPort(),
workerConfiguration.getDebugPort(), workerConfiguration.getConsolePort(),
workerConfiguration.getCustomPort(),
workerConfiguration.getSinkPort());
MachineDefinition machineDefinition =
MachineDefinitionUtils.sys(workerPorts, workerConfiguration.getNetworkBandwidthInMB());
String hostName = workerConfiguration.getExternalAddress();
this.taskExecutorRegistration =
TaskExecutorRegistration.builder()
.machineDefinition(machineDefinition)
.taskExecutorID(taskExecutorID)
.clusterID(clusterID)
.hostname(hostName)
.taskExecutorAddress(getAddress())
.workerPorts(workerPorts)
.taskExecutorAttributes(ImmutableMap.copyOf(
workerConfiguration
.getTaskExecutorAttributes()
.entrySet()
.stream()
.collect(Collectors.<Map.Entry<String, String>, String, String>toMap(
kv -> kv.getKey().toLowerCase(),
kv -> kv.getValue().toLowerCase()))))
.build();
log.info("Starting executor registration: {}", this.taskExecutorRegistration);
this.ioExecutor =
Executors.newCachedThreadPool(
new ExecutorThreadFactory("taskexecutor-io"));
this.runtimeTaskExecutor =
Executors.newCachedThreadPool(
new ExecutorThreadFactory("taskexecutor-runtime"));
this.resourceManagerCxnIdx = 0;
this.taskFactory = taskFactory == null ? new SingleTaskOnlyFactory() : taskFactory;
this.registeredState = new DurableBooleanState(
new File(workerConfiguration.getRegistrationStoreDir(),
"rmCxnState.txt").getAbsolutePath());
}
@Override
protected void onStart() {
try {
startTaskExecutorServices();
startFuture.complete(null);
} catch (Throwable throwable) {
log.error("Fatal error occurred in starting TaskExecutor {}", getAddress(), throwable);
startFuture.completeExceptionally(throwable);
throw throwable;
}
}
private void startTaskExecutorServices() {
validateRunsInMainThread();
masterMonitor = highAvailabilityServices.getMasterClientApi();
taskStatusUpdateHandler = TaskStatusUpdateHandler.forReportingToGateway(masterMonitor);
RxNetty.useMetricListenersFactory(new MantisNettyEventsListenerFactory());
resourceClusterGatewaySupplier =
highAvailabilityServices.connectWithResourceManager(clusterID);
resourceClusterGatewaySupplier.register((oldGateway, newGateway) -> TaskExecutor.this.runAsync(() -> setNewResourceClusterGateway(newGateway)));
establishNewResourceManagerCxnSync();
}
public CompletableFuture<Void> awaitRunning() {
return startFuture;
}
private void setNewResourceClusterGateway(ResourceClusterGateway gateway) {
// check if we are running on the main thread first
validateRunsInMainThread();
Preconditions.checkArgument(
this.currentResourceManagerCxn != null,
String.format("resource manager connection does not exist %s",
this.currentResourceManagerCxn));
log.info("Setting new resource cluster gateway {}", gateway);
this.currentResourceManagerCxn.setGateway(gateway);
}
private void establishNewResourceManagerCxnSync() {
// check if we are running on the main thread first
validateRunsInMainThread();
Preconditions.checkArgument(
this.currentResourceManagerCxn == null,
String.format("resource manager connection already exists %s",
this.currentResourceManagerCxn));
ResourceManagerGatewayCxn cxn = newResourceManagerCxn();
setResourceManagerCxn(cxn);
cxn.startAsync().awaitRunning();
}
private CompletableFuture<Void> establishNewResourceManagerCxnAsync() {
// check if we are running on the main thread first
validateRunsInMainThread();
if (this.currentResourceManagerCxn != null) {
return CompletableFutures.exceptionallyCompletedFuture(
new Exception(String.format("resource manager connection already exists %s",
this.currentResourceManagerCxn)));
}
ResourceManagerGatewayCxn cxn = newResourceManagerCxn();
setResourceManagerCxn(cxn);
return Services.startAsync(cxn, getIOExecutor()).handleAsync((dontCare, throwable) -> {
if (throwable != null) {
log.error("Failed to create a connection; Retrying", throwable);
// let's first verify if the cxn that failed to start is still the current cxn
if (this.currentResourceManagerCxn == cxn) {
this.currentResourceManagerCxn = null;
scheduleRunAsync(this::establishNewResourceManagerCxnAsync,
workerConfiguration.heartbeatInternalInMs(), TimeUnit.MILLISECONDS);
}
// since we have handled this issue, we don't need to propagate it further.
return null;
} else {
return dontCare;
}
}, getMainThreadExecutor());
}
private void setResourceManagerCxn(ResourceManagerGatewayCxn cxn) {
// check if we are running on the main thread first since we are operating on
// shared mutable state
validateRunsInMainThread();
Preconditions.checkArgument(this.currentResourceManagerCxn == null,
"existing connection already set");
cxn.addListener(new Service.Listener() {
@Override
public void failed(Service.State from, Throwable failure) {
if (from.ordinal() == Service.State.RUNNING.ordinal()) {
log.error("Connection with the resource manager failed; Retrying", failure);
clearResourceManagerCxn();
scheduleRunAsync(TaskExecutor.this::establishNewResourceManagerCxnAsync,
workerConfiguration.getHeartbeatInterval());
}
}
}, getMainThreadExecutor());
this.currentResourceManagerCxn = cxn;
}
private void clearResourceManagerCxn() {
validateRunsInMainThread();
TaskExecutor.this.currentResourceManagerCxn = null;
}
private ResourceManagerGatewayCxn newResourceManagerCxn() {
validateRunsInMainThread();
ResourceClusterGateway resourceManagerGateway = resourceClusterGatewaySupplier.getCurrent();
// let's register ourselves with the resource manager
// todo: move timeout/retry to apply values from this.dynamicPropertiesLoader
return new ResourceManagerGatewayCxn(
resourceManagerCxnIdx++,
taskExecutorRegistration,
resourceManagerGateway,
workerConfiguration.getHeartbeatInterval(),
workerConfiguration.getHeartbeatTimeout(),
this,
workerConfiguration.getTolerableConsecutiveHeartbeatFailures(),
workerConfiguration.heartbeatRetryInitialDelayMs(),
workerConfiguration.heartbeatRetryMaxDelayMs(),
workerConfiguration.registrationRetryInitialDelayMillis(),
workerConfiguration.registrationRetryMultiplier(),
workerConfiguration.registrationRetryRandomizationFactor(),
workerConfiguration.registrationRetryMaxAttempts(),
registeredState);
}
private ExecutorService getIOExecutor() {
return this.ioExecutor;
}
private ExecutorService getRuntimeExecutor() {
return this.runtimeTaskExecutor;
}
CompletableFuture<TaskExecutorReport> getCurrentReport() {
return callAsync(() -> {
if (this.currentTask == null) {
return TaskExecutorReport.available();
} else {
return TaskExecutorReport.occupied(WorkerId.fromIdUnsafe(currentTask.getWorkerId()));
}
}, DEFAULT_TIMEOUT);
}
@VisibleForTesting
<T> CompletableFuture<T> callInMainThread(Callable<CompletableFuture<T>> tSupplier,
Time timeout) {
return this.callAsync(tSupplier, timeout).thenCompose(t -> t);
}
@Override
public CompletableFuture<Ack> submitTask(ExecuteStageRequest request) {
log.info("Received request {} for execution", request);
if (currentTask != null) {
if (currentTask.getWorkerId().equals(request.getWorkerId().getId())) {
return CompletableFuture.completedFuture(Ack.getInstance());
} else {
return CompletableFutures.exceptionallyCompletedFuture(
new TaskAlreadyRunningException(WorkerId.fromIdUnsafe(currentTask.getWorkerId())));
}
}
// todo(sundaram): rethink on how this needs to be handled better.
// The publishsubject is today used to communicate the failure to start the request in a timely fashion.
// Seems very convoluted.
WrappedExecuteStageRequest wrappedRequest =
new WrappedExecuteStageRequest(PublishSubject.create(), request);
// do not wait for task processing (e.g. artifact download).
getIOExecutor().execute(() -> this.prepareTask(wrappedRequest));
return CompletableFuture.completedFuture(Ack.getInstance());
}
@Override
public CompletableFuture<Ack> cacheJobArtifacts(CacheJobArtifactsRequest request) {
log.info("Received request {} for downloading artifact", request);
getIOExecutor().execute(() -> this.classLoaderHandle.cacheJobArtifacts(request.getArtifacts()));
return CompletableFuture.completedFuture(Ack.getInstance());
}
private void prepareTask(WrappedExecuteStageRequest wrappedRequest) {
try {
this.currentRequest = wrappedRequest.getRequest();
UserCodeClassLoader userCodeClassLoader = this.taskFactory.getUserCodeClassLoader(
wrappedRequest.getRequest(), classLoaderHandle);
ClassLoader cl = userCodeClassLoader.asClassLoader();
// There should only be 1 task implementation provided by mantis-server-worker.
JsonSerializer ser = new JsonSerializer();
String executeRequest = ser.toJson(wrappedRequest.getRequest());
String configString = ser.toJson(WorkerConfigurationUtils.toWritable(workerConfiguration));
RuntimeTask task = this.taskFactory.getRuntimeTaskInstance(wrappedRequest.getRequest(), cl);
task.initialize(
executeRequest,
configString,
userCodeClassLoader);
scheduleRunAsync(() -> {
setCurrentTask(task);
startCurrentTask();
}, 0, TimeUnit.MILLISECONDS);
} catch (Exception ex) {
log.error("Failed to submit task, request: {}", wrappedRequest.getRequest(), ex);
final Status failedStatus = new Status(currentRequest.getJobId(), currentRequest.getStage(), currentRequest.getWorkerIndex(), currentRequest.getWorkerNumber(),
Status.TYPE.INFO, "stage " + currentRequest.getStage() + " worker index=" + currentRequest.getWorkerIndex() + " number=" + currentRequest.getWorkerNumber() + " failed during initialization",
MantisJobState.Failed);
updateExecutionStatus(failedStatus);
listeners.enqueue(getTaskFailedEvent(null, ex));
}
finally {
getIOExecutor().execute(listeners::dispatch);
}
}
private void startCurrentTask() {
validateRunsInMainThread();
if (currentTask.state().equals(State.NEW)) {
listeners.enqueue(getTaskStartingEvent(currentTask));
getIOExecutor().execute(listeners::dispatch);
CompletableFuture<Void> currentTaskSuccessfullyStartFuture =
Services.startAsync(currentTask, getRuntimeExecutor());
currentTaskSuccessfullyStartFuture
.whenCompleteAsync((dontCare, throwable) -> {
if (throwable != null) {
// okay failed to start task successfully
// lets stop it
log.error("TaskExecutor failed to start: {}", throwable);
RuntimeTask task = currentTask;
setCurrentTask(null);
setPreviousFailure(throwable);
listeners.enqueue(getTaskFailedEvent(task, throwable));
getIOExecutor().execute(listeners::dispatch);
}
}, getMainThreadExecutor());
}
}
private void setCurrentTask(@Nullable RuntimeTask task) {
validateRunsInMainThread();
this.currentTask = task;
if (task == null) {
setStatus(TaskExecutorReport.available());
} else {
setStatus(TaskExecutorReport.occupied(WorkerId.fromIdUnsafe(task.getWorkerId())));
}
}
private void setPreviousFailure(Throwable throwable) {
validateRunsInMainThread();
this.previousFailure = throwable;
}
// tries to update the local state and the resource manager responsible for the task executor
// so that it's aware of the task executor state correctly.
// any failure to update the resource manager is not propagated upwards and instead is silently
// ignored with just an exception log. this is okay because the resource manager anyways gets periodic
// heartbeats which also contain the status of the task executor.
private void setStatus(TaskExecutorReport newReport) {
validateRunsInMainThread();
this.currentReport = newReport;
try {
Preconditions.checkState(currentResourceManagerCxn != null,
"currentResourceManagerCxn was not expected to be null");
currentResourceManagerCxn.getGateway().notifyTaskExecutorStatusChange(
new TaskExecutorStatusChange(taskExecutorID, clusterID, newReport))
.whenCompleteAsync((ack, throwable) -> {
if (throwable != null) {
log.warn("Failed to update the status {}", newReport, throwable);
}
}, getIOExecutor());
} catch (Exception e) {
log.warn("Failed to update the status {}", newReport, e);
}
}
@Override
public CompletableFuture<Ack> cancelTask(WorkerId workerId) {
log.info("TaskExecutor cancelTask requested for {}", workerId);
if (this.currentTask == null) {
return CompletableFutures.exceptionallyCompletedFuture(new TaskNotFoundException(workerId));
} else if (!this.currentTask.getWorkerId().equals(workerId.getId())) {
log.error("my current worker id is {} while expected worker id is {}", currentTask.getWorkerId(), workerId);
return CompletableFutures.exceptionallyCompletedFuture(new TaskNotFoundException(workerId));
} else {
scheduleRunAsync(this::stopCurrentTask, 0, TimeUnit.MILLISECONDS);
return CompletableFuture.completedFuture(Ack.getInstance());
}
}
private CompletableFuture<Void> stopCurrentTask() {
log.info("TaskExecutor stopCurrentTask.");
validateRunsInMainThread();
if (this.currentTask != null) {
try {
if (this.currentTask.state().ordinal() <= Service.State.RUNNING.ordinal()) {
listeners.enqueue(getTaskCancellingEvent(currentTask));
CompletableFuture<Void> stopTaskFuture =
Services.stopAsync(this.currentTask, getRuntimeExecutor());
return stopTaskFuture
.whenCompleteAsync((dontCare, throwable) -> {
RuntimeTask t = this.currentTask;
setCurrentTask(null);
if (throwable != null) {
setPreviousFailure(throwable);
}
listeners.enqueue(getTaskCancelledEvent(t, throwable));
getIOExecutor().execute(listeners::dispatch);
}, getMainThreadExecutor());
} else {
return CompletableFuture.completedFuture(null);
}
} catch (Exception e) {
log.error("stopping current task failed", e);
return CompletableFutures.exceptionallyCompletedFuture(e);
} finally {
getIOExecutor().execute(listeners::dispatch);
}
} else {
return CompletableFuture.completedFuture(null);
}
}
private CompletableFuture<Void> stopResourceManager() {
validateRunsInMainThread();
final CompletableFuture<Void> currentResourceManagerCxnCompletionFuture;
if (currentResourceManagerCxn != null) {
currentResourceManagerCxnCompletionFuture = Services.stopAsync(currentResourceManagerCxn,
getIOExecutor());
} else {
currentResourceManagerCxnCompletionFuture = CompletableFuture.completedFuture(null);
}
return currentResourceManagerCxnCompletionFuture;
}
@Override
public CompletableFuture<String> requestThreadDump() {
return CompletableFuture.completedFuture(JvmUtils.createThreadDumpAsString());
}
@Override
public CompletableFuture<Boolean> isRegistered() {
return callAsync(() -> this.currentResourceManagerCxn != null && this.currentResourceManagerCxn.isRegistered(), DEFAULT_TIMEOUT);
}
CompletableFuture<Boolean> isRegistered(Time timeout) {
return callAsync(() -> this.currentResourceManagerCxn != null, timeout);
}
protected void updateExecutionStatus(Status status) {
taskStatusUpdateHandler.onStatusUpdate(status);
}
@Override
protected CompletableFuture<Void> onStop() {
validateRunsInMainThread();
log.info("TaskExecutor onStop.");
final CompletableFuture<Void> runningTaskCompletionFuture = stopCurrentTask();
return runningTaskCompletionFuture
.handleAsync((dontCare, throwable) -> {
if (throwable != null) {
log.error("Failed to stop the task successfully", throwable);
}
return stopResourceManager();
}, getMainThreadExecutor())
.thenCompose(Function.identity())
.whenCompleteAsync((dontCare, throwable) -> {
try {
classLoaderHandle.close();
} catch (Exception e) {
log.error("Failed to close classloader handle correctly", e);
}
}, getIOExecutor());
}
public final void addListener(Listener listener, Executor executor) {
synchronized (listeners) {
listeners.addListener(listener, executor);
}
}
/**
* Listener interface that allows one to listen on various events happening in the TaskExecutor.
*
* Some of these events include:
* -> when a task has started to be executed by the TaskExecutor
* -> when a task has failed to be started
* -> when a task is currently being cancelled
* -> when a cancellation is complete
*/
public interface Listener {
void onTaskStarting(RuntimeTask task);
void onTaskFailed(RuntimeTask task, Throwable throwable);
void onTaskCancelling(RuntimeTask task);
void onTaskCancelled(RuntimeTask task, @Nullable Throwable throwable);
static Listener noop() {
return new Listener() {
@Override
public void onTaskStarting(RuntimeTask task) {
}
@Override
public void onTaskFailed(RuntimeTask task, Throwable throwable) {
}
@Override
public void onTaskCancelling(RuntimeTask task) {
}
@Override
public void onTaskCancelled(RuntimeTask task, @Nullable Throwable throwable) {
}
};
}
}
private static ListenerCallQueue.Event<Listener> getTaskStartingEvent(RuntimeTask task) {
return new ListenerCallQueue.Event<Listener>() {
@Override
public void call(Listener listener) {
listener.onTaskStarting(task);
}
@Override
public String toString() {
return "starting()";
}
};
}
private static ListenerCallQueue.Event<Listener> getTaskCancellingEvent(RuntimeTask task) {
return new ListenerCallQueue.Event<Listener>() {
@Override
public void call(Listener listener) {
listener.onTaskCancelling(task);
}
@Override
public String toString() {
return "cancelling()";
}
};
}
private static ListenerCallQueue.Event<Listener> getTaskFailedEvent(RuntimeTask task, Throwable throwable) {
return new ListenerCallQueue.Event<Listener>() {
@Override
public void call(Listener listener) {
listener.onTaskFailed(task, throwable);
}
@Override
public String toString() {
return "failed()";
}
};
}
private static ListenerCallQueue.Event<Listener> getTaskCancelledEvent(RuntimeTask task, @Nullable Throwable throwable) {
return new ListenerCallQueue.Event<Listener>() {
@Override
public void call(Listener listener) {
listener.onTaskCancelled(task, throwable);
}
@Override
public String toString() {
return "cancelled()";
}
};
}
}
| 8,373 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/FileSystemInitializer.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.fs.FileSystem;
@Slf4j
public class FileSystemInitializer {
private static final Map<String, FileSystemFactory> FS_FACTORIES = new HashMap<>();
static {
FileSystemInitializer.initialize();
}
/**
* initialize needs to be called at the start of the JVM.
*/
public static void initialize() {
FS_FACTORIES.clear();
// let's get all the registered implementations
Iterator<FileSystemFactory> fileSystemFactoryIterator =
ServiceLoader.load(FileSystemFactory.class).iterator();
fileSystemFactoryIterator.forEachRemaining(fileSystemFactory -> {
log.info("Initializing FileSystem Factory {}", fileSystemFactory);
FS_FACTORIES.putIfAbsent(fileSystemFactory.getScheme(), fileSystemFactory);
});
}
public static FileSystem create(URI fsUri) throws IOException {
FileSystemFactory factory = FS_FACTORIES.get(fsUri.getScheme());
if (factory != null) {
return factory.create(fsUri);
} else {
throw new IllegalArgumentException(
String.format("Unknown schema %s", fsUri.getScheme()));
}
}
}
| 8,374 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/BlobStore.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.shaded.com.google.common.util.concurrent.Striped;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.locks.Lock;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import net.lingala.zip4j.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
/**
* Abstraction to deal with getting files stored in object stores such as s3.
*/
public interface BlobStore extends Closeable {
File get(URI blobUrl) throws IOException;
/**
* blob store that adds a prefix to every requested URI.
*
* @param prefixUri prefix that needs to be prepended to every requested resource.
* @return blob store with the prefix patterns baked in.
*/
default BlobStore withPrefix(URI prefixUri) {
return new PrefixedBlobStore(prefixUri, this);
}
/**
* blob store that when downloading zip files, also unpacks them and returns the unpacked file/directory to the caller.
*
* @return blob store that can effectively deal with zip files
*/
default BlobStore withZipCapabilities() {
return new ZipHandlingBlobStore(this);
}
default BlobStore withThreadSafeBlobStore() {
return new ThreadSafeBlobStore(this);
}
static BlobStore forHadoopFileSystem(URI clusterStoragePath, File localStoreDir) throws Exception {
final org.apache.hadoop.fs.FileSystem fileSystem =
FileSystemInitializer.create(clusterStoragePath);
return
new HadoopFileSystemBlobStore(fileSystem, localStoreDir)
.withPrefix(clusterStoragePath)
.withZipCapabilities()
.withThreadSafeBlobStore();
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class PrefixedBlobStore implements BlobStore {
private final URI rootUri;
private final BlobStore blobStore;
@Override
public File get(URI blobUrl) throws IOException {
final String fileName = FilenameUtils.getName(blobUrl.toString());
return blobStore.get(rootUri.resolve(fileName));
}
@Override
public void close() throws IOException {
blobStore.close();
}
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class ZipHandlingBlobStore implements BlobStore {
private final BlobStore blobStore;
@Override
public File get(URI blobUrl) throws IOException {
final File localFile = blobStore.get(blobUrl);
final ZipFile zipFile = getZipFile(localFile);
if (zipFile == null) {
return localFile;
} else {
File destDir = null;
try (ZipFile z = zipFile) {
String destDirStr = getUnzippedDestDir(z);
destDir = new File(destDirStr);
if (destDir.exists()) {
return destDir;
}
z.extractAll(destDirStr);
return destDir;
} catch(Exception e) {
// delete directory before re-throwing exception to avoid possible data corruptions
if (destDir != null) {
FileUtils.deleteDirectory(destDir);
}
throw e;
}
}
}
@Override
public void close() throws IOException {
blobStore.close();
}
private String getUnzippedDestDir(ZipFile zipFile) {
return zipFile.getFile().getPath() + "-unzipped";
}
private ZipFile getZipFile(File file) {
ZipFile file1 = new ZipFile(file);
if (file1.isValidZipFile()) {
return file1;
} else {
return null;
}
}
}
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class ThreadSafeBlobStore implements BlobStore {
private final BlobStore blobStore;
final Striped<Lock> locks = Striped.lock(1024);
@Override
public File get(URI blobUrl) throws IOException {
Lock lock = locks.get(blobUrl.getPath());
lock.lock();
try {
return blobStore.get(blobUrl);
} finally {
lock.unlock();
}
}
@Override
public void close() throws IOException {
blobStore.close();
}
}
}
| 8,375 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/FileSystemFactory.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.fs.FileSystem;
public interface FileSystemFactory {
/** Gets the scheme of the file system created by this factory. */
String getScheme();
/**
* Creates a new file system for the given file system URI. The URI describes the type of file
* system (via its scheme) and optionally the authority (for example the host) of the file
* system.
*
* @param fsUri The URI that describes the file system.
* @return A new instance of the specified file system.
* @throws IOException Thrown if the file system could not be instantiated.
*/
FileSystem create(URI fsUri) throws IOException;
}
| 8,376 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/MachineDefinitionUtils.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.mantisrx.common.WorkerPorts;
import io.mantisrx.runtime.MachineDefinition;
public class MachineDefinitionUtils {
public static MachineDefinition sys(WorkerPorts workerPorts, double networkBandwidthInMB) {
return new MachineDefinition(
Hardware.getNumberCPUCores(),
Hardware.getSizeOfPhysicalMemory(),
networkBandwidthInMB,
Hardware.getSizeOfDisk(),
workerPorts.getNumberOfPorts());
}
}
| 8,377 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/JvmUtils.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Arrays;
import java.util.Collection;
/**
* Utilities for {@link java.lang.management.ManagementFactory}.
*/
public final class JvmUtils {
/**
* Creates a thread dump of the current JVM.
*
* @return the thread dump of current JVM
*/
public static Collection<ThreadInfo> createThreadDump() {
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
return Arrays.asList(threadMxBean.dumpAllThreads(true, true));
}
public static String createThreadDumpAsString() {
final StringBuilder dump = new StringBuilder();
final Collection<ThreadInfo> threadInfos = createThreadDump();
for (ThreadInfo threadInfo : threadInfos) {
dump.append('"');
dump.append(threadInfo.getThreadName());
dump.append("\" ");
final Thread.State state = threadInfo.getThreadState();
dump.append("\n java.lang.Thread.State: ");
dump.append(state);
final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
for (final StackTraceElement stackTraceElement : stackTraceElements) {
dump.append("\n at ");
dump.append(stackTraceElement);
}
dump.append("\n\n");
}
return dump.toString();
}
/**
* Private default constructor to avoid instantiation.
*/
private JvmUtils() {
}
}
| 8,378 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/TaskExecutorStarter.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import com.mantisrx.common.utils.Services;
import io.mantisrx.common.properties.MantisPropertiesLoader;
import io.mantisrx.runtime.loader.ClassLoaderHandle;
import io.mantisrx.runtime.loader.TaskFactory;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.server.core.MantisAkkaRpcSystemLoader;
import io.mantisrx.server.master.client.HighAvailabilityServices;
import io.mantisrx.server.master.client.HighAvailabilityServicesUtil;
import io.mantisrx.shaded.com.google.common.base.Preconditions;
import io.mantisrx.shaded.com.google.common.util.concurrent.AbstractIdleService;
import io.mantisrx.shaded.com.google.common.util.concurrent.MoreExecutors;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import javax.annotation.Nullable;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.runtime.rpc.RpcSystem;
import org.apache.flink.runtime.rpc.RpcUtils;
/**
* TaskExecutorStarter class represents the starting point for a task executor.
* Use the {@link TaskExecutorStarterBuilder} to build {@link TaskExecutorStarter}.
* Once the service is build, start and stop it during the lifecycle of your runtime framework such as spring.
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class TaskExecutorStarter extends AbstractIdleService {
private final TaskExecutor taskExecutor;
private final HighAvailabilityServices highAvailabilityServices;
private final RpcSystem rpcSystem;
@Override
protected void startUp() {
// RxJava 1.x’s rx.ring-buffer.size property stores the size of any in-memory ring buffers that RxJava
// uses when an Observable cannot keep up with rate of event emissions. The ring buffer size is explicitly
// set to a low number (8) because different platforms have different defaults for this value. While the
// Java Virtual Machine (JVM) default is 128 items per ring buffer, Android has a much lower limit of 16.
// 1024 is a well-tested value in Netflix on many production use cases.
// source: From https://www.uber.com/blog/rxjava-backpressure/
System.setProperty("rx.ring-buffer.size", "1024");
highAvailabilityServices.startAsync().awaitRunning();
taskExecutor.start();
try {
taskExecutor.awaitRunning().get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
protected void shutDown() throws Exception {
taskExecutor
.closeAsync()
.exceptionally(throwable -> null)
.thenCompose(dontCare -> Services.stopAsync(highAvailabilityServices,
MoreExecutors.directExecutor()))
.thenRunAsync(rpcSystem::close)
.get();
}
public TaskExecutor getTaskExecutor() {
return this.taskExecutor;
}
public static TaskExecutorStarterBuilder builder(WorkerConfiguration workerConfiguration) {
return new TaskExecutorStarterBuilder(workerConfiguration);
}
@SuppressWarnings("unused")
public static class TaskExecutorStarterBuilder {
private final WorkerConfiguration workerConfiguration;
private Configuration configuration;
private MantisPropertiesLoader propertiesLoader;
@Nullable
private RpcSystem rpcSystem;
@Nullable
private RpcService rpcService;
@Nullable
private ClassLoaderHandle classLoaderHandle;
private final HighAvailabilityServices highAvailabilityServices;
@Nullable
private TaskFactory taskFactory;
private final List<Tuple2<TaskExecutor.Listener, Executor>> listeners = new ArrayList<>();
private TaskExecutorStarterBuilder(WorkerConfiguration workerConfiguration) {
this.workerConfiguration = workerConfiguration;
this.configuration = new Configuration();
this.highAvailabilityServices = HighAvailabilityServicesUtil.createHAServices(workerConfiguration);
}
public TaskExecutorStarterBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
public TaskExecutorStarterBuilder rpcSystem(RpcSystem rpcSystem) {
Preconditions.checkNotNull(rpcSystem);
this.rpcSystem = rpcSystem;
return this;
}
private RpcSystem getRpcSystem() {
if (this.rpcSystem == null) {
return MantisAkkaRpcSystemLoader.getInstance();
} else {
return this.rpcSystem;
}
}
public TaskExecutorStarterBuilder rpcService(RpcService rpcService) {
Preconditions.checkNotNull(rpcService);
this.rpcService = rpcService;
return this;
}
private RpcService getRpcService() throws Exception {
if (this.rpcService == null) {
return RpcUtils.createRemoteRpcService(
getRpcSystem(),
configuration,
workerConfiguration.getExternalAddress(),
workerConfiguration.getExternalPortRange(),
workerConfiguration.getBindAddress(),
Optional.ofNullable(workerConfiguration.getBindPort()));
} else {
return this.rpcService;
}
}
public TaskExecutorStarterBuilder taskFactory(TaskFactory taskFactory) {
this.taskFactory = taskFactory;
return this;
}
public TaskExecutorStarterBuilder classLoaderHandle(ClassLoaderHandle classLoaderHandle) {
this.classLoaderHandle = classLoaderHandle;
return this;
}
private ClassLoaderHandle getClassLoaderHandle() throws Exception {
if (this.classLoaderHandle == null) {
return new BlobStoreAwareClassLoaderHandle(
BlobStore.forHadoopFileSystem(
workerConfiguration.getBlobStoreArtifactDir(),
workerConfiguration.getLocalStorageDir()));
} else {
return this.classLoaderHandle;
}
}
public TaskExecutorStarterBuilder addListener(TaskExecutor.Listener listener, Executor executor) {
this.listeners.add(Tuple.of(listener, executor));
return this;
}
public TaskExecutorStarterBuilder propertiesLoader(MantisPropertiesLoader propertiesLoader) {
this.propertiesLoader = propertiesLoader;
return this;
}
public TaskExecutorStarter build() throws Exception {
final TaskExecutor taskExecutor =
new TaskExecutor(
getRpcService(),
Preconditions.checkNotNull(workerConfiguration, "WorkerConfiguration for TaskExecutor is null"),
Preconditions.checkNotNull(propertiesLoader, "propertiesLoader for TaskExecutor is null"),
highAvailabilityServices,
getClassLoaderHandle(),
this.taskFactory);
for (Tuple2<TaskExecutor.Listener, Executor> listener : listeners) {
taskExecutor.addListener(listener._1(), listener._2());
}
return new TaskExecutorStarter(taskExecutor, highAvailabilityServices, getRpcSystem());
}
}
}
| 8,379 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/Hardware.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.flink.util.OperatingSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Convenience class to extract hardware specifics of the computer executing the running JVM.
* This particular class has been copy-pasted from flink
* {@see <a href="https://github.com/apache/flink/blob/master/flink-runtime/src/main/java/org/apache/flink/runtime/util/Hardware.java">flink hardware</a>}
*/
public class Hardware {
private static final Logger LOG = LoggerFactory.getLogger(Hardware.class);
private static final String LINUX_MEMORY_INFO_PATH = "/proc/meminfo";
private static final Pattern LINUX_MEMORY_REGEX =
Pattern.compile("^MemTotal:\\s*(\\d+)\\s+kB$");
// ------------------------------------------------------------------------
/**
* Gets the number of CPU cores (hardware contexts) that the JVM has access to.
*
* @return The number of CPU cores.
*/
public static int getNumberCPUCores() {
return Runtime.getRuntime().availableProcessors();
}
/**
* Returns the total size of the disk. Assumes that it's a UNIX style filesystem. Will not work
* in Windows.
*
* @return
*/
public static long getSizeOfDisk() {
try {
File file = new File("/");
return file.getTotalSpace();
} catch (Exception e) {
LOG.error("Failed to get size of the disk", e);
}
return -1;
}
/**
* Returns the size of the physical memory in bytes.
*
* @return the size of the physical memory in bytes or {@code -1}, if the size could not be
* determined.
*/
public static long getSizeOfPhysicalMemory() {
// first try if the JVM can directly tell us what the system memory is
// this works only on Oracle JVMs
try {
Class<?> clazz = Class.forName("com.sun.management.OperatingSystemMXBean");
Method method = clazz.getMethod("getTotalPhysicalMemorySize");
OperatingSystemMXBean operatingSystemMXBean =
ManagementFactory.getOperatingSystemMXBean();
// someone may install different beans, so we need to check whether the bean
// is in fact the sun management bean
if (clazz.isInstance(operatingSystemMXBean)) {
return (Long) method.invoke(operatingSystemMXBean);
}
} catch (ClassNotFoundException e) {
// this happens on non-Oracle JVMs, do nothing and use the alternative code paths
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
LOG.warn(
"Access to physical memory size: "
+ "com.sun.management.OperatingSystemMXBean incompatibly changed.",
e);
}
// we now try the OS specific access paths
switch (OperatingSystem.getCurrentOperatingSystem()) {
case LINUX:
return getSizeOfPhysicalMemoryForLinux();
case WINDOWS:
return getSizeOfPhysicalMemoryForWindows();
case MAC_OS:
return getSizeOfPhysicalMemoryForMac();
case FREE_BSD:
return getSizeOfPhysicalMemoryForFreeBSD();
case UNKNOWN:
LOG.error("Cannot determine size of physical memory for unknown operating system");
return -1;
default:
LOG.error("Unrecognized OS: " + OperatingSystem.getCurrentOperatingSystem());
return -1;
}
}
/**
* Returns the size of the physical memory in bytes on a Linux-based operating system.
*
* @return the size of the physical memory in bytes or {@code -1}, if the size could not be
* determined
*/
private static long getSizeOfPhysicalMemoryForLinux() {
try (BufferedReader lineReader =
new BufferedReader(new FileReader(LINUX_MEMORY_INFO_PATH))) {
String line;
while ((line = lineReader.readLine()) != null) {
Matcher matcher = LINUX_MEMORY_REGEX.matcher(line);
if (matcher.matches()) {
String totalMemory = matcher.group(1);
return Long.parseLong(totalMemory) * 1024L; // Convert from kilobyte to byte
}
}
// expected line did not come
LOG.error(
"Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). "
+ "Unexpected format.");
return -1;
} catch (NumberFormatException e) {
LOG.error(
"Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo'). "
+ "Unexpected format.");
return -1;
} catch (Throwable t) {
LOG.error(
"Cannot determine the size of the physical memory for Linux host (using '/proc/meminfo') ",
t);
return -1;
}
}
/**
* Returns the size of the physical memory in bytes on a Mac OS-based operating system
*
* @return the size of the physical memory in bytes or {@code -1}, if the size could not be
* determined
*/
private static long getSizeOfPhysicalMemoryForMac() {
BufferedReader bi = null;
try {
Process proc = Runtime.getRuntime().exec("sysctl hw.memsize");
bi =
new BufferedReader(
new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = bi.readLine()) != null) {
if (line.startsWith("hw.memsize")) {
long memsize = Long.parseLong(line.split(":")[1].trim());
bi.close();
proc.destroy();
return memsize;
}
}
} catch (Throwable t) {
LOG.error("Cannot determine physical memory of machine for MacOS host", t);
return -1;
} finally {
if (bi != null) {
try {
bi.close();
} catch (IOException ignored) {
}
}
}
return -1;
}
/**
* Returns the size of the physical memory in bytes on FreeBSD.
*
* @return the size of the physical memory in bytes or {@code -1}, if the size could not be
* determined
*/
private static long getSizeOfPhysicalMemoryForFreeBSD() {
BufferedReader bi = null;
try {
Process proc = Runtime.getRuntime().exec("sysctl hw.physmem");
bi =
new BufferedReader(
new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = bi.readLine()) != null) {
if (line.startsWith("hw.physmem")) {
long memsize = Long.parseLong(line.split(":")[1].trim());
bi.close();
proc.destroy();
return memsize;
}
}
LOG.error(
"Cannot determine the size of the physical memory for FreeBSD host "
+ "(using 'sysctl hw.physmem').");
return -1;
} catch (Throwable t) {
LOG.error(
"Cannot determine the size of the physical memory for FreeBSD host "
+ "(using 'sysctl hw.physmem')",
t);
return -1;
} finally {
if (bi != null) {
try {
bi.close();
} catch (IOException ignored) {
}
}
}
}
/**
* Returns the size of the physical memory in bytes on Windows.
*
* @return the size of the physical memory in bytes or {@code -1}, if the size could not be
* determined
*/
private static long getSizeOfPhysicalMemoryForWindows() {
BufferedReader bi = null;
try {
Process proc = Runtime.getRuntime().exec("wmic memorychip get capacity");
bi =
new BufferedReader(
new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8));
String line = bi.readLine();
if (line == null) {
return -1L;
}
if (!line.startsWith("Capacity")) {
return -1L;
}
long sizeOfPhyiscalMemory = 0L;
while ((line = bi.readLine()) != null) {
if (line.isEmpty()) {
continue;
}
line = line.replaceAll(" ", "");
sizeOfPhyiscalMemory += Long.parseLong(line);
}
return sizeOfPhyiscalMemory;
} catch (Throwable t) {
LOG.error(
"Cannot determine the size of the physical memory for Windows host "
+ "(using 'wmic memorychip')",
t);
return -1L;
} finally {
if (bi != null) {
try {
bi.close();
} catch (Throwable ignored) {
}
}
}
}
// --------------------------------------------------------------------------------------------
private Hardware() {
}
}
| 8,380 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/LocalFileSystemFactory.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
public class LocalFileSystemFactory implements FileSystemFactory {
@Override
public String getScheme() {
return "file";
}
@Override
public FileSystem create(URI fsUri) throws IOException {
return FileSystem.get(fsUri, new Configuration());
}
}
| 8,381 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/ResourceManagerGatewayCxn.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent;
import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import io.github.resilience4j.retry.event.RetryOnRetryEvent;
import io.mantisrx.common.Ack;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.spectator.MetricGroupId;
import io.mantisrx.server.agent.utils.DurableBooleanState;
import io.mantisrx.server.agent.utils.ExponentialBackoffAbstractScheduledService;
import io.mantisrx.server.master.resourcecluster.ResourceClusterGateway;
import io.mantisrx.server.master.resourcecluster.TaskExecutorDisconnection;
import io.mantisrx.server.master.resourcecluster.TaskExecutorHeartbeat;
import io.mantisrx.server.master.resourcecluster.TaskExecutorRegistration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.apache.flink.api.common.time.Time;
@Slf4j
@ToString(of = "gateway")
class ResourceManagerGatewayCxn extends ExponentialBackoffAbstractScheduledService {
private final int idx;
private final TaskExecutorRegistration taskExecutorRegistration;
@Getter
@Setter
private volatile ResourceClusterGateway gateway;
private final Time heartBeatInterval;
private final Time heartBeatTimeout;
private final long registrationRetryInitialDelayMillis;
private final double registrationRetryMultiplier;
private final double registrationRetryRandomizationFactor;
private final int registrationRetryMaxAttempts;
private final int tolerableConsecutiveHeartbeatFailures;
private final TaskExecutor taskExecutor;
// flag representing if the task executor has been registered with the resource manager
@Getter
private volatile boolean registered = false;
private final Counter heartbeatTimeoutCounter;
private final Counter heartbeatFailureCounter;
private final Counter taskExecutorRegistrationFailureCounter;
private final Counter taskExecutorDisconnectionFailureCounter;
private final Counter taskExecutorRegistrationCounter;
private final Counter taskExecutorDisconnectionCounter;
private final DurableBooleanState alreadyRegistered;
ResourceManagerGatewayCxn(
int idx,
TaskExecutorRegistration taskExecutorRegistration,
ResourceClusterGateway gateway,
Time heartBeatInterval,
Time heartBeatTimeout,
TaskExecutor taskExecutor,
int tolerableConsecutiveHeartbeatFailures,
long heartbeatRetryInitialDelayMillis,
long heartbeatRetryMaxDelayMillis,
long registrationRetryInitialDelayMillis,
double registrationRetryMultiplier,
double registrationRetryRandomizationFactor,
int registrationRetryMaxAttempts,
DurableBooleanState alreadyRegistered) {
super(heartbeatRetryInitialDelayMillis, heartbeatRetryMaxDelayMillis);
this.tolerableConsecutiveHeartbeatFailures = tolerableConsecutiveHeartbeatFailures;
this.idx = idx;
this.taskExecutorRegistration = taskExecutorRegistration;
this.gateway = gateway;
this.heartBeatInterval = heartBeatInterval;
this.heartBeatTimeout = heartBeatTimeout;
this.taskExecutor = taskExecutor;
this.registrationRetryInitialDelayMillis = registrationRetryInitialDelayMillis;
this.registrationRetryMultiplier = registrationRetryMultiplier;
this.registrationRetryRandomizationFactor = registrationRetryRandomizationFactor;
this.registrationRetryMaxAttempts = registrationRetryMaxAttempts;
this.alreadyRegistered = alreadyRegistered;
final MetricGroupId teGroupId = new MetricGroupId("TaskExecutor");
Metrics m = new Metrics.Builder()
.id(teGroupId)
.addCounter("heartbeatTimeout")
.addCounter("heartbeatFailure")
.addCounter("taskExecutorRegistrationFailure")
.addCounter("taskExecutorDisconnectionFailure")
.addCounter("taskExecutorRegistration")
.addCounter("taskExecutorDisconnection")
.build();
this.heartbeatTimeoutCounter = m.getCounter("heartbeatTimeout");
this.heartbeatFailureCounter = m.getCounter("heartbeatFailure");
this.taskExecutorRegistrationFailureCounter = m.getCounter("taskExecutorRegistrationFailure");
this.taskExecutorDisconnectionFailureCounter = m.getCounter("taskExecutorDisconnectionFailure");
this.taskExecutorRegistrationCounter = m.getCounter("taskExecutorRegistration");
this.taskExecutorDisconnectionCounter = m.getCounter("taskExecutorDisconnection");
}
@Override
protected String serviceName() {
return "ResourceManagerGatewayCxn-" + idx;
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedDelaySchedule(
0,
heartBeatInterval.getSize(),
heartBeatInterval.getUnit());
}
@Override
public void startUp() throws Exception {
try {
if (!alreadyRegistered.getState()) {
log.info("Trying to register with resource manager {}", gateway);
registerTaskExecutorWithRetry();
} else {
log.info("Registered with resource manager {} already", gateway);
// sending heartbeat instead
runIteration();
}
registered = true;
alreadyRegistered.setState(true);
} catch (Exception e) {
// the registration may or may not have succeeded. Since we don't know let's just
// do the disconnection just to be safe.
log.error("Registration to gateway {} has failed; Disconnecting now to be safe", gateway,
e);
try {
disconnectTaskExecutor();
} catch (Exception ignored) {}
throw e;
}
}
private void onRegistrationRetry(RetryOnRetryEvent event) {
log.info("Retrying task executor registration. {}", event);
taskExecutorRegistrationFailureCounter.increment();
}
private void registerTaskExecutorWithRetry() throws Exception {
final IntervalFunction intervalFn = IntervalFunction.ofExponentialRandomBackoff(registrationRetryInitialDelayMillis, registrationRetryMultiplier, registrationRetryRandomizationFactor);
final RetryConfig retryConfig = RetryConfig.custom()
.maxAttempts(registrationRetryMaxAttempts)
.intervalFunction(intervalFn)
.build();
final RetryRegistry retryRegistry = RetryRegistry.of(retryConfig);
final Retry retry = retryRegistry.retry("ResourceManagerGatewayCxn:registerTaskExecutor", retryConfig);
retry.getEventPublisher().onRetry(this::onRegistrationRetry);
try {
Retry.decorateCheckedSupplier(retry, this::registerTaskExecutor).apply();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
private Ack registerTaskExecutor() throws ExecutionException, InterruptedException, TimeoutException {
taskExecutorRegistrationCounter.increment();
return gateway
.registerTaskExecutor(taskExecutorRegistration)
.get(heartBeatTimeout.getSize(), heartBeatTimeout.getUnit());
}
private void disconnectTaskExecutor() throws ExecutionException, InterruptedException, TimeoutException {
taskExecutorDisconnectionCounter.increment();
try {
gateway.disconnectTaskExecutor(
new TaskExecutorDisconnection(taskExecutorRegistration.getTaskExecutorID(),
taskExecutorRegistration.getClusterID()))
.get(2 * heartBeatTimeout.getSize(), heartBeatTimeout.getUnit());
} catch (Exception e) {
log.error("Disconnection has failed", e);
taskExecutorDisconnectionFailureCounter.increment();
throw e;
}
}
protected void runIteration() throws Exception {
try {
taskExecutor.getCurrentReport()
.thenComposeAsync(report -> {
log.debug("Sending heartbeat to resource manager {} with report {}", gateway, report);
return gateway.heartBeatFromTaskExecutor(new TaskExecutorHeartbeat(taskExecutorRegistration.getTaskExecutorID(), taskExecutorRegistration.getClusterID(), report));
})
.get(heartBeatTimeout.getSize(), heartBeatTimeout.getUnit());
// the heartbeat was successful, let's reset the counter and set the registered flag
registered = true;
} catch (TimeoutException e) {
heartbeatTimeoutCounter.increment();
handleHeartbeatFailure(e);
throw e;
} catch (Exception e) {
heartbeatFailureCounter.increment();
handleHeartbeatFailure(e);
throw e;
}
}
private void handleHeartbeatFailure(Exception e) throws Exception {
log.error("Failed to send heartbeat to gateway {}", gateway, e);
// if there are no more retries then clear the registered flag
if (getRetryCount() >= tolerableConsecutiveHeartbeatFailures) {
registered = false;
} else {
log.info("Ignoring heartbeat failure to gateway {} due to failed heartbeats {} <= {}",
gateway, getRetryCount(), tolerableConsecutiveHeartbeatFailures);
}
}
@Override
public void shutDown() throws Exception {
registered = false;
disconnectTaskExecutor();
}
}
| 8,382 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/ProcFileReader.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.shaded.com.google.common.base.Charsets;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
/**
* Reader that specializes in parsing {@code /proc/} files quickly. Walks
* through the stream using a single space {@code ' '} as token separator, and
* requires each line boundary to be explicitly acknowledged using
* {@link #finishLine()}. Assumes {@link Charsets#US_ASCII} encoding.
* <p>
* Currently doesn't support formats based on {@code \0}, tabs, or repeated
* delimiters.
*/
public class ProcFileReader implements Closeable {
private final InputStream mStream;
private final byte[] mBuffer;
/** Write pointer in {@link #mBuffer}. */
private int mTail;
/** Flag when last read token finished current line. */
private boolean mLineFinished;
public ProcFileReader(InputStream stream) throws IOException {
this(stream, 4096);
}
public ProcFileReader(InputStream stream, int bufferSize) throws IOException {
mStream = stream;
mBuffer = new byte[bufferSize];
// read enough to answer hasMoreData
fillBuf();
}
/**
* Read more data from {@link #mStream} into internal buffer.
*/
private int fillBuf() throws IOException {
final int length = mBuffer.length - mTail;
if (length == 0) {
throw new IOException("attempting to fill already-full buffer");
}
final int read = mStream.read(mBuffer, mTail, length);
if (read != -1) {
mTail += read;
}
return read;
}
/**
* Consume number of bytes from beginning of internal buffer. If consuming
* all remaining bytes, will attempt to {@link #fillBuf()}.
*/
private void consumeBuf(int count) throws IOException {
// TODO: consider moving to read pointer, but for now traceview says
// these copies aren't a bottleneck.
System.arraycopy(mBuffer, count, mBuffer, 0, mTail - count);
mTail -= count;
if (mTail == 0) {
fillBuf();
}
}
private int nextStartIndex() throws IOException {
for (int i = 0; i < mTail; i++) {
if (mBuffer[i] != ' ') {
return i;
}
}
return mTail;
}
/**
* Find buffer index of next token delimiter, usually space or newline. Will
* fill buffer as needed.
*/
private int nextTokenIndex() throws IOException {
if (mLineFinished) {
throw new IOException("no tokens remaining on current line");
}
int i = 0;
boolean nonWhitespaceSeen = false;
do {
// scan forward for token boundary
for (; i < mTail; i++) {
final byte b = mBuffer[i];
if (b == '\n') {
mLineFinished = true;
return i;
}
if (b == ' ' && nonWhitespaceSeen) {
return i;
}
if (b != ' ') {
nonWhitespaceSeen = true;
}
}
} while (fillBuf() > 0);
throw new IOException("end of stream while looking for token boundary");
}
/**
* Check if stream has more data to be parsed.
*/
public boolean hasMoreData() {
return mTail > 0;
}
/**
* Finish current line, skipping any remaining data.
*/
public void finishLine() throws IOException {
// last token already finished line; reset silently
if (mLineFinished) {
mLineFinished = false;
return;
}
int i = 0;
do {
// scan forward for line boundary and consume
for (; i < mTail; i++) {
if (mBuffer[i] == '\n') {
consumeBuf(i + 1);
return;
}
}
} while (fillBuf() > 0);
throw new IOException("end of stream while looking for line boundary");
}
/**
* Parse and return next token as {@link String}.
*/
public String nextString() throws IOException {
final int tokenIndex = nextTokenIndex();
if (tokenIndex == 0) {
return "";
}
final int startIndex = nextStartIndex();
final String s = new String(mBuffer, startIndex, (tokenIndex - startIndex), Charsets.US_ASCII);
consumeBuf(tokenIndex + 1);
return s;
}
/**
* Parse and return next token as base-10 encoded {@code long}.
*/
public long nextLong() throws IOException {
final int tokenIndex = nextTokenIndex();
final int startIndex = nextStartIndex();
final boolean negative = mBuffer[startIndex] == '-';
// TODO: refactor into something like IntegralToString
long result = 0;
for (int i = negative ? startIndex + 1 : startIndex; i < tokenIndex; i++) {
final int digit = mBuffer[i] - '0';
if (digit < 0 || digit > 9) {
throw invalidLong(tokenIndex);
}
// always parse as negative number and apply sign later; this
// correctly handles MIN_VALUE which is "larger" than MAX_VALUE.
final long next = result * 10 - digit;
if (next > result) {
throw invalidLong(tokenIndex);
}
result = next;
}
consumeBuf(tokenIndex + 1);
return negative ? result : -result;
}
private NumberFormatException invalidLong(int tokenIndex) {
return new NumberFormatException(
"invalid long: " + new String(mBuffer, 0, tokenIndex, Charsets.US_ASCII));
}
/**
* Parse and return next token as base-10 encoded {@code int}.
*/
public int nextInt() throws IOException {
final long value = nextLong();
if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) {
throw new NumberFormatException("parsed value larger than integer");
}
return (int) value;
}
public void close() throws IOException {
mStream.close();
}
}
| 8,383 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/NetworkSubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.runtime.loader.config.Usage.UsageBuilder;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.Value;
/**
* Implementation uses ideas from <a href="https://github.com/python-diamond/Diamond/blob/master/src/collectors/network/network.py">the diamond project</a>'s network metrics collector.
*/
@RequiredArgsConstructor
class NetworkSubsystemProcess implements SubsystemProcess {
private final String fileName;
private final String device;
private Map<String, NetworkStats> getDeviceLevelStats() throws IOException {
Map<String, NetworkStats> result = new HashMap<>();
try (ProcFileReader reader = new ProcFileReader(Files.newInputStream(Paths.get(fileName)))) {
// consume header
reader.finishLine();
reader.finishLine();
while (reader.hasMoreData()) {
String iface = reader.nextString();
if (iface.isEmpty()) {
break;
}
// always include snapshot values
long rxBytes = reader.nextLong();
long rxPackets = reader.nextLong();
reader.nextLong(); // errs skip
reader.nextLong(); // drop skip
reader.nextLong(); // fifo skip
reader.nextLong(); // frame skip
reader.nextLong(); // compressed skip
reader.nextLong(); // multicast skip
long txBytes = reader.nextLong();
long txPackets = reader.nextLong();
result.put(iface, new NetworkStats(rxBytes, rxPackets, txBytes, txPackets));
reader.finishLine();
}
} catch (IOException e) {
throw e;
} catch (NullPointerException | NumberFormatException e) {
throw new IllegalStateException("problem parsing stats: " + e);
}
return result;
}
@Override
public void getUsage(UsageBuilder usageBuilder) throws IOException {
Map<String, NetworkStats> result = getDeviceLevelStats();
NetworkStats stats = result.get(device);
usageBuilder.networkReadBytes(stats.getRxBytes());
usageBuilder.networkWriteBytes(stats.getTxBytes());
}
@Value
private class NetworkStats {
long rxBytes;
long rxPackets;
long txBytes;
long txPackets;
}
}
| 8,384 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/CpuAcctsSubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.runtime.loader.config.Usage;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Uses cpuacct.stat file for setting various metrics.
* Code uses ideas from the <a href="https://github.com/apache/mesos/blob/96339efb53f7cdf1126ead7755d2b83b435e3263/src/slave/containerizer/mesos/isolators/cgroups/subsystems/cpuacct.cpp#L90-L108">mesos implementation here</a> .
*/
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class CpuAcctsSubsystemProcess implements SubsystemProcess {
private final Cgroup cgroup;
@Override
public void getUsage(Usage.UsageBuilder resourceUsageBuilder) throws IOException {
if (cgroup.isV1()) {
handleV1(resourceUsageBuilder);
} else {
handleV2(resourceUsageBuilder);
}
}
private void handleV1(Usage.UsageBuilder resourceUsageBuilder) throws IOException {
final Map<String, Long> stat = cgroup.getStats("cpuacct", "cpuacct.stat");
Optional<Long> user = Optional.ofNullable(stat.get("user"));
Optional<Long> system = Optional.ofNullable(stat.get("system"));
if (user.isPresent() && system.isPresent()) {
// the user usage and the system usage is measured in jiffies.
// Hence, the division by 100.0.
resourceUsageBuilder.cpusUserTimeSecs(user.get() / (100.0));
resourceUsageBuilder.cpusSystemTimeSecs(system.get() / (100.0));
} else {
log.warn("Expected metrics not found; Found stats={}", stat);
}
Long quota = cgroup.getMetric("cpuacct", "cpu.cfs_quota_us");
Long period = cgroup.getMetric("cpuacct", "cpu.cfs_period_us");
double quotaCount = 0;
if (quota > -1 && period > 0) {
quotaCount = Math.ceil((float) quota / (float) period);
}
if (quotaCount > 0.) {
resourceUsageBuilder.cpusLimit(quotaCount);
} else {
log.warn("quota={} & period={} are not configured correctly", quota, period);
}
}
private void handleV2(Usage.UsageBuilder resourceUsageBuilder) throws IOException {
Map<String, Long> cpuStats = cgroup.getStats("", "cpu.stat");
resourceUsageBuilder
.cpusUserTimeSecs(cpuStats.getOrDefault("user_usec", 0L) / 1000_000.0)
.cpusSystemTimeSecs(cpuStats.getOrDefault("system_usec", 0L) / 1000_000.0);
List<Long> metrics = cgroup.getMetrics("", "cpu.max");
if (metrics.size() != 2) {
log.warn("cpu.max metrics={} are not configured correctly", metrics);
} else {
Long quota = metrics.get(0);
Long period = metrics.get(1);
resourceUsageBuilder.cpusLimit(quota / (float) period);
}
}
}
| 8,385 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/Cgroup.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import java.io.IOException;
import java.util.List;
import java.util.Map;
interface Cgroup {
/**
* Represents if this cgroup is a v1 or v2 cgroup
* @return
*/
Boolean isV1();
List<Long> getMetrics(String subsystem, String metricName) throws IOException;
Long getMetric(String subsystem, String metricName) throws IOException;
Map<String, Long> getStats(String subsystem, String stat) throws IOException;
}
| 8,386 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/SubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.runtime.loader.config.Usage;
import java.io.IOException;
interface SubsystemProcess {
void getUsage(Usage.UsageBuilder usageBuilder) throws IOException;
}
| 8,387 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/CgroupsMetricsCollector.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.runtime.loader.config.MetricsCollector;
import io.mantisrx.runtime.loader.config.Usage;
import java.io.IOException;
import java.util.Properties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Cgroups based metrics collector.
* This assumes that the worker task is being run on a cgroup based on container.
*/
@Slf4j
@RequiredArgsConstructor
public class CgroupsMetricsCollector implements MetricsCollector {
private final CpuAcctsSubsystemProcess cpu;
private final MemorySubsystemProcess memory;
private final NetworkSubsystemProcess network;
@SuppressWarnings("unused")
public static CgroupsMetricsCollector valueOf(Properties properties) {
String cgroupPath = properties.getProperty("mantis.cgroups.path", "/sys/fs/cgroup");
String networkIfacePath = properties.getProperty("mantis.cgroups.networkPath", "/proc/net/dev");
String interfaceName = properties.getProperty("mantis.cgroups.interface", "eth0:");
return new CgroupsMetricsCollector(cgroupPath, networkIfacePath, interfaceName);
}
public CgroupsMetricsCollector(String cgroupPath, String networkIfacePath, String interfaceName) {
Cgroup cgroup = new CgroupImpl(cgroupPath);
this.cpu = new CpuAcctsSubsystemProcess(cgroup);
this.memory = new MemorySubsystemProcess(cgroup);
this.network = new NetworkSubsystemProcess(networkIfacePath, interfaceName);
}
@Override
public Usage get() throws IOException {
try {
Usage.UsageBuilder usageBuilder = Usage.builder();
cpu.getUsage(usageBuilder);
memory.getUsage(usageBuilder);
network.getUsage(usageBuilder);
return usageBuilder.build();
} catch (Exception ex) {
log.warn("Failed to get usage: ", ex);
return Usage.builder().build();
}
}
}
| 8,388 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/MemorySubsystemProcess.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.runtime.loader.config.Usage.UsageBuilder;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Uses cgroup memory.stat for collecting various metrics about the memory usage of the container.
* Implementation uses ideas from the <a href="https://github.com/apache/mesos/blob/96339efb53f7cdf1126ead7755d2b83b435e3263/src/slave/containerizer/mesos/isolators/cgroups/subsystems/memory.cpp#L474-L499">actual mesos implementation</a> used in the statistics.json endpoint.
*/
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
class MemorySubsystemProcess implements SubsystemProcess {
private final Cgroup cgroup;
@Override
public void getUsage(UsageBuilder usageBuilder) throws IOException {
if (cgroup.isV1()) {
handleV1(usageBuilder);
} else {
handleV2(usageBuilder);
}
}
private void handleV1(UsageBuilder usageBuilder) throws IOException {
Long memLimit = cgroup.getMetric("memory", "memory.limit_in_bytes");
usageBuilder.memLimit(memLimit);
Map<String, Long> stats = cgroup.getStats("memory", "memory.stat");
Optional<Long> totalRss = Optional.ofNullable(stats.get("total_rss"));
if (totalRss.isPresent()) {
usageBuilder.memAnonBytes(totalRss.get());
usageBuilder.memRssBytes(totalRss.get());
} else {
log.warn("stats for memory not found; stats={}", stats);
}
}
private void handleV2(UsageBuilder usageBuilder) throws IOException {
Long memLimit = cgroup.getMetric("", "memory.max");
usageBuilder.memLimit(memLimit);
Long memCurrent = cgroup.getMetric("", "memory.current");
usageBuilder.memRssBytes(memCurrent);
Map<String, Long> stats = cgroup.getStats("", "memory.stat");
Optional<Long> anon = Optional.ofNullable(stats.get("anon"));
if (anon.isPresent()) {
usageBuilder.memAnonBytes(anon.get());
} else {
log.warn("stats for memory not found; stats={}", stats);
}
}
}
| 8,389 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/metrics/cgroups/CgroupImpl.java | /*
* Copyright 2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.metrics.cgroups;
import io.mantisrx.shaded.org.apache.curator.shaded.com.google.common.base.Preconditions;
import io.vavr.Tuple2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class CgroupImpl implements Cgroup {
private final String path;
/**
* Maybe change this to the below command in the future.
* <p>
* ``` stat -fc %T /sys/fs/cgroup/ ``` This should return cgroup2fs for cgroupv2 and tmpfs for
* cgroupv1.
*/
@Getter(lazy = true, value = AccessLevel.PRIVATE)
private final boolean old = getSubsystems().size() > 0;
@Override
public Boolean isV1() {
return isOld();
}
@Override
public List<Long> getMetrics(String subsystem, String metricName) throws IOException {
Path metricPath = Paths.get(path, subsystem, metricName);
try {
return
Files.readAllLines(metricPath)
.stream()
.findFirst()
.map(s -> Arrays.asList(s.split(" ")))
.orElse(Collections.emptyList())
.stream()
.map(CgroupImpl::convertStringToLong)
.collect(Collectors.toList());
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public Long getMetric(String subsystem, String metricName) throws IOException {
Path metricPath = Paths.get(path, subsystem, metricName);
try {
return Files.readAllLines(metricPath).stream().findFirst()
.map(CgroupImpl::convertStringToLong).get();
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* Example usage: user 43873627 system 4185541
*
* @param subsystem subsystem the stat file is part of.
* @param stat name of the stat file
* @return map of metrics to their corresponding values
* @throws IOException
*/
@Override
public Map<String, Long> getStats(String subsystem, String stat) throws IOException {
Path statPath = Paths.get(path, subsystem, stat);
return
Files.readAllLines(statPath)
.stream()
.map(l -> {
String[] parts = l.split("\\s+");
Preconditions.checkArgument(parts.length == 2,
"Expected two parts only but was {} parts", parts.length);
return new Tuple2<>(parts[0], convertStringToLong(parts[1]));
})
.collect(Collectors.toMap(t -> t._1, t -> t._2));
}
/**
* Convert a number from its string representation to a long.
*
* @param strval: value to convert
* @return The converted long value. Long max value is returned if the string representation
* exceeds the range of type long.
*/
private static long convertStringToLong(String strval) {
try {
return Long.parseLong(strval);
} catch (NumberFormatException e) {
// For some properties (e.g. memory.limit_in_bytes, cgroups v1) we may overflow
// the range of signed long. In this case, return Long max value.
return Long.MAX_VALUE;
}
}
private static final Set<String> knownSubsystems =
new HashSet<>(Arrays.asList("cpu", "cpuacct", "cpuset", "memory"));
private List<String> getSubsystems() {
return
Arrays.asList(Objects.requireNonNull(Paths.get(path).toFile().listFiles()))
.stream()
.filter(s -> s.isDirectory())
.map(s -> s.getName())
.filter(s -> knownSubsystems.contains(s))
.collect(Collectors.toList());
}
}
| 8,390 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/config/ConfigurationFactory.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.config;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
public interface ConfigurationFactory {
WorkerConfiguration getConfig();
}
| 8,391 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/config/StaticPropertiesConfigurationFactory.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.config;
import io.mantisrx.runtime.loader.config.WorkerConfiguration;
import io.mantisrx.runtime.loader.config.WorkerConfigurationUtils;
import java.util.Properties;
public class StaticPropertiesConfigurationFactory implements ConfigurationFactory {
private final WorkerConfiguration config;
public StaticPropertiesConfigurationFactory(Properties props) {
config = WorkerConfigurationUtils.frmProperties(props, WorkerConfiguration.class);
}
@Override
public WorkerConfiguration getConfig() {
return this.config;
}
@Override
public String toString() {
return "StaticPropertiesConfigurationFactory{" +
", config=" + config +
'}';
}
}
| 8,392 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/utils/DurableBooleanState.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DurableBooleanState {
private final String fileName;
public DurableBooleanState(String fileName) {
this.fileName = fileName;
try {
init();
} catch (IOException e) {
log.error("Failed to initialize the state file", e);
throw new RuntimeException(e);
}
}
private void init() throws IOException {
// create file if it does not exist
if (!new File(fileName).exists()) {
new File(fileName).createNewFile();
}
// initialize the file to 1 byte if it is empty
if (new File(fileName).length() == 0) {
byte[] contents = new byte[]{0};
Files.write(new File(fileName).toPath(), contents, StandardOpenOption.TRUNCATE_EXISTING);
}
}
public void setState(boolean state) throws IOException {
try (FileOutputStream fos = new FileOutputStream(fileName)) {
fos.write(state ? 1 : 0);
fos.flush();
log.info("Set the state to {} successfully", state);
}
}
public boolean getState() throws IOException {
try (FileInputStream fis = new FileInputStream(fileName)) {
int state = fis.read();
return state != 0;
}
}
}
| 8,393 |
0 | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent | Create_ds/mantis/mantis-server/mantis-server-agent/src/main/java/io/mantisrx/server/agent/utils/ExponentialBackoffAbstractScheduledService.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.agent.utils;
import io.mantisrx.shaded.com.google.common.util.concurrent.AbstractScheduledService;
import java.util.concurrent.ThreadLocalRandom;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public abstract class ExponentialBackoffAbstractScheduledService extends AbstractScheduledService {
private final long initialDelayMillis;
private final long maxDelayMillis;
private int retryCount = 0;
private long nextRunTime = 0;
protected ExponentialBackoffAbstractScheduledService(long initialDelayMillis,
long maxDelayMillis) {
this.initialDelayMillis = initialDelayMillis;
this.maxDelayMillis = maxDelayMillis;
}
protected abstract void runIteration() throws Exception;
@Override
protected void runOneIteration() {
if (!isTimeForNextRun()) {
log.debug("Skipping runIteration due to retry delay. Next run after: {}", nextRunTime);
return;
}
runNow();
}
private void runNow() {
try {
runIteration();
resetRetryCount();
} catch (Exception e) {
onFailure();
}
}
private boolean isTimeForNextRun() {
return System.currentTimeMillis() >= nextRunTime;
}
private void onFailure() {
// Reschedule task with backoff
retryCount++;
long delay = (long) Math.min(initialDelayMillis * Math.pow(2, Math.max(20, retryCount)),
maxDelayMillis);
long jitter = ThreadLocalRandom.current().nextLong(delay / 2);
nextRunTime = System.currentTimeMillis() + delay + jitter;
}
private void resetRetryCount() {
retryCount = 0;
nextRunTime = 0;
}
protected int getRetryCount() {
return retryCount;
}
}
| 8,394 |
0 | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker/TestSseServerFactory.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.worker;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelOption;
import io.netty.channel.WriteBufferWaterMark;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import mantis.io.reactivex.netty.RxNetty;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurators;
import mantis.io.reactivex.netty.protocol.http.server.HttpServer;
import mantis.io.reactivex.netty.protocol.http.server.HttpServerRequest;
import mantis.io.reactivex.netty.protocol.http.server.HttpServerResponse;
import mantis.io.reactivex.netty.protocol.http.server.RequestHandler;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import rx.Observable;
public class TestSseServerFactory {
private static final AtomicInteger port = new AtomicInteger(30303);
private static List<HttpServer<String, ServerSentEvent>> servers = new ArrayList<>();
private TestSseServerFactory() {}
public static int getServerPort() {
return port.incrementAndGet();
}
public static int newServerWithInitialData(final String data) {
int port = getServerPort();
return newServerWithInitialData(port, data);
}
public static int newServerWithInitialData(final int port, final String data) {
final HttpServer<String, ServerSentEvent> server = RxNetty.newHttpServerBuilder(
port,
new RequestHandler<String, ServerSentEvent>() {
@Override
public Observable<Void> handle(HttpServerRequest<String> req, HttpServerResponse<ServerSentEvent> resp) {
final ByteBuf byteBuf = resp.getAllocator().buffer().writeBytes(data.getBytes());
resp.writeAndFlush(new ServerSentEvent(byteBuf));
return Observable.empty();
}
})
.pipelineConfigurator(PipelineConfigurators.<String>serveSseConfigurator())
.channelOption(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(1024 * 1024, 5 * 1024 * 1024))
.build();
server.start();
synchronized (servers) {
servers.add(server);
}
return port;
}
public static void stopAllRunning() throws InterruptedException {
synchronized (servers) {
final Iterator<HttpServer<String, ServerSentEvent>> iter = servers.iterator();
while (iter.hasNext()) {
final HttpServer<String, ServerSentEvent> server = iter.next();
server.shutdown();
iter.remove();
}
}
}
} | 8,395 |
0 | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker/client/SseWorkerConnectionFunctionTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.worker.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import io.mantisrx.common.MantisServerSentEvent;
import io.mantisrx.server.worker.TestSseServerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;
public class SseWorkerConnectionFunctionTest {
private static final Logger logger = LoggerFactory.getLogger(SseWorkerConnectionFunctionTest.class);
private static final String TEST_EVENT_DATA = "test event string";
@Test
public void testSseConnection() throws InterruptedException {
final int serverPort = TestSseServerFactory.getServerPort();
final CountDownLatch errorLatch = new CountDownLatch(1);
final CountDownLatch latch = new CountDownLatch(1);
final boolean reconnectOnConnReset = true;
SseWorkerConnectionFunction connectionFunction = new SseWorkerConnectionFunction(reconnectOnConnReset, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
logger.warn("connection was reset, should be retried", throwable);
errorLatch.countDown();
}
});
final WorkerConnection<MantisServerSentEvent> conn = connectionFunction.call("localhost", serverPort);
final Observable<MantisServerSentEvent> events = conn.call();
events
.doOnNext(new Action1<MantisServerSentEvent>() {
@Override
public void call(MantisServerSentEvent e) {
logger.info("got event {}", e.getEventAsString());
assertEquals(TEST_EVENT_DATA, e.getEventAsString());
latch.countDown();
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
logger.error("caught error ", throwable);
fail("unexpected error");
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.warn("onCompleted");
}
})
.subscribe();
errorLatch.await(30, TimeUnit.SECONDS);
// newServerWithInitialData test server after client started and unable to connect
// the client should recover and get expected data
TestSseServerFactory.newServerWithInitialData(serverPort, TEST_EVENT_DATA);
latch.await(30, TimeUnit.SECONDS);
TestSseServerFactory.stopAllRunning();
}
}
| 8,396 |
0 | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker/client/MetricsClientImplTest.java | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.worker.client;
import static org.junit.Assert.assertEquals;
import io.mantisrx.common.MantisServerSentEvent;
import io.mantisrx.common.metrics.measurement.CounterMeasurement;
import io.mantisrx.common.metrics.measurement.GaugeMeasurement;
import io.mantisrx.common.metrics.measurement.Measurements;
import io.mantisrx.common.network.Endpoint;
import io.mantisrx.common.network.WorkerEndpoint;
import io.mantisrx.runtime.parameter.SinkParameters;
import io.mantisrx.server.core.stats.MetricStringConstants;
import io.mantisrx.server.worker.TestSseServerFactory;
import io.mantisrx.shaded.com.fasterxml.jackson.core.JsonProcessingException;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.reactivex.mantis.remote.observable.EndpointChange;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.Observer;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class MetricsClientImplTest {
private static final Logger logger = LoggerFactory.getLogger(MetricsClientImplTest.class);
private static final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
public String generateMetricJson(final String metricGroup) throws JsonProcessingException {
return mapper.writeValueAsString(new Measurements(metricGroup, System.currentTimeMillis(),
Collections.<CounterMeasurement>emptyList(),
Arrays.asList(new GaugeMeasurement(MetricStringConstants.CPU_PCT_USAGE_CURR, 20),
new GaugeMeasurement(MetricStringConstants.TOT_MEM_USAGE_CURR, 123444)),
Collections.<String, String>emptyMap()));
}
@Test
public void testMetricConnections() throws InterruptedException, UnsupportedEncodingException, JsonProcessingException {
final String jobId = "test-job-1";
final String testResUsageMetricData = generateMetricJson(MetricStringConstants.RESOURCE_USAGE_METRIC_GROUP);
final String testDropDataMetricData = generateMetricJson(MetricStringConstants.DATA_DROP_METRIC_GROUP);
final int metricsPort = TestSseServerFactory.newServerWithInitialData(testResUsageMetricData);
final AtomicInteger i = new AtomicInteger(0);
final Observable<EndpointChange> workerMetricLocationStream = Observable.interval(1, TimeUnit.SECONDS, Schedulers.io()).map(new Func1<Long, EndpointChange>() {
@Override
public EndpointChange call(Long aLong) {
logger.info("emitting endpointChange");
if (i.getAndIncrement() % 10 == 0) {
return new EndpointChange(EndpointChange.Type.add, new Endpoint("localhost", 31002));
} else {
return new EndpointChange(EndpointChange.Type.add, new WorkerEndpoint("localhost", 31002, 1, metricsPort, 0, 1));
}
}
});
MetricsClientImpl<MantisServerSentEvent> metricsClient =
new MetricsClientImpl<>(jobId,
new SseWorkerConnectionFunction(true, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
logger.error("Metric connection error: " + throwable.getMessage());
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
logger.error("Interrupted waiting for retrying connection");
}
}
}, new SinkParameters.Builder().withParameter("name", MetricStringConstants.RESOURCE_USAGE_METRIC_GROUP).build()),
new JobWorkerMetricsLocator() {
@Override
public Observable<EndpointChange> locateWorkerMetricsForJob(String jobId) {
return workerMetricLocationStream;
}
},
Observable.just(1),
new Observer<WorkerConnectionsStatus>() {
@Override
public void onCompleted() {
logger.info("got onCompleted in WorkerConnStatus obs");
}
@Override
public void onError(Throwable e) {
logger.info("got onError in WorkerConnStatus obs");
}
@Override
public void onNext(WorkerConnectionsStatus workerConnectionsStatus) {
logger.info("got WorkerConnStatus {}", workerConnectionsStatus);
}
},
60);
final CountDownLatch latch = new CountDownLatch(1);
final Observable<Observable<MantisServerSentEvent>> results = metricsClient.getResults();
Observable.merge(results)
.doOnNext(new Action1<MantisServerSentEvent>() {
@Override
public void call(MantisServerSentEvent event) {
logger.info("got event {}", event.getEventAsString());
assertEquals(testResUsageMetricData, event.getEventAsString());
latch.countDown();
}
})
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
logger.error("got error {}", throwable.getMessage(), throwable);
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
logger.info("onComplete");
}
})
.subscribe();
latch.await(30, TimeUnit.SECONDS);
TestSseServerFactory.stopAllRunning();
}
}
| 8,397 |
0 | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/test/java/io/mantisrx/server/worker/client/SseWorkerConnectionTest.java | /*
* Copyright 2021 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.worker.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.netflix.spectator.api.DefaultRegistry;
import io.mantisrx.common.MantisServerSentEvent;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.common.metrics.spectator.MetricGroupId;
import io.mantisrx.common.metrics.spectator.SpectatorRegistryFactory;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.reactivx.mantis.operators.DropOperator;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import mantis.io.reactivex.netty.protocol.http.sse.ServerSentEvent;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
import rx.schedulers.TestScheduler;
public class SseWorkerConnectionTest {
private static final Logger logger = LoggerFactory.getLogger(SseWorkerConnectionTest.class);
@Test
public void testStreamContentDrops() throws Exception {
SpectatorRegistryFactory.setRegistry(new DefaultRegistry());
String metricGroupString = "testmetric";
MetricGroupId metricGroupId = new MetricGroupId(metricGroupString);
SseWorkerConnection workerConnection = new SseWorkerConnection("connection_type",
"hostname",
80,
b -> {},
b -> {},
t -> {},
600,
false,
new CopyOnWriteArraySet<>(),
1,
null,
true,
metricGroupId);
HttpClientResponse<ServerSentEvent> response = mock(HttpClientResponse.class);
TestScheduler testScheduler = Schedulers.test();
// Events are just "0", "1", "2", ...
Observable<ServerSentEvent> contentObs = Observable.interval(1, TimeUnit.SECONDS, testScheduler)
.map(t -> new ServerSentEvent(Unpooled.copiedBuffer(Long.toString(t), Charset.defaultCharset())));
when(response.getContent()).thenReturn(contentObs);
TestSubscriber<MantisServerSentEvent> subscriber = new TestSubscriber<>(1);
workerConnection.streamContent(response, b -> {}, 600, "delimiter").subscribeOn(testScheduler).subscribe(subscriber);
testScheduler.advanceTimeBy(100, TimeUnit.SECONDS);
subscriber.assertValueCount(1);
List<MantisServerSentEvent> events = subscriber.getOnNextEvents();
assertEquals("0", events.get(0).getEventAsString());
Metrics metrics = MetricsRegistry.getInstance().getMetric(metricGroupId);
Counter onNextCounter = metrics.getCounter(DropOperator.Counters.onNext.toString());
Counter droppedCounter = metrics.getCounter(DropOperator.Counters.dropped.toString());
logger.info("next: {}", onNextCounter.value());
logger.info("drop: {}", droppedCounter.value());
assertTrue(onNextCounter.value() < 10);
assertTrue(droppedCounter.value() > 90);
}
// Goals of tests:
// SseWorkerConnection uses the MantisHttpClientImpl client
// Connection tracking functionality of the MantisHttpClientImpl
// The connect call should go via MantisHttpClientImpl
@Test
public void testMantisHttpClientUsage() throws Exception {
SpectatorRegistryFactory.setRegistry(new DefaultRegistry());
String metricGroupString = "testmetric";
MetricGroupId metricGroupId = new MetricGroupId(metricGroupString);
SseWorkerConnection workerConnection = new SseWorkerConnection("connection_type",
"hostname",
80,
b -> {},
b -> {},
t -> {},
600,
false,
new CopyOnWriteArraySet<>(),
1,
null,
true,
metricGroupId);
// get SseWorkerConnection to instantiate client
workerConnection.call();
MantisHttpClientImpl client = (MantisHttpClientImpl) workerConnection.client;
// SseWorkerConnection object should use MantisHttpClientImpl
logger.info("Client type: {}", client.getClass().toString());
assertTrue(workerConnection.client instanceof MantisHttpClientImpl);
// check MantisHttpClientImpl.connect usage
logger.info("MantisHttpClientImpl.connect() called: {}", client.isObservableConectionSet());
assertTrue(client.isObservableConectionSet());
// check connection monitor functionality of MantisHttpClientImpl
Channel dummyChannel = mock(Channel.class);
client.trackConnection(dummyChannel);
logger.info("Connection tracker size: {}", client.connectionTrackerSize());
assertEquals(1, client.connectionTrackerSize());
client.closeConn();
logger.info("Connection tracker size: {}", client.connectionTrackerSize());
assertEquals(0, client.connectionTrackerSize());
// Test cannot add more channels after the client is closed.
client.trackConnection(dummyChannel);
logger.info("Connection tracker size: {}", client.connectionTrackerSize());
assertEquals(0, client.connectionTrackerSize());
}
}
| 8,398 |
0 | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/main/java/io/mantisrx/server/worker | Create_ds/mantis/mantis-server/mantis-server-worker-client/src/main/java/io/mantisrx/server/worker/client/MantisHttpClientImpl.java | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.server.worker.client;
import com.netflix.spectator.api.Tag;
import io.mantisrx.common.metrics.Gauge;
import io.mantisrx.common.metrics.Metrics;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import lombok.extern.slf4j.Slf4j;
import mantis.io.reactivex.netty.channel.ObservableConnection;
import mantis.io.reactivex.netty.client.ClientChannelFactory;
import mantis.io.reactivex.netty.client.ClientConnectionFactory;
import mantis.io.reactivex.netty.client.ClientMetricsEvent;
import mantis.io.reactivex.netty.client.ConnectionPoolBuilder;
import mantis.io.reactivex.netty.metrics.MetricEventsSubject;
import mantis.io.reactivex.netty.pipeline.PipelineConfigurator;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientImpl;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientRequest;
import mantis.io.reactivex.netty.protocol.http.client.HttpClientResponse;
import rx.Observable;
@Slf4j
public class MantisHttpClientImpl<I, O> extends HttpClientImpl<I, O> {
private Observable<ObservableConnection<HttpClientResponse<O>, HttpClientRequest<I>>> observableConection;
private List<Channel> connectionTracker;
private AtomicBoolean isClosed = new AtomicBoolean(false);
private final Gauge numConnectionsTracked;
private final static String connectionTrackerMetricgroup = "ConnectionMonitor";
private final static String metricName = "numConnectionsTracked";
private final static String metricTagName = "uuid";
public MantisHttpClientImpl(String name, ServerInfo serverInfo, Bootstrap clientBootstrap, PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ClientConfig clientConfig, ClientChannelFactory<HttpClientResponse<O>, HttpClientRequest<I>> channelFactory, ClientConnectionFactory<HttpClientResponse<O>, HttpClientRequest<I>, ? extends ObservableConnection<HttpClientResponse<O>, HttpClientRequest<I>>> connectionFactory, MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject) {
super(name, serverInfo, clientBootstrap, pipelineConfigurator, clientConfig, channelFactory, connectionFactory, eventsSubject);
this.connectionTracker = new ArrayList<>();
Tag metricTag = Tag.of(metricTagName, UUID.randomUUID().toString());
Metrics m = new Metrics.Builder()
.id(connectionTrackerMetricgroup, metricTag)
.addGauge(metricName)
.build();
this.numConnectionsTracked = m.getGauge(metricName);
}
public MantisHttpClientImpl(String name, ServerInfo serverInfo, Bootstrap clientBootstrap, PipelineConfigurator<HttpClientResponse<O>, HttpClientRequest<I>> pipelineConfigurator, ClientConfig clientConfig, ConnectionPoolBuilder<HttpClientResponse<O>, HttpClientRequest<I>> poolBuilder, MetricEventsSubject<ClientMetricsEvent<?>> eventsSubject) {
super(name, serverInfo, clientBootstrap, pipelineConfigurator, clientConfig, poolBuilder, eventsSubject);
this.connectionTracker = new ArrayList<>();
Tag metricTag = Tag.of(metricTagName, UUID.randomUUID().toString());
Metrics m = new Metrics.Builder()
.id(connectionTrackerMetricgroup, metricTag)
.addGauge(metricName)
.build();
this.numConnectionsTracked = m.getGauge(metricName);
}
@Override
public Observable<ObservableConnection<HttpClientResponse<O>, HttpClientRequest<I>>> connect() {
this.observableConection = super.connect();
return this.observableConection.doOnNext(conn -> trackConnection(conn.getChannel()));
}
protected void trackConnection(Channel channel) {
log.info("Tracking connection: {}", channel.toString());
synchronized (connectionTracker) {
if (isClosed.get()) {
log.info("Http client is already closed. Close the channel immediately. {}", channel);
channel.close();
} else {
this.connectionTracker.add(channel);
numConnectionsTracked.increment();
}
}
}
protected void closeConn() {
synchronized (connectionTracker) {
isClosed.set(true);
for (Channel value : this.connectionTracker) {
Channel channel = value;
log.info("Closing connection: {}. Status at close: isActive: {}, isOpen: {}, isWritable: {}",
channel.toString(), channel.isActive(), channel.isOpen(), channel.isWritable());
channel.close();
numConnectionsTracked.decrement();
}
this.connectionTracker.clear();
}
}
protected int connectionTrackerSize() {
return this.connectionTracker.size();
}
protected boolean isObservableConectionSet() {
return (this.observableConection != null);
}
}
| 8,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.