index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/perf/PerfTest.java
package netflix.ocelli.perf; import java.util.ArrayList; import java.util.List; import netflix.ocelli.LoadBalancer; import netflix.ocelli.client.Behaviors; import netflix.ocelli.client.Connects; import netflix.ocelli.client.TestClient; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PerfTest { private static final Logger LOG = LoggerFactory.getLogger(PerfTest.class); private static final int NUM_HOSTS = 1000; private LoadBalancer<TestClient> selector; @BeforeClass public static void setup() { List<TestClient> hosts = new ArrayList<TestClient>(); for (int i = 0; i < NUM_HOSTS-1; i++) { // hosts.add(TestHost.create("host-"+i, Connects.immediate(), Behaviors.delay(100 + (int)(100 * RANDOM.nextDouble()), TimeUnit.MILLISECONDS))); // hosts.add(TestHost.create("host-"+i, Connects.immediate(), Behaviors.proportionalToLoad(100, 10, TimeUnit.MILLISECONDS))); hosts.add(TestClient.create("host-"+i, Connects.immediate(), Behaviors.immediate())); } // hosts.add(TestHost.create("degrading", Connects.immediate(), Behaviors.degradation(100, 50, TimeUnit.MILLISECONDS))); // source = Observable // .from(hosts) // .map(MembershipEvent.<TestClient>toEvent(EventType.ADD)); } @Test @Ignore public void perf() throws InterruptedException { // ClientLifecycleFactory<TestClient> factory = // FailureDetectingClientLifecycleFactory.<TestClient>builder() // .build(); // this.selector = RoundRobinLoadBalancer.create(source.lift(ClientCollector.create(factory))); // //// this.selector.prime(10).toBlocking().last(); // // Observable.range(1, 10) // .subscribe(new Action1<Integer>() { // @Override // public void call(final Integer id) { // Observable.interval(100, TimeUnit.MILLISECONDS, Schedulers.newThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(final Long counter) { // Observable.create(selector) // .concatMap(new TrackingOperation(counter + "")) // .retry() // .subscribe(new Action1<String>() { // @Override // public void call(String t1) { // LOG.info("{} - {} - {}", id, counter, t1); // } // }); // } // }); // } // }); } @Test @Ignore public void perf2() throws InterruptedException { // ClientLifecycleFactory<TestClient> factory = // FailureDetectingClientLifecycleFactory.<TestClient>builder() // .build(); // // this.selector = RoundRobinLoadBalancer.create(source.lift(ClientCollector.create(factory))); // // final AtomicLong messageCount = new AtomicLong(0); // // Observable.range(1, 400) // .subscribe(new Action1<Integer>() { // @Override // public void call(final Integer id) { // Observable.interval(10, TimeUnit.MILLISECONDS, Schedulers.newThread()) // .subscribe(new Action1<Long>() { // @Override // public void call(final Long counter) { // Observable.create(selector) // .concatMap(new TrackingOperation(counter + "")) // .retry() // .subscribe(new Action1<String>() { // @Override // public void call(String t1) { // messageCount.incrementAndGet(); // //// LOG.info("{} - {} - {}", id, counter, t1); // } // }); // } // }); // } // }); // // Observable.interval(1, TimeUnit.SECONDS).subscribe(new Action1<Long>() { // private long previous = 0; // @Override // public void call(Long t1) { // long current = messageCount.get(); // LOG.info("Rate : " + (current - previous) + " Host count: " + selector.all().count().toBlocking().first()); // previous = current; // } // }); } }
2,200
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/Operations.java
package netflix.ocelli.client; import rx.Observable; import rx.functions.Func1; import java.net.SocketTimeoutException; import java.util.concurrent.TimeUnit; public class Operations { public static Func1<TestClient, Observable<String>> delayed(final long duration, final TimeUnit units) { return new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(final TestClient server) { return Observable .interval(duration, units) .first() .map(new Func1<Long, String>() { @Override public String call(Long t1) { return server + "-ok"; } }); } }; } public static Func1<TestClient, Observable<String>> timeout(final long duration, final TimeUnit units) { return new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(final TestClient server) { return Observable .interval(duration, units) .flatMap(new Func1<Long, Observable<String>>() { @Override public Observable<String> call(Long t1) { return Observable.error(new SocketTimeoutException("Timeout")); } }); } }; } public static TrackingOperation tracking(String response) { return new TrackingOperation(response); } }
2,201
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/Connects.java
package netflix.ocelli.client; import rx.Observable; import rx.functions.Func1; import java.util.concurrent.TimeUnit; public class Connects { public static Observable<Void> delay(final long timeout, final TimeUnit units) { return Observable.timer(timeout, units).ignoreElements().cast(Void.class); } public static Observable<Void> failure() { return Observable.error(new Exception("Connectus interruptus")); } public static Observable<Void> failure(final long timeout, final TimeUnit units) { return Observable.timer(timeout, units).concatMap(new Func1<Long, Observable<Void>>() { @Override public Observable<Void> call(Long t1) { return Observable.error(new Exception("Connectus interruptus")); } }); } public static Observable<Void> immediate() { return Observable.empty(); } public static Observable<Void> never() { return Observable.never(); } public static Observable<Void> error(Exception e) { return Observable.error(e); } }
2,202
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/TestClient.java
package netflix.ocelli.client; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicLong; import netflix.ocelli.util.RxUtil; import rx.Observable; import rx.Observer; import rx.functions.Func1; import rx.functions.Func2; public class TestClient { private final String id; private final Func1<TestClient, Observable<TestClient>> behavior; private final Observable<Void> connect; private final int concurrency = 10; private final Semaphore sem = new Semaphore(concurrency); private final Set<String> vips = new HashSet<String>(); private String rack; public static Func1<TestClient, Observable<String>> byVip() { return new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(TestClient t1) { return Observable.from(t1.vips).concatWith(Observable.just("*")); } }; } public static Func1<TestClient, Observable<String>> byRack() { return new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(TestClient t1) { return Observable.just(t1.rack); } }; } public static Func1<TestClient, Integer> byPendingRequestCount() { return new Func1<TestClient, Integer>() { @Override public Integer call(TestClient t1) { return t1.sem.availablePermits(); } }; } public static TestClient create(String id, Observable<Void> connect, Func1<TestClient, Observable<TestClient>> behavior) { return new TestClient(id, connect, behavior); } public static TestClient create(String id, Func1<TestClient, Observable<TestClient>> behavior) { return new TestClient(id, Connects.immediate(), behavior); } public static Func2<TestClient, String, Observable<String>> func() { return new Func2<TestClient, String,Observable<String>>() { @Override public Observable<String> call(TestClient client, String request) { return client.execute(new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(TestClient t1) { return Observable.just(t1.id()); } }); } }; } public TestClient(String id, Observable<Void> connect, Func1<TestClient, Observable<TestClient>> behavior) { this.id = id; this.behavior = behavior; this.connect = connect; } public Observable<Void> connect() { return connect; } public TestClient withVip(String vip) { this.vips.add(vip); return this; } public TestClient withRack(String rack) { this.rack = rack; return this; } public Set<String> vips() { return this.vips; } public String rack() { return this.rack; } public String id() { return this.id; } private AtomicLong executeCount = new AtomicLong(0); private AtomicLong onNextCount = new AtomicLong(0); private AtomicLong onCompletedCount = new AtomicLong(0); private AtomicLong onSubscribeCount = new AtomicLong(0); private AtomicLong onUnSubscribeCount = new AtomicLong(0); private AtomicLong onErrorCount = new AtomicLong(0); public long getExecuteCount() { return executeCount.get(); } public long getOnNextCount() { return onNextCount.get(); } public long getOnCompletedCount() { return onCompletedCount.get(); } public long getOnErrorCount() { return onErrorCount.get(); } public long getOnSubscribeCount() { return onSubscribeCount.get(); } public long getOnUnSubscribeCount() { return onUnSubscribeCount.get(); } public boolean hasError() { return onErrorCount.get() > 0; } public Observable<String> execute(Func1<TestClient, Observable<String>> operation) { this.executeCount.incrementAndGet(); return behavior.call(this) .doOnSubscribe(RxUtil.increment(onSubscribeCount)) .doOnSubscribe(RxUtil.acquire(sem)) .doOnUnsubscribe(RxUtil.increment(onUnSubscribeCount)) .concatMap(operation) .doOnEach(new Observer<String>() { @Override public void onCompleted() { onCompletedCount.incrementAndGet(); sem.release(); } @Override public void onError(Throwable e) { onErrorCount.incrementAndGet(); } @Override public void onNext(String t) { onNextCount.incrementAndGet(); } }); } public String toString() { return "Host[id=" + id + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; TestClient other = (TestClient) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
2,203
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/Behaviors.java
package netflix.ocelli.client; import netflix.ocelli.util.RxUtil; import rx.Observable; import rx.Scheduler; import rx.functions.Func1; import rx.schedulers.Schedulers; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class Behaviors { public static Func1<TestClient, Observable<TestClient>> delay(final long amount, final TimeUnit units) { return delay(amount, units, Schedulers.computation()); } public static Func1<TestClient, Observable<TestClient>> delay(final long amount, final TimeUnit units, final Scheduler scheduler) { return new Func1<TestClient, Observable<TestClient>>() { @Override public Observable<TestClient> call(final TestClient client) { return Observable .just(client) .delay(amount, units, scheduler) ; } }; } public static Func1<TestClient, Observable<TestClient>> immediate() { return new Func1<TestClient, Observable<TestClient>>() { @Override public Observable<TestClient> call(TestClient client) { return Observable .just(client); } }; } public static Func1<TestClient, Observable<TestClient>> failure(final long amount, final TimeUnit units) { return failure(amount, units, Schedulers.computation()); } public static Func1<TestClient, Observable<TestClient>> failure(final long amount, final TimeUnit units, final Scheduler scheduler) { return new Func1<TestClient, Observable<TestClient>>() { @Override public Observable<TestClient> call(TestClient client) { return Observable.timer(amount, units, scheduler) .flatMap(new Func1<Long, Observable<TestClient>>() { @Override public Observable<TestClient> call(Long t1) { return Observable.error(new Exception("SimulatedErrorBehavior")); } }); } }; } public static Func1<TestClient, Observable<TestClient>> failFirst(final int num) { return new Func1<TestClient, Observable<TestClient>>() { private int counter; @Override public Observable<TestClient> call(TestClient client) { if (counter++ < num) { return Observable.error(new Exception("Failure-" + counter)); } return Observable.just(client); } }; } public static Func1<TestClient, Observable<TestClient>> failure() { return new Func1<TestClient, Observable<TestClient>>() { @Override public Observable<TestClient> call(TestClient client) { return Observable .just(client) .concatWith(Observable.<TestClient>error(new Exception("SimulatedErrorBehavior"))); } }; } public static Func1<TestClient, Observable<TestClient>> degradation(final long initial, final long step, final TimeUnit units) { return new Func1<TestClient, Observable<TestClient>>() { private AtomicLong counter = new AtomicLong(0); @Override public Observable<TestClient> call(TestClient client) { return Observable .just(client) .delay(initial + counter.incrementAndGet() + step, units); } }; } public static Func1<TestClient, Observable<TestClient>> proportionalToLoad(final long baseline, final long step, final TimeUnit units) { return new Func1<TestClient, Observable<TestClient>>() { private AtomicLong counter = new AtomicLong(0); @Override public Observable<TestClient> call(TestClient client) { final long count = counter.incrementAndGet(); return Observable .just(client) .delay(baseline + count + step, units) .finallyDo(RxUtil.decrement(counter)); } }; } public static Func1<TestClient, Observable<TestClient>> empty() { return new Func1<TestClient, Observable<TestClient>>() { @Override public Observable<TestClient> call(TestClient t1) { return Observable.empty(); } }; } // public static poissonDelay() // public static gaussianDelay(); // public static gcPauses(); }
2,204
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/TrackingOperation.java
package netflix.ocelli.client; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.functions.Func1; import java.util.ArrayList; import java.util.List; public class TrackingOperation implements Func1<TestClient, Observable<String>> { private static final Logger LOG = LoggerFactory.getLogger(TrackingOperation.class); private final String response; private List<TestClient> servers = new ArrayList<TestClient>(); public TrackingOperation(String response) { this.response = response; } @Override public Observable<String> call(final TestClient client) { servers.add(client); return client.execute(new Func1<TestClient, Observable<String>>() { @Override public Observable<String> call(TestClient t1) { return Observable.just(response); } }); } public List<TestClient> getServers() { return servers; } }
2,205
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/ManualFailureDetector.java
package netflix.ocelli.client; import java.util.concurrent.ConcurrentMap; import rx.Observable; import rx.functions.Func1; import rx.subjects.PublishSubject; import com.google.common.collect.Maps; public class ManualFailureDetector implements Func1<TestClient, Observable<Throwable>> { private ConcurrentMap<TestClient, PublishSubject<Throwable>> clients = Maps.newConcurrentMap(); @Override public Observable<Throwable> call(TestClient client) { PublishSubject<Throwable> subject = PublishSubject.create(); PublishSubject<Throwable> prev = clients.putIfAbsent(client, subject); if (prev != null) { subject = prev; } return subject; } public PublishSubject<Throwable> get(TestClient client) { return clients.get(client); } }
2,206
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/ResponseObserver.java
package netflix.ocelli.client; import rx.Observer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class ResponseObserver implements Observer<String> { private volatile Throwable t; private volatile String response; private CountDownLatch latch = new CountDownLatch(1); @Override public void onCompleted() { latch.countDown(); } @Override public void onError(Throwable e) { this.t = e; latch.countDown(); } @Override public void onNext(String t) { this.response = t; } public String await(long duration, TimeUnit units) throws Throwable { latch.await(duration, units); if (this.t != null) throw this.t; return response; } public String get() { return response; } }
2,207
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/TestClientConnector.java
package netflix.ocelli.client; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.subjects.PublishSubject; public class TestClientConnector implements OnSubscribe<Void> { private final PublishSubject<TestClient> stream = PublishSubject.create(); private final TestClient client; public TestClientConnector(TestClient client) { this.client = client; } @Override public void call(Subscriber<? super Void> s) { s.onCompleted(); stream.onNext(client); } public Observable<TestClient> stream() { return stream; } }
2,208
0
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/test/java/netflix/ocelli/client/TestClientConnectorFactory.java
package netflix.ocelli.client; import java.util.concurrent.ConcurrentMap; import rx.Observable; import rx.functions.Func1; import com.google.common.collect.Maps; public class TestClientConnectorFactory implements Func1<TestClient, Observable<Void>> { private ConcurrentMap<TestClient, TestClientConnector> connectors = Maps.newConcurrentMap(); @Override public Observable<Void> call(TestClient client) { return Observable.create(get(client)); } public TestClientConnector get(TestClient client) { TestClientConnector connector = new TestClientConnector(client); TestClientConnector prev = connectors.putIfAbsent(client, connector); if (prev != null) { connector = prev; } return connector; } }
2,209
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceToNotification.java
package netflix.ocelli; import netflix.ocelli.InstanceToNotification.InstanceNotification; import rx.Notification; import rx.Observable; import rx.functions.Func1; public class InstanceToNotification<T> implements Func1<Instance<T>, Observable<InstanceNotification<T>>> { public static <T> InstanceToNotification<T> create() { return new InstanceToNotification<T>(); } public enum Kind { OnAdd, OnRemove } public static class InstanceNotification<T> { private final Instance<T> value; private final Kind kind; public InstanceNotification(Instance<T> instance, Kind kind) { this.value = instance; this.kind = kind; } public Kind getKind() { return kind; } public Instance<T> getInstance() { return value; } public String toString() { return "Notification[" + value + " " + kind + "]"; } } @Override public Observable<InstanceNotification<T>> call(final Instance<T> instance) { return Observable .just(new InstanceNotification<T>(instance, Kind.OnAdd)) .concatWith(instance.getLifecycle().materialize().map(new Func1<Notification<Void>, InstanceNotification<T>>() { @Override public InstanceNotification<T> call(Notification<Void> t1) { return new InstanceNotification<T>(instance, Kind.OnRemove); } })); } }
2,210
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceManager.java
package netflix.ocelli; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import rx.Observable; import rx.Subscriber; import rx.subjects.PublishSubject; /** * InstanceSubject can be used as a basic bridge from an add/remove host membership * paradigm to Ocelli's internal Instance with lifecycle representation of entity * membership in the load balancer. * * @see LoadBalancer * * @author elandau */ public class InstanceManager<T> extends Observable<Instance<T>> { private final PublishSubject<Instance<T>> subject; private final ConcurrentMap<T, CloseableInstance<T>> instances; public static <T> InstanceManager<T> create() { return new InstanceManager<T>(); } public InstanceManager() { this(PublishSubject.<Instance<T>>create(), new ConcurrentHashMap<T, CloseableInstance<T>>()); } private InstanceManager(final PublishSubject<Instance<T>> subject, final ConcurrentMap<T, CloseableInstance<T>> instances) { super(new OnSubscribe<Instance<T>>() { @Override public void call(Subscriber<? super Instance<T>> s) { // TODO: This is a very naive implementation that may have race conditions // whereby instances may be dropped Observable .from(new ArrayList<Instance<T>>(instances.values())) .concatWith(subject).subscribe(s); } }); this.subject = subject; this.instances = instances; } /** * Add an entity to the source, which feeds into a load balancer * @param t * @return */ public CloseableInstance<T> add(T t) { CloseableInstance<T> member = CloseableInstance.from(t); CloseableInstance<T> existing = instances.putIfAbsent(t, member); if (null == existing) { subject.onNext(member); return member; } return existing; } /** * Remove an entity from the source. If the entity exists it's lifecycle will * onComplete. * * @param t * @return */ public CloseableInstance<T> remove(T t) { CloseableInstance<T> member = instances.remove(t); if (member != null) { member.close(); } return member; } }
2,211
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/AbstractLoadBalancerEvent.java
package netflix.ocelli; @SuppressWarnings("rawtypes") public class AbstractLoadBalancerEvent <T extends Enum> implements LoadBalancerEvent<T> { protected final T name; protected final boolean isTimed; protected final boolean isError; protected AbstractLoadBalancerEvent(T name, boolean isTimed, boolean isError) { this.isTimed = isTimed; this.name = name; this.isError = isError; } @Override public T getType() { return name; } @Override public boolean isTimed() { return isTimed; } @Override public boolean isError() { return isError; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AbstractLoadBalancerEvent)) { return false; } AbstractLoadBalancerEvent that = (AbstractLoadBalancerEvent) o; if (isError != that.isError) { return false; } if (isTimed != that.isTimed) { return false; } if (name != that.name) { return false; } return true; } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + (isTimed ? 1 : 0); result = 31 * result + (isError ? 1 : 0); return result; } }
2,212
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/CloseableInstance.java
package netflix.ocelli; import rx.Observable; import rx.functions.Func1; import rx.subjects.BehaviorSubject; /** * An Instance that can be manually closed to indicate it is no longer * in existence and should be removed from the connection pool. * * @author elandau * * @param <T> */ public class CloseableInstance<T> extends Instance<T> { public static <T> CloseableInstance<T> from(T value) { return from(value, BehaviorSubject.<Void>create()); } public static <T> CloseableInstance<T> from(final T value, final BehaviorSubject<Void> lifecycle) { return new CloseableInstance<T>(value, lifecycle); } public static <T> Func1<T, CloseableInstance<T>> toMember() { return new Func1<T, CloseableInstance<T>>() { @Override public CloseableInstance<T> call(T t) { return from(t); } }; } private T value; private BehaviorSubject<Void> lifecycle; public CloseableInstance(T value, BehaviorSubject<Void> lifecycle) { this.value = value; this.lifecycle = lifecycle; } public String toString() { return "CloseableInstance[" + getValue() + "]"; } /** * onComplete the instance's lifecycle Observable<Void> */ public void close() { lifecycle.onCompleted(); } @Override public Observable<Void> getLifecycle() { return lifecycle; } @Override public T getValue() { return value; } }
2,213
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceEventListener.java
package netflix.ocelli; import java.util.concurrent.TimeUnit; public abstract class InstanceEventListener implements LoadBalancerEventListener<InstanceEvent<?>> { @Override public void onEvent(InstanceEvent<?> event, long duration, TimeUnit timeUnit, Throwable throwable, Object value) { switch ((InstanceEvent.EventType) event.getType()) { case ExecutionSuccess: onExecutionSuccess(duration, timeUnit); break; case ExecutionFailed: onExecutionFailed(duration, timeUnit, throwable); break; } } protected void onExecutionFailed(long duration, TimeUnit timeUnit, Throwable throwable) { // No Op } protected void onExecutionSuccess(long duration, TimeUnit timeUnit) { // No Op } @Override public void onCompleted() { // No Op } @Override public void onSubscribe() { // No Op } }
2,214
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/LoadBalancer.java
package netflix.ocelli; import netflix.ocelli.InstanceQuarantiner.IncarnationFactory; import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observable.Transformer; import rx.Scheduler; import rx.Subscriber; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subscriptions.Subscriptions; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * The LoadBalancer tracks lifecycle of entities and selects the next best entity based on plugable * algorithms such as round robin, choice of two, random, weighted, weighted random, etc. * * The LoadBalancer provides two usage modes, LoadBalancer#next and LoadBalancer#toObservable. * LoadBalancer#next selects the next best entity from the list of known entities based on the * load balancing algorithm. LoadBalancer#toObservable() creates an Observable that whenever * subscribed to will emit a single next best entity. Use toObservable() to compose with * Rx retry operators. * * Use one of the fromXXX methods to begin setting up a load balancer builder. The builder begins * with a source of entities that can be augmented with different topologies and quarantine strategies. * Finally the load balancer is created by calling build() with the desired algorithm. * * @author elandau * * @param <T> */ public class LoadBalancer<T> { public static class Builder<T> { private final Observable<Instance<T>> source; Builder(Observable<Instance<T>> source) { this.source = source; } /** * Topology to limit the number of active instances from the previously provided source. A * topology will track lifecycle of all source provided entities but only send a subset of these * entities to the load balancer. * * @param topology * @return */ public Builder<T> withTopology(Transformer<Instance<T>, Instance<T>> topology) { return new Builder<T>(source.compose(topology)); } /** * The quaratiner creates a new incarnation of each entity while letting the entity manage its * own lifecycle that onCompletes whenever the entity fails. A separate lifecycle (Observable<Void>) * is tracked for each incarnation with all incarnation subject to the original entities membership * lifecycle. Determination failure is deferred to the entity itself. * * @param factory * @param backoffStrategy * @param scheduler * @return */ public Builder<T> withQuarantiner(IncarnationFactory<T> factory, DelayStrategy backoffStrategy, Scheduler scheduler) { return new Builder<T>(source.flatMap(InstanceQuarantiner.create(factory, backoffStrategy, scheduler))); } /** * The quaratiner creates a new incarnation of each entity while letting the entity manage its * own lifecycle that onCompletes whenever the entity fails. A separate lifecycle (Observable<Void>) * is tracked for each incarnation with all incarnation subject to the original entities membership * lifecycle. Determination failure is deferred to the entity itself. * * @param factory * @param backoffStrategy * @param scheduler * @return */ public Builder<T> withQuarantiner(IncarnationFactory<T> factory, DelayStrategy backoffStrategy) { return new Builder<T>(source.flatMap(InstanceQuarantiner.create(factory, backoffStrategy, Schedulers.io()))); } /** * Convert the client from one type to another. Note that topology or failure detection will * still occur on the previous type * @param converter * @return */ public <S> Builder<S> convertTo(Func1<Instance<T>, Instance<S>> converter) { return new Builder<S>(source.map(converter)); } /** * Construct the default LoadBalancer using the round robin load balancing strategy * @return */ public LoadBalancer<T> buildDefault() { return new LoadBalancer<T>(source.compose(InstanceCollector.<T>create()), RoundRobinLoadBalancer.<T>create()); } /** * Finally create a load balancer given a specified strategy such as RoundRobin or ChoiceOfTwo * @param strategy * @return */ public LoadBalancer<T> build(LoadBalancerStrategy<T> strategy) { return new LoadBalancer<T>(source.compose(InstanceCollector.<T>create()), strategy); } /** * Finally create a load balancer given a specified strategy such as RoundRobin or ChoiceOfTwo * @param strategy * @return */ public LoadBalancer<T> build(LoadBalancerStrategy<T> strategy, InstanceCollector<T> instanceCollector) { return new LoadBalancer<T>(source.compose(instanceCollector), strategy); } } /** * Start the builder from a stream of Instance<T> where each emitted item represents an added * instances and the instance's Instance#getLifecycle() onCompletes when the instance is removed. * * The source can be managed manually via {@link InstanceManager} or may be tied directly to a hot * Observable from a host registry service such as Eureka. Note that the source may itself be a * composed Observable that includes transformations from one type to another. * * @param source * @return */ public static <T> Builder<T> fromSource(Observable<Instance<T>> source) { return new Builder<T>(source); } /** * Construct a load balancer builder from a stream of client snapshots. Note that * T must implement hashCode() and equals() so that a proper delta may determined * between successive snapshots. * * @param source * @return */ public static <T> Builder<T> fromSnapshotSource(Observable<List<T>> source) { return new Builder<T>(source.compose(new SnapshotToInstance<T>())); } /** * Construct a load balancer builder from a fixed list of clients * @param clients * @return */ public static <T> Builder<T> fromFixedSource(List<T> clients) { return fromSnapshotSource(Observable.just(clients)); } private final static Subscription IDLE_SUBSCRIPTION = Subscriptions.empty(); private final static Subscription SHUTDOWN_SUBSCRIPTION = Subscriptions.empty(); private final AtomicReference<Subscription> subscription; private volatile List<T> cache; private final AtomicBoolean isSubscribed = new AtomicBoolean(false); private final Observable<List<T>> source; private final LoadBalancerStrategy<T> algo; // Visible for testing only static <T> LoadBalancer<T> create(Observable<List<T>> source, LoadBalancerStrategy<T> algo) { return new LoadBalancer<T>(source, algo); } // Visible for testing only LoadBalancer(final Observable<List<T>> source, final LoadBalancerStrategy<T> algo) { this.source = source; this.subscription = new AtomicReference<Subscription>(IDLE_SUBSCRIPTION); this.cache = cache; this.algo = algo; } public Observable<T> toObservable() { return Observable.create(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> s) { try { s.onNext(next()); s.onCompleted(); } catch (Exception e) { s.onError(e); } } }); } /** * Select the next best T from the source. Will auto-subscribe to the source on the first * call to next(). shutdown() must be called to unsubscribe() from the source once the load * balancer is no longer used. * * @return * @throws NoSuchElementException */ public T next() throws NoSuchElementException { // Auto-subscribe if (isSubscribed.compareAndSet(false, true)) { Subscription s = source.subscribe(new Action1<List<T>>() { @Override public void call(List<T> t1) { cache = t1; } }); // Prevent subscription after shutdown if (!subscription.compareAndSet(IDLE_SUBSCRIPTION, s)) { s.unsubscribe(); } } List<T> latest = cache; if (latest == null) { throw new NoSuchElementException(); } return algo.choose(latest); } /** * Shut down the source subscription. This LoadBalancer may no longer be used * after shutdown is called. */ public void shutdown() { Subscription s = subscription.getAndSet(SHUTDOWN_SUBSCRIPTION); s.unsubscribe(); cache = null; } }
2,215
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/Instances.java
package netflix.ocelli; import rx.Observable; import rx.functions.Func1; public abstract class Instances { public static <T, S> Func1<Instance<T>, Instance<S>> transform(final Func1<T, S> func) { return new Func1<Instance<T>, Instance<S>>() { @Override public Instance<S> call(final Instance<T> primary) { final S s = func.call(primary.getValue()); return new Instance<S>() { @Override public Observable<Void> getLifecycle() { return primary.getLifecycle(); } @Override public S getValue() { return s; } @Override public String toString() { return "Instance[" + primary.getValue() + " -> " + getValue() + "]"; } }; } }; } }
2,216
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/LoadBalancerStrategy.java
package netflix.ocelli; import java.util.List; /** * Strategy that when given a list of candidates selects the single best one. * @author elandau * * @param <T> */ public interface LoadBalancerStrategy<T> { T choose(List<T> candidates); }
2,217
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/KeyedInstance.java
package netflix.ocelli; import rx.Observable; import rx.Observable.Transformer; import rx.functions.Func1; import rx.observables.GroupedObservable; public class KeyedInstance<K, T> { private final K key; private final Instance<T> member; KeyedInstance(K key, Instance<T> member) { this.key = key; this.member = member; } /** * Partition Members into multiple partitions based on a partition function. * It's possible for a member to exist in multiple partitions. Each partition * is a GroupedObservable of members for that partition alone. This stream can * be fed into a load balancer. * * Partitions are useful in the following use cases. * * 1. Hosts are grouped into VIPs where each VIP subset can service a certain subset of * requests. In the example below API's provided by vip1 can be serviced by Hosts 1,2,3 * whereas API's provied by vip2 can only be serviced by hosts 2 and 3. * * VIP : F(Host) -> O(vip) Multiple vips * * <vip1> Host1, Host2, Host3 * <vip2> Host2, Host3 * * 2. Shard or hash aware clients using consistent hashing (ex. Cassandra) or sharding (ex. EvCache) * will opt to send traffic only to nodes that can own the data. The partitioner function * will return the tokenRangeId or shardId for each host. Note that for replication factor of 1 * each shard will contain only 1 host while for higher replication factors each shard will contain * multiple hosts (equal to the number of shards) and that these hosts will overlap. * * <range1> Host1, Host2 * <range2> Host2, Host3 * <range3> Host3, Host4 * <range4> Host4, Host5 * * @author elandau * * @param <C> Client type * @param <K> The partition key */ public static <K, T> Transformer<Instance<T>, GroupedObservable<K, Instance<T>>> partitionBy(final Func1<T, Observable<K>> partitioner) { return new Transformer<Instance<T>, GroupedObservable<K, Instance<T>>>() { @Override public Observable<GroupedObservable<K, Instance<T>>> call(final Observable<Instance<T>> o) { return o .flatMap(new Func1<Instance<T>, Observable<KeyedInstance<K, T>>>() { @Override public Observable<KeyedInstance<K, T>> call(final Instance<T> member) { return partitioner .call(member.getValue()) .map(new Func1<K, KeyedInstance<K, T>>() { @Override public KeyedInstance<K, T> call(K key) { return new KeyedInstance<K, T>(key, member); } }); } }) .groupBy( new Func1<KeyedInstance<K, T>, K>() { @Override public K call(KeyedInstance<K, T> t1) { return t1.key; } }, new Func1<KeyedInstance<K, T>, Instance<T>>() { @Override public Instance<T> call(KeyedInstance<K, T> t1) { return t1.member; } }); } }; } }
2,218
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/Instance.java
package netflix.ocelli; import rx.Observable; /** * An {@link Instance} encapsulates a generic entity as well as its lifecycle. Lifecycle * is managed as an Observable<Void> that onCompletes when the entity is no longer in the * pool. This technique is also used to introduce topologies and quarantine logic for any * client type where each incarnation of the entity within the load balancer has its own * lifecycle. * * Instance is used internally in Ocelli and should not be created directly other than * for implementing specific entity registry solutions, such as Eureka. * * @see LoadBalancer * * @author elandau * * @param <T> */ public abstract class Instance<T> { public static <T> Instance<T> create(final T value, final Observable<Void> lifecycle) { return new Instance<T>() { @Override public Observable<Void> getLifecycle() { return lifecycle; } @Override public T getValue() { return value; } }; } /** * Return the lifecycle for this object * @return */ public abstract Observable<Void> getLifecycle(); /** * Return the instance object which could be an address or an actual client implementation * @return */ public abstract T getValue(); public String toString() { return "Instance[" + getValue() + "]"; } }
2,219
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceEvent.java
package netflix.ocelli; @SuppressWarnings("rawtypes") public class InstanceEvent<T extends Enum> extends AbstractLoadBalancerEvent<T> { public enum EventType implements MetricEventType { /* Connection specific events. */ ExecutionSuccess(true, false, Void.class), ExecutionFailed(true, true, Void.class), ; private final boolean isTimed; private final boolean isError; private final Class<?> optionalDataType; EventType(boolean isTimed, boolean isError, Class<?> optionalDataType) { this.isTimed = isTimed; this.isError = isError; this.optionalDataType = optionalDataType; } @Override public boolean isTimed() { return isTimed; } @Override public boolean isError() { return isError; } @Override public Class<?> getOptionalDataType() { return optionalDataType; } } public static final InstanceEvent<EventType> EXECUTION_SUCCESS = from(EventType.ExecutionSuccess); public static final InstanceEvent<EventType> EXECUTION_FAILED = from(EventType.ExecutionFailed); /*Always refer to as constants*/protected InstanceEvent(T name, boolean isTimed, boolean isError) { super(name, isTimed, isError); } private static InstanceEvent<EventType> from(EventType type) { return new InstanceEvent<EventType>(type, type.isTimed(), type.isError()); } }
2,220
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/LoadBalancerEventListener.java
package netflix.ocelli; import java.util.concurrent.TimeUnit; public interface LoadBalancerEventListener <E extends LoadBalancerEvent<?>> { int NO_DURATION = -1; Object NO_VALUE = null; Throwable NO_ERROR = null; TimeUnit NO_TIME_UNIT = null; /** * Event callback for any {@link MetricsEvent}. The parameters passed are all the contextual information possible for * any event. There presence or absence will depend on the type of event. * * @param event Event for which this callback has been invoked. This will never be {@code null} * @param duration If the passed event is {@link MetricsEvent#isTimed()} then the actual duration, else * {@link #NO_DURATION} * @param timeUnit The time unit for the duration, if exists, else {@link #NO_TIME_UNIT} * @param throwable If the passed event is {@link MetricsEvent#isError()} then the cause of the error, else * {@link #NO_ERROR} * @param value If the passed event requires custom object to be passed, then that object, else {@link #NO_VALUE} */ void onEvent(E event, long duration, TimeUnit timeUnit, Throwable throwable, Object value); /** * Marks the end of all event callbacks. No methods on this listener will ever be called once this method is called. */ void onCompleted(); /** * A callback when this listener is subscribed to a {@link MetricEventsPublisher}. */ void onSubscribe(); }
2,221
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/LoadBalancerEvent.java
package netflix.ocelli; @SuppressWarnings("rawtypes") public interface LoadBalancerEvent <T extends Enum> { T getType(); boolean isTimed(); boolean isError(); /** * This interface is a "best-practice" rather than a contract as a more strongly required contract is for the event * type to be an enum. */ interface MetricEventType { boolean isTimed(); boolean isError(); Class<?> getOptionalDataType(); } }
2,222
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/SnapshotToInstance.java
package netflix.ocelli; import rx.Observable; import rx.Observable.Transformer; import rx.functions.Func1; import rx.functions.Func2; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Utility class to convert a full snapshot of pool members, T, to an Observable<Instance<T>> * by diffing the new list with the last list. Any {@link Instance} that has been removed * will have it's lifecycle terminated. * * @author elandau * * @param <T> */ public class SnapshotToInstance<T> implements Transformer<List<T>, Instance<T>> { public class State { final Map<T, CloseableInstance<T>> members; final List<Instance<T>> newInstances; public State() { members = new HashMap<T, CloseableInstance<T>>(); newInstances = Collections.emptyList(); } public State(State toCopy) { members = new HashMap<T, CloseableInstance<T>>(toCopy.members); newInstances = new ArrayList<>(); } } @Override public Observable<Instance<T>> call(Observable<List<T>> snapshots) { return snapshots.scan(new State(), new Func2<State, List<T>, State>() { @Override public State call(State state, List<T> instances) { State newState = new State(state); Set<T> keysToRemove = new HashSet<T>(newState.members.keySet()); for (T ii : instances) { keysToRemove.remove(ii); if (!newState.members.containsKey(ii)) { CloseableInstance<T> member = CloseableInstance.from(ii); newState.members.put(ii, member); newState.newInstances.add(member); } } for (T tKey : keysToRemove) { CloseableInstance<T> removed = newState.members.remove(tKey); if (null != removed) { removed.close(); } } return newState; } }).concatMap(new Func1<State, Observable<Instance<T>>>() { @Override public Observable<Instance<T>> call(State state) { return Observable.from(state.newInstances); } }); } }
2,223
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/Host.java
package netflix.ocelli; import java.util.Map; /** * A class for expressing a host. * * @author Nitesh Kant */ public class Host { private String hostName; private int port; private Map<String, String> attributes; public Host(String hostName, int port) { this.hostName = hostName; this.port = port; } public Host(String hostName, int port, Map<String, String> attributes) { this.hostName = hostName; this.port = port; this.attributes = attributes; } public String getHostName() { return hostName; } public int getPort() { return port; } public String getAttributes(String key, String defaultValue) { if (attributes != null && attributes.containsKey(key)) { return attributes.get(key); } return defaultValue; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Host)) { return false; } Host host = (Host) o; return port == host.port && !(hostName != null ? !hostName.equals(host.hostName) : host.hostName != null); } @Override public int hashCode() { int result = hostName != null ? hostName.hashCode() : 0; result = 31 * result + port; return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Host [") .append("hostName=").append(hostName) .append(", port=").append(port); if (attributes != null && attributes.isEmpty()) { sb.append(", attr=").append(attributes); } return sb.append("]").toString(); } }
2,224
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/DelayStrategy.java
package netflix.ocelli; /** * Strategy to determine the backoff delay after N consecutive failures. * * @author elandau * */ public interface DelayStrategy { long get(int consecutiveFailures); }
2,225
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceQuarantiner.java
package netflix.ocelli; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Scheduler; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.BehaviorSubject; /** * To be used as a flatMap on a stream of Instance<T> the quarantiner converts the Instance<T> * to an Observable<Instance<T>> where each emitted item represents an active Instance<T> based * on a failure detector specific to T. When failure is detected the emitted instance's lifecycle * will be terminated and a new Instance<T> based on the original Instance<T> (passed to the flatMap) * will be emitted after a configurable quarantine time. * * @author elandau * * @param <T> */ public class InstanceQuarantiner<T> implements Func1<Instance<T>, Observable<Instance<T>>> { private static final Logger LOG = LoggerFactory.getLogger(InstanceQuarantiner.class); private final IncarnationFactory<T> factory; private final DelayStrategy backoffStrategy; private final Scheduler scheduler; /** * Factory for creating a new incarnation of a server based on the primary incarnation. * * @author elandau * * @param <T> */ public interface IncarnationFactory<T> { /** * * @param value The primary client instance * @param listener Listener to invoke with success and failure events * @param lifecycle Composite of this incarnations failure detected lifecycle and membership * @return */ public T create(T value, InstanceEventListener listener, Observable<Void> lifecycle); } public interface ShutdownAction<T> { void shutdown(T object); } /** * Create a new InstanceQuaratiner * * @param failureActionSetter Function to call to associate the failure callback with a T */ public static <T> InstanceQuarantiner<T> create( IncarnationFactory<T> factory, DelayStrategy backoffStrategy, Scheduler scheduler) { return new InstanceQuarantiner<T>(factory, backoffStrategy, scheduler); } public InstanceQuarantiner(IncarnationFactory<T> factory, DelayStrategy backoffStrategy, Scheduler scheduler) { this.factory = factory; this.scheduler = scheduler; this.backoffStrategy = backoffStrategy; } /** * Metrics for a single incarnation of a client type */ static class IncarnationMetrics extends InstanceEventListener { final Action0 shutdownAction; final AtomicBoolean failed = new AtomicBoolean(false); final InstanceMetrics parent; public IncarnationMetrics(InstanceMetrics parent, Action0 shutdownAction) { this.parent = parent; this.shutdownAction = shutdownAction; } @Override protected void onExecutionFailed(long duration, TimeUnit timeUnit, Throwable throwable) { if (failed.compareAndSet(false, true)) { parent.onExecutionFailed(duration, timeUnit, throwable); shutdownAction.call(); } } @Override protected void onExecutionSuccess(long duration, TimeUnit timeUnit) { if (!failed.get()) { parent.onExecutionSuccess(duration, timeUnit); } } } /** * Metrics shared across all incarnations of a client type */ static class InstanceMetrics extends InstanceEventListener { private AtomicInteger consecutiveFailures = new AtomicInteger(); @Override protected void onExecutionFailed(long duration, TimeUnit timeUnit, Throwable throwable) { consecutiveFailures.incrementAndGet(); } @Override protected void onExecutionSuccess(long duration, TimeUnit timeUnit) { consecutiveFailures.set(0); } } @Override public Observable<Instance<T>> call(final Instance<T> primaryInstance) { return Observable.create(new OnSubscribe<Instance<T>>() { @Override public void call(final Subscriber<? super Instance<T>> s) { final InstanceMetrics instanceMetrics = new InstanceMetrics(); final AtomicBoolean first = new AtomicBoolean(true); s.add(Observable .defer(new Func0<Observable<Instance<T>>>() { @Override public Observable<Instance<T>> call() { LOG.info("Creating next incarnation of '{}'", primaryInstance.getValue()); final BehaviorSubject<Void> incarnationLifecycle = BehaviorSubject.create(); final IncarnationMetrics metrics = new IncarnationMetrics( instanceMetrics, // TODO: Make this a policy new Action0() { @Override public void call() { incarnationLifecycle.onCompleted(); } }); // The incarnation lifecycle is tied to the main instance membership as well as failure // detection // TODO: Can we do this without cache? final Observable<Void> lifecycle = incarnationLifecycle.ambWith(primaryInstance.getLifecycle()).cache(); Observable<Instance<T>> o = Observable.just(Instance.create(factory.create(primaryInstance.getValue(), metrics, lifecycle), lifecycle)); if (!first.compareAndSet(true, false)) { long delay = backoffStrategy.get(instanceMetrics.consecutiveFailures.get()); o = o.delaySubscription(delay, TimeUnit.MILLISECONDS, scheduler); } return o; } }) .concatMap(new Func1<Instance<T>, Observable<Void>>() { @Override public Observable<Void> call(final Instance<T> instance) { s.onNext(instance); return instance.getLifecycle(); } }) .repeat() .takeUntil(primaryInstance.getLifecycle()) .subscribe()); } }); } }
2,226
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/InstanceCollector.java
package netflix.ocelli; import rx.Observable; import rx.Observable.Operator; import rx.Observable.Transformer; import rx.Subscriber; import rx.Subscription; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.subscriptions.CompositeSubscription; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * From a list of Instance<T> maintain a List of active Instance<T>. Add when T is up and remove * when T is either down or Instance failed or completed. * * @author elandau * * @param <T> */ public class InstanceCollector<T> implements Transformer<Instance<T>, List<T>> { private final Func0<Map<T, Subscription>> instanceStoreFactory; private InstanceCollector(Func0<Map<T, Subscription>> instanceStoreFactory) { this.instanceStoreFactory = instanceStoreFactory; } public static <T> InstanceCollector<T> create() { return create(new Func0<Map<T, Subscription>>() { @Override public Map<T, Subscription> call() { return new ConcurrentHashMap<T, Subscription>(); } }); } public static <T> InstanceCollector<T> create(Func0<Map<T, Subscription>> instanceStoreFactory) { return new InstanceCollector<T>(instanceStoreFactory); } // TODO: Move this into a utils package public static <K, T> Action1<Instance<T>> toMap(final Map<K, T> map, final Func1<T, K> keyFunc) { return new Action1<Instance<T>>() { @Override public void call(final Instance<T> t1) { map.put(keyFunc.call(t1.getValue()), t1.getValue()); t1.getLifecycle().doOnCompleted(new Action0() { @Override public void call() { map.remove(t1.getValue()); } }); } }; } @Override public Observable<List<T>> call(Observable<Instance<T>> o) { return o.lift(new Operator<Set<T>, Instance<T>>() { @Override public Subscriber<? super Instance<T>> call(final Subscriber<? super Set<T>> s) { final CompositeSubscription cs = new CompositeSubscription(); final Map<T, Subscription> instances = instanceStoreFactory.call(); s.add(cs); return new Subscriber<Instance<T>>() { @Override public void onCompleted() { s.onCompleted(); } @Override public void onError(Throwable e) { s.onError(e); } @Override public void onNext(final Instance<T> t) { Subscription sub = t.getLifecycle().doOnCompleted(new Action0() { @Override public void call() { Subscription sub = instances.remove(t.getValue()); cs.remove(sub); s.onNext(instances.keySet()); } }).subscribe(); instances.put(t.getValue(), sub); s.onNext(instances.keySet()); } }; } }) .map(new Func1<Set<T>, List<T>>() { @Override public List<T> call(Set<T> instances) { ArrayList<T> snapshot = new ArrayList<T>(instances.size()); snapshot.addAll(instances); // Make an immutable copy of the list return Collections.unmodifiableList(snapshot); } }); } }
2,227
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/SingleMetric.java
package netflix.ocelli.util; /** * Contract for tracking a single Metric. For example, a SingleMetric may track an exponential moving * average where add() is called for each new sample and get() is called to get the current * exponential moving average * * @author elandau * * @param <T> */ public interface SingleMetric<T> { /** * Add a new sample * @param sample */ void add(T sample); /** * Reset the value to default */ void reset(); /** * @return The latest calculated value */ T get(); }
2,228
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/RpsEstimator.java
package netflix.ocelli.util; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class RpsEstimator { private static final double MICROS_PER_SECOND = TimeUnit.MICROSECONDS.convert(1, TimeUnit.SECONDS); private AtomicLong sampleCounter = new AtomicLong(); private AtomicLong lastCheckpoint = new AtomicLong(); private volatile long estimatedRps; private volatile long nextCheckpoint; private volatile long lastFlushTime = System.nanoTime(); public static class State { long count; long rps; } public RpsEstimator(long initialRps) { this.estimatedRps = 0; this.nextCheckpoint = 1000; } public State addSample() { long counter = sampleCounter.incrementAndGet(); if (counter - lastCheckpoint.get() == nextCheckpoint) { long count = counter - lastCheckpoint.get(); synchronized (this) { lastCheckpoint.set(counter); long now = System.nanoTime(); estimatedRps = (long) (count * MICROS_PER_SECOND / (lastFlushTime - now)); lastFlushTime = now; nextCheckpoint = estimatedRps; State state = new State(); state.count = count; state.rps = estimatedRps; return state; } } else if (counter - lastCheckpoint.get() > 2 * estimatedRps) { nextCheckpoint = (counter - lastCheckpoint.get()) * 2; } return null; } long getSampleCount() { return sampleCounter.get(); } long getRps() { return estimatedRps; } }
2,229
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/RxUtil.java
package netflix.ocelli.util; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observable.Operator; import rx.Observer; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.FuncN; import rx.subscriptions.Subscriptions; public class RxUtil { private static final Logger LOG = LoggerFactory.getLogger(RxUtil.class); private interface Action01<T> extends Action1<T>, Action0 {} /** * Increment a stateful counter outside the stream. * * {code * <pre> * observable * .doOnNext(RxUtil.increment(mycounter)) * </pre> * } * * @param metric * @return */ public static <T> Action01<T> increment(final AtomicLong metric) { return new Action01<T>() { @Override public void call(T t1) { metric.incrementAndGet(); } @Override public void call() { metric.incrementAndGet(); } }; } public static <T> Action01<T> increment(final AtomicInteger metric) { return new Action01<T>() { @Override public void call(T t1) { metric.incrementAndGet(); } @Override public void call() { metric.incrementAndGet(); } }; } /** * Decrement a stateful counter outside the stream. * * {code * <pre> * observable * .doOnNext(RxUtil.decrement(mycounter)) * </pre> * } * * @param metric * @return */ public static <T> Action01<T> decrement(final AtomicLong metric) { return new Action01<T>() { @Override public void call(T t1) { metric.decrementAndGet(); } @Override public void call() { metric.decrementAndGet(); } }; } /** * Trace each item emitted on the stream with a given label. * Will log the file and line where the trace occurs. * * {code * <pre> * observable * .doOnNext(RxUtil.trace("next: ")) * </pre> * } * * @param label */ public static <T> Action01<T> trace(String label) { final String caption = getSourceLabel(label); final AtomicLong counter = new AtomicLong(); return new Action01<T>() { @Override public void call(T t1) { LOG.trace("{} ({}) {}", caption, counter.incrementAndGet(), t1); } @Override public void call() { LOG.trace("{} ({}) {}", caption, counter.incrementAndGet()); } }; } /** * Log info line for each item emitted on the stream with a given label. * Will log the file and line where the trace occurs. * * {code * <pre> * observable * .doOnNext(RxUtil.info("next: ")) * </pre> * } * * @param label */ public static <T> Action01<T> info(String label) { final String caption = getSourceLabel(label); final AtomicLong counter = new AtomicLong(); return new Action01<T>() { @Override public void call(T t1) { LOG.info("{} ({}) {}", caption, counter.incrementAndGet(), t1); } @Override public void call() { LOG.info("{} ({})", caption, counter.incrementAndGet()); } }; } /** * Action to sleep in the middle of a pipeline. This is normally used in tests to * introduce an artifical delay. * @param timeout * @param units * @return */ public static <T> Action01<T> sleep(final long timeout, final TimeUnit units) { return new Action01<T>() { @Override public void call(T t1) { call(); } @Override public void call() { try { units.sleep(timeout); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } }; } /** * Decrement a countdown latch for each item * * {code * <pre> * observable * .doOnNext(RxUtil.decrement(latch)) * </pre> * } */ public static <T> Action01<T> countdown(final CountDownLatch latch) { return new Action01<T>() { @Override public void call(T t1) { latch.countDown(); } @Override public void call() { latch.countDown(); } }; } /** * Log the request rate at the given interval. * * {code * <pre> * observable * .lift(RxUtil.rate("items per 10 seconds", 10, TimeUnit.SECONDS)) * </pre> * } * * @param label * @param interval * @param units */ public static String[] TIME_UNIT = {"ns", "us", "ms", "s", "m", "h", "d"}; public static <T> Operator<T, T> rate(final String label, final long interval, final TimeUnit units) { final String caption = getSourceLabel(label); return new Operator<T, T>() { @Override public Subscriber<? super T> call(final Subscriber<? super T> child) { final AtomicLong counter = new AtomicLong(); final String sUnits = (interval == 1) ? TIME_UNIT[units.ordinal()] : String.format("({} {})", interval, TIME_UNIT[units.ordinal()]); child.add( Observable.interval(interval, units) .subscribe(new Action1<Long>() { @Override public void call(Long t1) { LOG.info("{} {} / {}", caption, counter.getAndSet(0), sUnits); } })); return new Subscriber<T>(child) { @Override public void onCompleted() { if (!isUnsubscribed()) child.onCompleted(); } @Override public void onError(Throwable e) { if (!isUnsubscribed()) child.onError(e); } @Override public void onNext(T t) { counter.incrementAndGet(); if (!isUnsubscribed()) child.onNext(t); } }; } }; } /** * Log error line when an error occurs. * Will log the file and line where the trace occurs. * * {code * <pre> * observable * .doOnError(RxUtil.error("Stream broke")) * </pre> * } * * @param label */ public static Action1<Throwable> error(String label) { final String caption = getSourceLabel(label); final AtomicLong counter = new AtomicLong(); return new Action1<Throwable>() { @Override public void call(Throwable t1) { LOG.error("{} ({}) {}", caption, counter.incrementAndGet(), t1); } }; } /** * Log a warning line when an error occurs. * Will log the file and line where the trace occurs. * * {code * <pre> * observable * .doOnError(RxUtil.warn("Stream broke")) * </pre> * } * * @param label */ public static Action1<Throwable> warn(String label) { final String caption = getSourceLabel(label); final AtomicLong counter = new AtomicLong(); return new Action1<Throwable>() { @Override public void call(Throwable t1) { LOG.warn("{} ({}) {}", caption, counter.incrementAndGet(), t1); } }; } public static <T> Func1<List<T>, Boolean> listNotEmpty() { return new Func1<List<T>, Boolean>() { @Override public Boolean call(List<T> t1) { return !t1.isEmpty(); } }; } /** * Filter out any collection that is empty. * * {code * <pre> * observable * .filter(RxUtil.collectionNotEmpty()) * </pre> * } */ public static <T> Func1<Collection<T>, Boolean> collectionNotEmpty() { return new Func1<Collection<T>, Boolean>() { @Override public Boolean call(Collection<T> t1) { return !t1.isEmpty(); } }; } /** * Operator that acts as a pass through. Use this when you want the operator * to be interchangable with the default implementation being a single passthrough. * * {code * <pre> * Operator<T,T> customOperator = RxUtil.passthrough(); * observable * .lift(customOperator) * </pre> * } */ public static <T> Operator<T, T> passthrough() { return new Operator<T, T>() { @Override public Subscriber<? super T> call(final Subscriber<? super T> o) { return o; } }; } /** * Cache all items and emit a single LinkedHashSet with all data when onComplete is called * @return */ public static <T> Operator<Set<T>, T> toLinkedHashSet() { return new Operator<Set<T>, T>() { @Override public Subscriber<? super T> call(final Subscriber<? super Set<T>> o) { final Set<T> set = new LinkedHashSet<T>(); return new Subscriber<T>() { @Override public void onCompleted() { o.onNext(set); o.onCompleted(); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onNext(T t) { set.add(t); } }; } }; } private static String getSourceLabel(String label) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); StackTraceElement element = stack[3]; return "(" + element.getFileName() + ":" + element.getLineNumber() + ") " + label; } /** * Filter that returns true whenever an external state is true * {code * <pre> * final AtomicBoolean condition = new AtomicBoolean(); * * observable * .filter(RxUtil.isTrue(condition)) * </pre> * } * @param condition */ public static <T> Func1<T, Boolean> isTrue(final AtomicBoolean condition) { return new Func1<T, Boolean>() { @Override public Boolean call(T t1) { return condition.get(); } }; } /** * Filter that returns true whenever an external state is false * {code * <pre> * final AtomicBoolean condition = new AtomicBoolean(); * * observable * .filter(RxUtil.isTrue(condition)) * </pre> * } * @param condition */ public static <T> Func1<T, Boolean> isFalse(final AtomicBoolean condition) { return new Func1<T, Boolean>() { @Override public Boolean call(T t1) { return !condition.get(); } }; } /** * Filter that returns true whenever a CAS operation on an external static * AtomicBoolean succeeds * {code * <pre> * final AtomicBoolean condition = new AtomicBoolean(); * * observable * .filter(RxUtil.isTrue(condition)) * </pre> * } * @param condition */ public static Func1<? super Long, Boolean> compareAndSet(final AtomicBoolean condition, final boolean expect, final boolean value) { return new Func1<Long, Boolean>() { @Override public Boolean call(Long t1) { return condition.compareAndSet(expect, value); } }; } /** * Simple operation that sets an external condition for each emitted item * {code * <pre> * final AtomicBoolean condition = new AtomicBoolean(); * * observable * .doOnNext(RxUtil.set(condition, true)) * </pre> * } * @param condition * @param value * @return */ public static <T> Action01<T> set(final AtomicBoolean condition, final boolean value) { return new Action01<T>() { @Override public void call(T t1) { condition.set(value); } @Override public void call() { condition.set(value); } }; } /** * Filter that always returns a constant value. Use this to create a default filter * when the filter implementation is plugable. * * @param constant * @return */ public static <T> Func1<T, Boolean> constantFilter(final boolean constant) { return new Func1<T, Boolean>() { @Override public Boolean call(T t1) { return constant; } }; } /** * Observable factory to be used with {@link Observable.defer()} which will round robin * through a list of {@link Observable}'s so that each subscribe() returns the next * {@link Observable} in the list. * * @param sources * @return */ public static <T> Func0<Observable<T>> roundRobinObservableFactory(@SuppressWarnings("unchecked") final Observable<T> ... sources) { return new Func0<Observable<T>>() { final AtomicInteger count = new AtomicInteger(); @Override public Observable<T> call() { int index = count.getAndIncrement() % sources.length; return sources[index]; } }; } public static <T> Observable<Observable<T>> onSubscribeChooseNext(final Observable<T> ... sources) { return Observable.create(new OnSubscribe<Observable<T>>() { private AtomicInteger count = new AtomicInteger(); @Override public void call(Subscriber<? super Observable<T>> t1) { int index = count.getAndIncrement(); if (index < sources.length) { t1.onNext(sources[index]); } t1.onCompleted(); } }); } /** * Given a list of observables that emit a boolean condition AND all conditions whenever * any condition changes and emit the resulting condition when the final condition changes. * @param sources * @return */ public static Observable<Boolean> conditionAnder(List<Observable<Boolean>> sources) { return Observable.combineLatest(sources, new FuncN<Observable<Boolean>>() { @Override public Observable<Boolean> call(Object... args) { return Observable.from(args).cast(Boolean.class).firstOrDefault(true, new Func1<Boolean, Boolean>() { @Override public Boolean call(Boolean status) { return !status; } }); } }) .flatMap(new Func1<Observable<Boolean>, Observable<Boolean>>() { @Override public Observable<Boolean> call(Observable<Boolean> t1) { return t1; } }) .distinctUntilChanged(); } /** * Trace all parts of an observable's state and especially when * notifications are discarded due to being unsubscribed. This should * only used for debugging purposes. * @param label * @return */ public static <T> Operator<T, T> uberTracer(String label) { final String caption = getSourceLabel(label); return new Operator<T, T>() { @Override public Subscriber<? super T> call(final Subscriber<? super T> s) { s.add(Subscriptions.create(new Action0() { @Override public void call() { LOG.info("{} unsubscribing", caption); } })); return new Subscriber<T>(s) { private AtomicLong completedCounter = new AtomicLong(); private AtomicLong nextCounter = new AtomicLong(); private AtomicLong errorCounter = new AtomicLong(); @Override public void onCompleted() { if (!s.isUnsubscribed()) { s.onCompleted(); } else { LOG.info("{} ({}) Discarding onCompleted", caption, completedCounter.incrementAndGet()); } } @Override public void onError(Throwable e) { if (!s.isUnsubscribed()) { s.onCompleted(); } else { LOG.info("{} ({}) Discarding onError", caption, errorCounter.incrementAndGet()); } } @Override public void onNext(T t) { if (!s.isUnsubscribed()) { s.onNext(t); } else { LOG.info("{} ({}) Discarding onNext", caption, nextCounter.incrementAndGet()); } } }; } }; } /** * Utility to call an action when any event occurs regardless that event * @param action * @return */ public static <T> Observer<T> onAny(final Action0 action) { return new Observer<T>() { @Override public void onCompleted() { action.call(); } @Override public void onError(Throwable e) { action.call(); } @Override public void onNext(T t) { action.call(); } } ; } public static <T> Action01<T> acquire(final Semaphore sem) { return new Action01<T>() { @Override public void call(T t1) { call(); } @Override public void call() { try { sem.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; } public static <T> Action01<T> release(final Semaphore sem) { return new Action01<T>() { @Override public void call(T t1) { call(); } @Override public void call() { sem.release(); } }; } public static <T> Action1<T> set(final AtomicReference<T> ref) { return new Action1<T>() { @Override public void call(T t1) { ref.set(t1); } }; } }
2,230
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/Stopwatch.java
package netflix.ocelli.util; import java.util.concurrent.TimeUnit; /** * A stopwatch starts counting when the object is created and can be used * to track how long operations take. For simplicity this contract does * not provide a mechanism to stop, restart, or clear the stopwatch. Instead * it just returns the elapsed time since the object was created. * * @author elandau * @see {@link Stopwatches} */ public interface Stopwatch { /** * Elapsed time since object was created. * @param units * @return */ long elapsed(TimeUnit units); }
2,231
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/AtomicDouble.java
package netflix.ocelli.util; import java.util.concurrent.atomic.AtomicLong; /** * Utility class to track an atomic double for use in non blocking algorithms (@see ExponentialAverage) * * @author elandau */ public class AtomicDouble { private AtomicLong bits; public AtomicDouble() { this(0f); } public AtomicDouble(double initialValue) { bits = new AtomicLong(Double.doubleToLongBits(initialValue)); } public final boolean compareAndSet(double expect, double update) { return bits.compareAndSet(Double.doubleToLongBits(expect), Double.doubleToLongBits(update)); } public final void set(double newValue) { bits.set(Double.doubleToLongBits(newValue)); } public final double get() { return Double.longBitsToDouble(bits.get()); } public final double getAndSet(double newValue) { return Double.longBitsToDouble(bits.getAndSet(Double.doubleToLongBits(newValue))); } public final boolean weakCompareAndSet(double expect, double update) { return bits.weakCompareAndSet(Double.doubleToLongBits(expect), Double.doubleToLongBits(update)); } public double doubleValue() { return (double) get(); } public int intValue() { return (int) get(); } public long longValue() { return (long) get(); } }
2,232
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/StateMachine.java
package netflix.ocelli.util; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Action2; import rx.functions.Func0; import rx.functions.Func1; import rx.subjects.PublishSubject; public class StateMachine<T, E> implements Action1<E> { private static final Logger LOG = LoggerFactory.getLogger(StateMachine.class); public static class State<T, E> { private String name; private Func1<T, Observable<E>> enter; private Func1<T, Observable<E>> exit; private Map<E, State<T, E>> transitions = new HashMap<E, State<T, E>>(); private Set<E> ignore = new HashSet<E>(); public static <T, E> State<T, E> create(String name) { return new State<T, E>(name); } public State(String name) { this.name = name; } public State<T, E> onEnter(Func1<T, Observable<E>> func) { this.enter = func; return this; } public State<T, E> onExit(Func1<T, Observable<E>> func) { this.exit = func; return this; } public State<T, E> transition(E event, State<T, E> state) { transitions.put(event, state); return this; } public State<T, E> ignore(E event) { ignore.add(event); return this; } Observable<E> enter(T context) { if (enter != null) return enter.call(context); return Observable.empty(); } Observable<E> exit(T context) { if (exit != null) exit.call(context); return Observable.empty(); } State<T, E> next(E event) { return transitions.get(event); } public String toString() { return name; } } private volatile State<T, E> state; private final T context; private final PublishSubject<E> events = PublishSubject.create(); public static <T, E> StateMachine<T, E> create(T context, State<T, E> initial) { return new StateMachine<T, E>(context, initial); } public StateMachine(T context, State<T, E> initial) { this.state = initial; this.context = context; } public Observable<Void> start() { return Observable.create(new OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> sub) { sub.add(events.collect(new Func0<T>() { @Override public T call() { return context; } }, new Action2<T, E>() { @Override public void call(T context, E event) { LOG.trace("{} : {}({})", context, state, event); final State<T, E> next = state.next(event); if (next != null) { state.exit(context); state = next; next.enter(context).subscribe(StateMachine.this); } else if (!state.ignore.contains(event)) { LOG.warn("Unexpected event {} in state {} for {} ", event, state, context); } } }) .subscribe()); state.enter(context); } }); } @Override public void call(E event) { events.onNext(event); } public State<T, E> getState() { return state; } public T getContext() { return context; } }
2,233
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/util/RandomBlockingQueue.java
package netflix.ocelli.util; import java.util.AbstractQueue; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class RandomBlockingQueue<E> extends AbstractQueue<E> { /** The queued items */ private List<E> items = new ArrayList<E>(); private Random rand = new Random(); /** Main lock guarding all access */ final ReentrantLock lock; /** Condition for waiting takes */ private final Condition notEmpty; public RandomBlockingQueue() { this(false); } public RandomBlockingQueue(boolean fair) { lock = new ReentrantLock(fair); notEmpty = lock.newCondition(); } private static void checkNotNull(Object v) { if (v == null) throw new NullPointerException(); } @SuppressWarnings("unchecked") static <E> E cast(Object item) { return (E) item; } /** * Inserts element into array * Call only when holding lock. */ private void insert(E x) { if (items.size() == 0) { items.add(x); } else { int index = rand.nextInt(items.size()); items.add(items.get(index)); items.set(index, x); } notEmpty.signal(); } /** * Extracts random element. Moves the last element to the spot where the random * element was removed. This avoids having to shift all the items in the array. * * Call only when holding lock. */ private E extract() { return items.remove(items.size()-1); } public boolean offer(E e) { checkNotNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { insert(e); return true; } finally { lock.unlock(); } } public void put(E e) throws InterruptedException { offer(e); } public boolean offer(E e, long timeout, TimeUnit unit) { offer(e); return true; } public E poll() { final ReentrantLock lock = this.lock; lock.lock(); try { return (items.size() == 0) ? null : extract(); } finally { lock.unlock(); } } public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (items.size() == 0) notEmpty.await(); return extract(); } finally { lock.unlock(); } } public E poll(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (items.size() == 0) { if (nanos <= 0) return null; nanos = notEmpty.awaitNanos(nanos); } return extract(); } finally { lock.unlock(); } } public E peek() { final ReentrantLock lock = this.lock; lock.lock(); try { return (items.size() == 0) ? null : items.get(rand.nextInt(items.size())); } finally { lock.unlock(); } } // this doc comment is overridden to remove the reference to collections // greater in size than Integer.MAX_VALUE /** * Returns the number of elements in this queue. * * @return the number of elements in this queue */ public int size() { final ReentrantLock lock = this.lock; lock.lock(); try { return items.size(); } finally { lock.unlock(); } } // this doc comment is a modified copy of the inherited doc comment, // without the reference to unlimited queues. /** * Returns the number of additional elements that this queue can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this queue * less the current {@code size} of this queue. * * <p>Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting {@code remainingCapacity} * because it may be the case that another thread is about to * insert or remove an element. */ public int remainingCapacity() { final ReentrantLock lock = this.lock; lock.lock(); try { return Integer.MAX_VALUE - items.size(); } finally { lock.unlock(); } } /** * Removes a single instance of the specified element from this queue, * if it is present. More formally, removes an element {@code e} such * that {@code o.equals(e)}, if this queue contains one or more such * elements. * Returns {@code true} if this queue contained the specified element * (or equivalently, if this queue changed as a result of the call). * * <p>Removal of interior elements in circular array based queues * is an intrinsically slow and disruptive operation, so should * be undertaken only in exceptional circumstances, ideally * only when the queue is known not to be accessible by other * threads. * * @param o element to be removed from this queue, if present * @return {@code true} if this queue changed as a result of the call */ public boolean remove(Object o) { if (o == null) return false; final ReentrantLock lock = this.lock; lock.lock(); try { return this.items.remove(o); } finally { lock.unlock(); } } /** * Returns {@code true} if this queue contains the specified element. * More formally, returns {@code true} if and only if this queue contains * at least one element {@code e} such that {@code o.equals(e)}. * * @param o object to be checked for containment in this queue * @return {@code true} if this queue contains the specified element */ public boolean contains(Object o) { if (o == null) return false; final ReentrantLock lock = this.lock; lock.lock(); try { return items.contains(o); } finally { lock.unlock(); } } /** * Returns an array containing all of the elements in this queue, in * proper sequence. * * <p>The returned array will be "safe" in that no references to it are * maintained by this queue. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * * <p>This method acts as bridge between array-based and collection-based * APIs. * * @return an array containing all of the elements in this queue */ public Object[] toArray() { final ReentrantLock lock = this.lock; lock.lock(); try { return this.items.toArray(new Object[items.size()]); } finally { lock.unlock(); } } /** * Returns an array containing all of the elements in this queue, in * proper sequence; the runtime type of the returned array is that of * the specified array. If the queue fits in the specified array, it * is returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array and the size of this queue. * * <p>If this queue fits in the specified array with room to spare * (i.e., the array has more elements than this queue), the element in * the array immediately following the end of the queue is set to * {@code null}. * * <p>Like the {@link #toArray()} method, this method acts as bridge between * array-based and collection-based APIs. Further, this method allows * precise control over the runtime type of the output array, and may, * under certain circumstances, be used to save allocation costs. * * <p>Suppose {@code x} is a queue known to contain only strings. * The following code can be used to dump the queue into a newly * allocated array of {@code String}: * * <pre> * String[] y = x.toArray(new String[0]);</pre> * * Note that {@code toArray(new Object[0])} is identical in function to * {@code toArray()}. * * @param a the array into which the elements of the queue are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * @return an array containing all of the elements in this queue * @throws ArrayStoreException if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this queue * @throws NullPointerException if the specified array is null */ public <T> T[] toArray(T[] a) { final ReentrantLock lock = this.lock; lock.lock(); try { return items.toArray(a); } finally { lock.unlock(); } } public String toString() { final ReentrantLock lock = this.lock; lock.lock(); try { return items.toString(); } finally { lock.unlock(); } } /** * Atomically removes all of the elements from this queue. * The queue will be empty after this call returns. */ public void clear() { final ReentrantLock lock = this.lock; lock.lock(); try { this.items.clear(); } finally { lock.unlock(); } } /** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c) { checkNotNull(c); if (c == this) throw new IllegalArgumentException(); final ReentrantLock lock = this.lock; lock.lock(); try { int n = this.items.size(); this.items.removeAll(c); return n; } finally { lock.unlock(); } } /** * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} */ public int drainTo(Collection<? super E> c, int maxElements) { checkNotNull(c); if (c == this) throw new IllegalArgumentException(); if (maxElements <= 0) return 0; final ReentrantLock lock = this.lock; lock.lock(); try { if (maxElements < this.items.size()) maxElements = this.items.size(); int n = this.items.size(); this.items.removeAll(c); return n; } finally { lock.unlock(); } } /** * Returns an iterator over the elements in this queue in proper sequence. * The elements will be returned in order from first (head) to last (tail). * * <p>The returned {@code Iterator} is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException * ConcurrentModificationException}, * and guarantees to traverse elements as they existed upon * construction of the iterator, and may (but is not guaranteed to) * reflect any modifications subsequent to construction. * * @return an iterator over the elements in this queue in proper sequence */ public Iterator<E> iterator() { throw new UnsupportedOperationException(); } }
2,234
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/ChoiceOfTwoLoadBalancer.java
package netflix.ocelli.loadbalancer; import netflix.ocelli.LoadBalancerStrategy; import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; /** * This selector chooses 2 random hosts and picks the host with the 'best' * performance where that determination is deferred to a customizable function. * * This implementation is based on the paper 'The Power of Two Choices in * Randomized Load Balancing' http://www.eecs.harvard.edu/~michaelm/postscripts/tpds2001.pdf * This paper states that selecting the best of 2 random servers results in an * exponential improvement over selecting a single random node (also includes * round robin) but that adding a third (or more) servers does not yield a significant * performance improvement. * * @author elandau * * @param <T> */ public class ChoiceOfTwoLoadBalancer<T> implements LoadBalancerStrategy<T> { public static <T> ChoiceOfTwoLoadBalancer<T> create(final Comparator<T> func) { return new ChoiceOfTwoLoadBalancer<T>(func); } private final Comparator<T> func; private final Random rand = new Random(); public ChoiceOfTwoLoadBalancer(final Comparator<T> func2) { func = func2; } /** * @throws NoSuchElementException */ @Override public T choose(List<T> candidates) { if (candidates.isEmpty()) { throw new NoSuchElementException("No servers available in the load balancer"); } else if (candidates.size() == 1) { return candidates.get(0); } else { int pos = rand.nextInt(candidates.size()); T first = candidates.get(pos); T second = candidates.get((rand.nextInt(candidates.size()-1) + pos + 1) % candidates.size()); return func.compare(first, second) >= 0 ? first : second; } } }
2,235
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/RandomWeightedLoadBalancer.java
package netflix.ocelli.loadbalancer; import netflix.ocelli.LoadBalancerStrategy; import netflix.ocelli.loadbalancer.weighting.ClientsAndWeights; import netflix.ocelli.loadbalancer.weighting.WeightingStrategy; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; /** * Select the next element using a random number. * * The weights are sorted such as that each cell in the array represents the * sum of the previous weights plus its weight. This structure makes it * possible to do a simple binary search using a random number from 0 to * total weights. * * Runtime complexity is O(log N) * * @author elandau * */ public class RandomWeightedLoadBalancer<T> implements LoadBalancerStrategy<T> { public static <T> RandomWeightedLoadBalancer<T> create(final WeightingStrategy<T> strategy) { return new RandomWeightedLoadBalancer<T>(strategy); } private final WeightingStrategy<T> strategy; private final Random rand = new Random(); public RandomWeightedLoadBalancer(final WeightingStrategy<T> strategy) { this.strategy = strategy; } /** * @throws NoSuchElementException */ @Override public T choose(List<T> local) { final ClientsAndWeights<T> caw = strategy.call(local); if (caw.isEmpty()) { throw new NoSuchElementException("No servers available in the load balancer"); } int total = caw.getTotalWeights(); if (total == 0) { return caw.getClient(rand.nextInt(caw.size())); } int pos = Collections.binarySearch(caw.getWeights(), rand.nextInt(total)); return caw.getClient(pos >= 0? pos+1 : -pos - 1); } }
2,236
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java
package netflix.ocelli.loadbalancer; import netflix.ocelli.LoadBalancerStrategy; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * Very simple LoadBlancer that when subscribed to gets an ImmutableList of active clients * and round robins on the elements in that list * * @author elandau */ public class RoundRobinLoadBalancer<T> implements LoadBalancerStrategy<T> { public static <T> RoundRobinLoadBalancer<T> create() { return create(new Random().nextInt(1000)); } public static <T> RoundRobinLoadBalancer<T> create(int seedPosition) { return new RoundRobinLoadBalancer<T>(seedPosition); } private final AtomicInteger position; public RoundRobinLoadBalancer() { position = new AtomicInteger(new Random().nextInt(1000)); } public RoundRobinLoadBalancer(int seedPosition) { position = new AtomicInteger(seedPosition); } /** * @throws NoSuchElementException */ @Override public T choose(List<T> local) { if (local.isEmpty()) { throw new NoSuchElementException("No servers available in the load balancer"); } else { int pos = Math.abs(position.incrementAndGet()); return local.get(pos % local.size()); } } }
2,237
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/weighting/LinearWeightingStrategy.java
package netflix.ocelli.loadbalancer.weighting; import rx.functions.Func1; import java.util.ArrayList; import java.util.List; public class LinearWeightingStrategy<C> implements WeightingStrategy<C> { private final Func1<C, Integer> func; public LinearWeightingStrategy(Func1<C, Integer> func) { this.func = func; } @Override public ClientsAndWeights<C> call(List<C> clients) { ArrayList<Integer> weights = new ArrayList<Integer>(clients.size()); if (!clients.isEmpty()) { for (C client : clients) { weights.add(func.call(client)); } int sum = 0; for (int i = 0; i < weights.size(); i++) { sum += weights.get(i); weights.set(i, sum); } } return new ClientsAndWeights<C>(clients, weights); } }
2,238
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/weighting/ClientsAndWeights.java
package netflix.ocelli.loadbalancer.weighting; import java.util.List; public class ClientsAndWeights<C> { private final List<C> clients; private final List<Integer> weights; public ClientsAndWeights(List<C> clients, List<Integer> weights) { this.clients = clients; this.weights = weights; } public List<C> getClients() { return clients; } public List<Integer> getWeights() { return weights; } public boolean isEmpty() { return clients.isEmpty(); } public int size() { return clients.size(); } public int getTotalWeights() { if (weights == null || weights.isEmpty()) { return 0; } return weights.get(weights.size() -1); } public C getClient(int index) { return clients.get(index); } public int getWeight(int index) { if (weights == null) { return 0; } return weights.get(index); } @Override public String toString() { return "ClientsAndWeights [clients=" + clients + ", weights=" + weights + ']'; } }
2,239
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/weighting/EqualWeightStrategy.java
package netflix.ocelli.loadbalancer.weighting; import java.util.List; /** * Strategy where all clients have the same weight * @author elandau * * @param <Host> * @param <C> * @param <Metrics> */ public class EqualWeightStrategy<C> implements WeightingStrategy<C> { @Override public ClientsAndWeights<C> call(List<C> clients) { return new ClientsAndWeights<C>(clients, null); } }
2,240
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/weighting/WeightingStrategy.java
package netflix.ocelli.loadbalancer.weighting; import java.util.List; import rx.functions.Func1; /** * Contract for strategy to determine client weights from a list of clients * * @author elandau * * @param <C> */ public interface WeightingStrategy<C> extends Func1<List<C>, ClientsAndWeights<C>> { /** * Run the weighting algorithm on the active set of clients and their associated statistics and * return an object containing the weights */ ClientsAndWeights<C> call(List<C> clients); }
2,241
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/loadbalancer/weighting/InverseMaxWeightingStrategy.java
package netflix.ocelli.loadbalancer.weighting; import java.util.ArrayList; import java.util.List; import rx.functions.Func1; /** * Weighting strategy that gives an inverse weight to the highest rate. Using * this strategy higher input values receive smaller weights. * * For example, if the weight is based on pending requests then an input of * [1, 5, 10, 1] pending request counts would yield the following weights * [10, 6, 1, 10] using the formula : w(i) = max - w(i) + 1 * * Note that 1 is added to ensure that we don't have a 0 weight, which is invalid. * * @author elandau * * @param <C> */ public class InverseMaxWeightingStrategy<C> implements WeightingStrategy<C> { private Func1<C, Integer> func; public InverseMaxWeightingStrategy(Func1<C, Integer> func) { this.func = func; } @Override public ClientsAndWeights<C> call(List<C> clients) { ArrayList<Integer> weights = new ArrayList<Integer>(clients.size()); if (clients.size() > 0) { Integer max = 0; for (int i = 0; i < clients.size(); i++) { int weight = func.call(clients.get(i)); if (weight > max) { max = weight; } weights.add(i, weight); } int sum = 0; for (int i = 0; i < weights.size(); i++) { sum += (max - weights.get(i)) + 1; weights.set(i, sum); } } return new ClientsAndWeights<C>(clients, weights); } }
2,242
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/topologies/RingTopology.java
package netflix.ocelli.topologies; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import netflix.ocelli.CloseableInstance; import netflix.ocelli.Instance; import netflix.ocelli.InstanceToNotification; import netflix.ocelli.InstanceToNotification.InstanceNotification; import rx.Observable; import rx.Observable.Transformer; import rx.Scheduler; import rx.functions.Action0; import rx.functions.Func1; import rx.functions.Func2; import rx.schedulers.Schedulers; /** * The ring topology uses consistent hashing to arrange all hosts in a predictable ring * topology such that each client instance will be located in a uniformly distributed * fashion around the ring. The client will then target the next N hosts after its location. * * This type of topology ensures that each client instance communicates with a subset of * hosts in such a manner that the overall load shall be evenly distributed. * * @author elandau * * @param <T> */ public class RingTopology<K extends Comparable<K>, T> implements Transformer<Instance<T>, Instance<T>> { private final Func1<Integer, Integer> countFunc; private final Func1<T, K> keyFunc; private final Entry local; class Entry implements Comparable<Entry> { final K key; final T value; CloseableInstance<T> instance; public Entry(K key) { this(key, null); } public Entry(K key, T value) { this.key = key; this.value = value; } @Override public int compareTo(Entry o) { return key.compareTo(o.key); } public void setInstance(CloseableInstance<T> instance) { if (this.instance != null) { this.instance.close(); } this.instance = instance; } public void closeInstance() { setInstance(null); } public String toString() { return key.toString(); } } class State { // Complete hash ordered list of all existing instances final List<Entry> ring = new ArrayList<Entry>(); // Lookup of all entries in the active list final Map<K, Entry> active = new HashMap<K, Entry>(); State() { ring.add(local); } Observable<Instance<T>> update() { Collections.sort(ring); // Get the starting position in the ring and number of entries // that should be active. int pos = Collections.binarySearch(ring, local) + 1; int count = Math.min(ring.size() - 1, countFunc.call(ring.size() - 1)); // Determine the current 'active' set Set<Entry> current = new HashSet<Entry>(); for (int i = 0; i < count; i++) { current.add(ring.get((pos + i) % ring.size())); } // Determine Entries that have either been added or removed Set<Entry> added = new HashSet<Entry>(current); added.removeAll(active.values()); final Set<Entry> removed = new HashSet<Entry>(active.values()); removed.removeAll(current); // Update the active list for (Entry entry : added) { active.put(entry.key, entry); } return Observable // New instance will be added immediately .from(added) .map(new Func1<Entry, Instance<T>>() { @Override public Instance<T> call(Entry entry) { CloseableInstance<T> instance = CloseableInstance.from(entry.value); entry.setInstance(instance); return instance; } } ) .doOnCompleted(new Action0() { @Override public void call() { for (Entry entry : removed) { entry.closeInstance(); active.remove(entry.key); } } }); } public void add(Instance<T> value) { ring.add(new Entry(keyFunc.call(value.getValue()), value.getValue())); } public void remove(Instance<T> value) { K key = keyFunc.call(value.getValue()); int pos = Collections.binarySearch(ring, new Entry(key)); if (pos >= 0) { ring.remove(pos).closeInstance(); active.remove(key); } } } public static <K extends Comparable<K>, T> RingTopology<K, T> create(final K localKey, final Func1<T, K> keyFunc, Func1<Integer, Integer> countFunc) { return new RingTopology<K, T>(localKey, keyFunc, countFunc); } public static <K extends Comparable<K>, T> RingTopology<K, T> create(final K localKey, final Func1<T, K> keyFunc, Func1<Integer, Integer> countFunc, Scheduler scheduler) { return new RingTopology<K, T>(localKey, keyFunc, countFunc, scheduler); } public RingTopology(final K localKey, final Func1<T, K> keyFunc, Func1<Integer, Integer> countFunc) { this(localKey, keyFunc, countFunc, Schedulers.computation()); } // Visible for testing public RingTopology(final K localKey, final Func1<T, K> keyFunc, Func1<Integer, Integer> countFunc, Scheduler scheduler) { this.local = new Entry(localKey); this.countFunc = countFunc; this.keyFunc = keyFunc; } @Override public Observable<Instance<T>> call(Observable<Instance<T>> o) { return o .flatMap(InstanceToNotification.<T>create()) .scan(new State(), new Func2<State, InstanceNotification<T>, State>() { @Override public State call(State state, InstanceNotification<T> instance) { switch (instance.getKind()) { case OnAdd: state.add(instance.getInstance()); break; case OnRemove: state.remove(instance.getInstance()); break; } return state; } }) .concatMap(new Func1<State, Observable<Instance<T>>>() { @Override public Observable<Instance<T>> call(State state) { return state.update(); } }); } }
2,243
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Retrys.java
package netflix.ocelli.functions; import java.util.concurrent.TimeUnit; import netflix.ocelli.retrys.ExponentialBackoff; import rx.Observable; import rx.functions.Func1; public abstract class Retrys { public static Func1<Throwable, Boolean> ALWAYS = new Func1<Throwable, Boolean>() { @Override public Boolean call(Throwable t1) { return true; } }; public static Func1<Throwable, Boolean> NEVER = new Func1<Throwable, Boolean>() { @Override public Boolean call(Throwable t1) { return false; } }; /** * Exponential backoff * @param maxRetrys * @param timeslice * @param units * @return */ public static Func1<Observable<? extends Throwable>, Observable<?>> exponentialBackoff(final int maxRetrys, final long timeslice, final TimeUnit units) { return new ExponentialBackoff(maxRetrys, timeslice, -1, units, ALWAYS); } /** * Bounded exponential backoff * @param maxRetrys * @param timeslice * @param units * @return */ public static Func1<Observable<? extends Throwable>, Observable<?>> exponentialBackoff(final int maxRetrys, final long timeslice, final TimeUnit units, final long maxDelay) { return new ExponentialBackoff(maxRetrys, timeslice, maxDelay, units, ALWAYS); } }
2,244
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Actions.java
package netflix.ocelli.functions; import java.util.concurrent.atomic.AtomicBoolean; import rx.functions.Action0; public abstract class Actions { public static Action0 once(final Action0 delegate) { return new Action0() { private AtomicBoolean called = new AtomicBoolean(false); @Override public void call() { if (called.compareAndSet(false, true)) { delegate.call(); } } }; } }
2,245
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Functions.java
package netflix.ocelli.functions; import rx.functions.Func1; public abstract class Functions { public static Func1<Integer, Integer> log() { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return (int)Math.ceil(Math.log(t1)); } }; } public static Func1<Integer, Integer> memoize(final Integer value) { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return Math.min(value, t1); } }; } public static Func1<Integer, Integer> log_log() { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return (int)Math.ceil(Math.log(Math.log(t1))); } }; } public static Func1<Integer, Integer> identity() { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return t1; } }; } public static Func1<Integer, Integer> sqrt() { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return (int)Math.ceil(Math.sqrt((double)t1)); } }; } public static Func1<Integer, Integer> root(final double pow) { return new Func1<Integer, Integer>() { @Override public Integer call(Integer t1) { return (int)Math.ceil(Math.pow((double)t1, 1/pow)); } }; } }
2,246
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Connectors.java
package netflix.ocelli.functions; import rx.Observable; import rx.functions.Func1; public abstract class Connectors { public static <C> Func1<C, Observable<Void>> never() { return new Func1<C, Observable<Void>>() { @Override public Observable<Void> call(C client) { return Observable.never(); } }; } public static <C> Func1<C, Observable<Void>> immediate() { return new Func1<C, Observable<Void>>() { @Override public Observable<Void> call(C client) { return Observable.empty(); } }; } public static <C> Func1<C, Observable<Void>> failure(final Throwable t) { return new Func1<C, Observable<Void>>() { @Override public Observable<Void> call(C client) { return Observable.error(t); } }; } }
2,247
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Topologies.java
package netflix.ocelli.functions; import netflix.ocelli.topologies.RingTopology; import rx.functions.Func1; /** * Convenience class for creating different topologies that filter clients into * a specific arrangement that limit the set of clients this instance will communicate * with. * * @author elandau * */ public abstract class Topologies { public static <T, K extends Comparable<K>> RingTopology<K, T> ring(K id, Func1<T, K> idFunc, Func1<Integer, Integer> countFunc) { return new RingTopology<K, T>(id, idFunc, countFunc); } }
2,248
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Weightings.java
package netflix.ocelli.functions; import rx.functions.Func1; import netflix.ocelli.loadbalancer.weighting.EqualWeightStrategy; import netflix.ocelli.loadbalancer.weighting.InverseMaxWeightingStrategy; import netflix.ocelli.loadbalancer.weighting.LinearWeightingStrategy; import netflix.ocelli.loadbalancer.weighting.WeightingStrategy; public abstract class Weightings { /** * @return Strategy that provides a uniform weight to each client */ public static <C> WeightingStrategy<C> uniform() { return new EqualWeightStrategy<C>(); } /** * @param func * @return Strategy that uses the output of the function as the weight */ public static <C> WeightingStrategy<C> identity(Func1<C, Integer> func) { return new LinearWeightingStrategy<C>(func); } /** * @param func * @return Strategy that sets the weight to the difference between the max * value of all clients and the client value. */ public static <C> WeightingStrategy<C> inverseMax(Func1<C, Integer> func) { return new InverseMaxWeightingStrategy<C>(func); } }
2,249
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Stopwatches.java
package netflix.ocelli.functions; import java.util.concurrent.TimeUnit; import netflix.ocelli.util.Stopwatch; import rx.functions.Func0; /** * Utility class to create common Stopwatch factories in the form of Func0<Stopwatch> * functions * * @author elandau * */ public class Stopwatches { /** * Stopwatch that calls System.nanoTime() * * @return */ public static Func0<Stopwatch> systemNano() { return new Func0<Stopwatch>() { @Override public Stopwatch call() { return new Stopwatch() { private final long startTime = System.nanoTime(); @Override public long elapsed(TimeUnit units) { return units.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } }; } }; } }
2,250
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Limiters.java
package netflix.ocelli.functions; import netflix.ocelli.stats.ExponentialAverage; import rx.functions.Func1; public abstract class Limiters { /** * Guard against excessive backup requests using exponential moving average * on a per sample basis which is incremented by 1 for each request and by 0 * for each backup request. A backup request is allowed as long as the average * is able the expected percentile of primary requests to backup requests. * * Note that this implementation favors simplicity over accuracy and has * many drawbacks. * 1. Backup requests are per request and not tied to any time window * 2. I have yet to determine an equation that selects the proper window * for the requested ratio so that the updated exponential moving average * allows the ratio number of requests. * @param ratio * @param window * @return */ public static Func1<Boolean, Boolean> exponential(final double ratio, final int window) { return new Func1<Boolean, Boolean>() { private ExponentialAverage exp = new ExponentialAverage(window, 0); @Override public Boolean call(Boolean isPrimary) { if (isPrimary) { exp.add(1L); return true; } if (exp.get() > ratio) { exp.add(0L); return true; } return false; } }; } }
2,251
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Delays.java
package netflix.ocelli.functions; import java.util.concurrent.TimeUnit; import netflix.ocelli.DelayStrategy; public abstract class Delays { public static DelayStrategy fixed(final long delay, final TimeUnit units) { return new DelayStrategy() { @Override public long get(int count) { return TimeUnit.MILLISECONDS.convert(delay, units); } }; } public static DelayStrategy linear(final long delay, final TimeUnit units) { return new DelayStrategy() { @Override public long get(int count) { return count * TimeUnit.MILLISECONDS.convert(delay, units); } }; } public static DelayStrategy exp(final long step, final TimeUnit units) { return new DelayStrategy() { @Override public long get(int count) { if (count < 0) count = 0; else if (count > 30) count = 30; return (1 << count) * TimeUnit.MILLISECONDS.convert(step, units); } }; } public static DelayStrategy boundedExp(final long step, final long max, final TimeUnit units) { return new DelayStrategy() { @Override public long get(int count) { if (count < 0) count = 0; else if (count > 30) count = 30; long delay = (1 << count) * TimeUnit.MILLISECONDS.convert(step, units); if (delay > max) { return max; } return delay; } }; } public static DelayStrategy immediate() { return new DelayStrategy() { @Override public long get(int t1) { return 0L; } }; } }
2,252
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Failures.java
package netflix.ocelli.functions; import rx.Observable; import rx.functions.Func1; public abstract class Failures { public static <C> Func1<C, Observable<Throwable>> never() { return new Func1<C, Observable<Throwable>>() { @Override public Observable<Throwable> call(C client) { return Observable.never(); } }; } public static <C> Func1<C, Observable<Throwable>> always(final Throwable t) { return new Func1<C, Observable<Throwable>>() { @Override public Observable<Throwable> call(C client) { return Observable.error(t); } }; } }
2,253
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/functions/Metrics.java
package netflix.ocelli.functions; import rx.functions.Func0; import netflix.ocelli.stats.CKMSQuantiles; import netflix.ocelli.stats.Quantiles; import netflix.ocelli.util.SingleMetric; /** * Utility class for creating common strategies for tracking specific types of metrics * * @author elandau * */ public class Metrics { public static <T> Func0<SingleMetric<T>> memoizeFactory(final T value) { return new Func0<SingleMetric<T>>() { @Override public SingleMetric<T> call() { return memoize(value); } }; } /** * Return a predetermine constant value regardless of samples added. * @param value * @return */ public static <T> SingleMetric<T> memoize(final T value) { return new SingleMetric<T>() { @Override public void add(T sample) { } @Override public void reset() { } @Override public T get() { return value; } }; } public static Func0<SingleMetric<Long>> quantileFactory(final double percentile) { return new Func0<SingleMetric<Long>>() { @Override public SingleMetric<Long> call() { return quantile(percentile); } }; } /** * Use the default CKMSQuantiles algorithm to track a specific percentile * @param percentile * @return */ public static SingleMetric<Long> quantile(final double percentile) { return quantile(new CKMSQuantiles(new CKMSQuantiles.Quantile[]{new CKMSQuantiles.Quantile(percentile, 1)}), percentile); } /** * Use an externally provided Quantiles algorithm to track a single percentile. Note that * quantiles may be shared and should track homogeneous operations. * * @param quantiles * @param percentile * @return */ public static SingleMetric<Long> quantile(final Quantiles quantiles, final double percentile) { return new SingleMetric<Long>() { @Override public void add(Long sample) { quantiles.insert(sample.intValue()); } @Override public void reset() { } @Override public Long get() { return (long)quantiles.get(percentile); } }; } }
2,254
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/retrys/BackupRequestRetryStrategy.java
package netflix.ocelli.retrys; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import netflix.ocelli.functions.Metrics; import netflix.ocelli.functions.Retrys; import netflix.ocelli.functions.Stopwatches; import netflix.ocelli.util.SingleMetric; import netflix.ocelli.util.Stopwatch; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Observable.Transformer; import rx.Scheduler; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func0; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Retry strategy that kicks off a second request if the first request does not * respond within an expected amount of time. The original request remains in * flight until either one responds. The strategy tracks response latencies and * feeds them into a SingleMetric that is used to determine the backup request * timeout. A common metric to use is the 90th percentile response time. * * Note that the same BackupRequestRetryStrategy instance is stateful and should * be used for all requests. Multiple BackupRequestRetryStrategy instances may be * used for different request types known to have varying response latency * distributions. * * Usage, * * {@code * <pre> * * BackupRequestRetryStrategy strategy = BackupRequestRetryStrategy.builder() * .withTimeoutMetric(Metrics.quantile(0.90)) * .withIsRetriablePolicy(somePolicyThatReturnsTrueOnRetriableErrors) * .build(); * * loadBalancer * .flatMap(operation) * .compose(strategy) * .subscribe(responseHandler) * </pre> * code} * * @author elandau * * @param <T> */ public class BackupRequestRetryStrategy<T> implements Transformer<T, T> { public static Func0<Stopwatch> DEFAULT_CLOCK = Stopwatches.systemNano(); private final Func0<Stopwatch> sw; private final SingleMetric<Long> metric; private final Func1<Throwable, Boolean> retriableError; private final Scheduler scheduler; public static class Builder<T> { private Func0<Stopwatch> sw = DEFAULT_CLOCK; private SingleMetric<Long> metric = Metrics.memoize(10L); private Func1<Throwable, Boolean> retriableError = Retrys.ALWAYS; private Scheduler scheduler = Schedulers.computation(); /** * Function to determine if an exception is retriable or not. A non * retriable exception will result in an immediate error being returned * while the first retriable exception on either the primary or secondary * request will be ignored to allow the other request to complete. * @param retriableError */ public Builder<T> withIsRetriablePolicy(Func1<Throwable, Boolean> retriableError) { this.retriableError = retriableError; return this; } /** * Function to determine the backup request timeout for each operation. * @param func * @param units */ public Builder<T> withTimeoutMetric(SingleMetric<Long> metric) { this.metric = metric; return this; } /** * Provide an external scheduler to drive the backup timeout. Use this * to test with a TestScheduler * * @param scheduler */ public Builder<T> withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } /** * Factory for creating stopwatches. A new stopwatch is created per operation. * @param clock */ public Builder<T> withStopwatch(Func0<Stopwatch> sw) { this.sw = sw; return this; } public BackupRequestRetryStrategy<T> build() { return new BackupRequestRetryStrategy<T>(this); } } public static <T> Builder<T> builder() { return new Builder<T>(); } private BackupRequestRetryStrategy(Builder<T> builder) { this.metric = builder.metric; this.retriableError = builder.retriableError; this.scheduler = builder.scheduler; this.sw = builder.sw; } @Override public Observable<T> call(final Observable<T> o) { Observable<T> timedO = Observable.create(new OnSubscribe<T>() { @Override public void call(Subscriber<? super T> s) { final Stopwatch timer = sw.call(); o.doOnNext(new Action1<T>() { @Override public void call(T t1) { metric.add(timer.elapsed(TimeUnit.MILLISECONDS)); } }).subscribe(s); } }); return Observable .just(timedO, timedO.delaySubscription(metric.get(), TimeUnit.MILLISECONDS, scheduler)) .flatMap(new Func1<Observable<T>, Observable<T>>() { final AtomicInteger counter = new AtomicInteger(); @Override public Observable<T> call(Observable<T> t1) { return t1.onErrorResumeNext(new Func1<Throwable, Observable<T>>() { @Override public Observable<T> call(Throwable e) { if (counter.incrementAndGet() == 2 || !retriableError.call(e)) { return Observable.error(e); } return Observable.never(); } }); } }) .take(1); } }
2,255
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/retrys/ExponentialBackoff.java
package netflix.ocelli.retrys; import java.util.Random; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.functions.Func1; /** * Func1 to be passed to retryWhen which implements a robust random exponential backoff. The * random part of the exponential backoff ensures that some randomness is inserted so that multiple * clients blocked on a non-responsive resource spread out the retries to mitigate a thundering * herd. * * This class maintains retry count state and should be instantiated for entire top level request. * * @author elandau */ public class ExponentialBackoff implements Func1<Observable<? extends Throwable>, Observable<?>> { private static final int MAX_SHIFT = 30; private final int maxRetrys; private final long maxDelay; private final long slice; private final TimeUnit units; private final Func1<Throwable, Boolean> retryable; private static final Random rand = new Random(); private int tryCount; /** * Construct an exponential backoff * * @param maxRetrys Maximum number of retires to attempt * @param slice - Time interval multiplied by backoff amount * @param maxDelay - Upper bound allowable backoff delay * @param units - Time unit for slice and maxDelay * @param retryable - Function that returns true if the error is retryable or false if not. */ public ExponentialBackoff(int maxRetrys, long slice, long maxDelay, TimeUnit units, Func1<Throwable, Boolean> retryable) { this.maxDelay = maxDelay; this.maxRetrys = maxRetrys; this.slice = slice; this.units = units; this.retryable = retryable; this.tryCount = 0; } @Override public Observable<?> call(Observable<? extends Throwable> error) { return error.flatMap(new Func1<Throwable, Observable<?>>() { @Override public Observable<?> call(Throwable e) { // First make sure the error is actually retryable if (!retryable.call(e)) { return Observable.error(e); } if (tryCount >= maxRetrys) { return Observable.error(new Exception("Failed with " + tryCount + " retries", e)); } // Calculate the number of slices to wait int slices = (1 << Math.min(MAX_SHIFT, tryCount)); slices = (slices + rand.nextInt(slices+1)) / 2; long delay = slices * slice; if (maxDelay > 0 && delay > maxDelay) { delay = maxDelay; } tryCount++; return Observable.timer(delay, units); } }); } }
2,256
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/stats/ExponentialAverage.java
package netflix.ocelli.stats; import netflix.ocelli.util.AtomicDouble; import netflix.ocelli.util.SingleMetric; import rx.functions.Func0; public class ExponentialAverage implements SingleMetric<Long> { private final double k; private final AtomicDouble ema; private final double initial; public static Func0<SingleMetric<Long>> factory(final int N, final double initial) { return new Func0<SingleMetric<Long>>() { @Override public SingleMetric<Long> call() { return new ExponentialAverage(N, initial); } }; } public ExponentialAverage(int N, double initial) { this.initial = initial; this.k = 2.0/(double)(N+1); this.ema = new AtomicDouble(initial); } @Override public void add(Long sample) { double next; double current; do { current = ema.get(); next = sample * k + current * (1-k); } while(!ema.compareAndSet(current, next)); } @Override public Long get() { return (long)ema.get(); } @Override public void reset() { ema.set(initial); } }
2,257
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/stats/Frugal2UQuantiles.java
package netflix.ocelli.stats; import java.util.Random; /** * Implementation of the Frugal2U Algorithm. * * Reference: * Ma, Qiang, S. Muthukrishnan, and Mark Sandler. "Frugal Streaming for * Estimating Quantiles." Space-Efficient Data Structures, Streams, and * Algorithms. Springer Berlin Heidelberg, 2013. 77-96. * * Original code: <https://github.com/dgryski/go-frugal> * More info: http://blog.aggregateknowledge.com/2013/09/16/sketch-of-the-day-frugal-streaming/ * * @author Maycon Viana Bordin <mayconbordin@gmail.com> */ public class Frugal2UQuantiles implements Quantiles { private final Quantile quantiles[]; public Frugal2UQuantiles(Quantile[] quantiles) { this.quantiles = quantiles; } public Frugal2UQuantiles(double[] quantiles, int initialEstimate) { this.quantiles = new Quantile[quantiles.length]; for (int i=0; i<quantiles.length; i++) { this.quantiles[i] = new Quantile(initialEstimate, quantiles[i]); } } @Override public synchronized void insert(int value) { for (Quantile q : quantiles) { q.insert(value); } } public int get(double q) { for (Quantile quantile : quantiles) { if (quantile.q == q) return quantile.m; } return 0; } public class Quantile { int m; double q; int step = 1; int sign = 0; Random r = new Random(new Random().nextInt()); Quantile(int estimate, double quantile) { m = estimate; q = quantile; } void insert(int s) { if (sign == 0) { m = s; sign = 1; return; } if (s > m && r.nextDouble() > 1-q) { step += sign * f(step); if (step > 0) { m += step; } else { m += 1; } if (m > s) { step += (s - m); m = s; } if (sign < 0) { step = 1; } sign = 1; } else if (s < m && r.nextDouble() > q) { step += -sign * f(step); if (step > 0) { m -= step; } else { m--; } if (m < s) { step += (m - s); m = s; } if (sign > 0) { step = 1; } sign = -1; } } int f(int step) { return 1; } } }
2,258
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/stats/CKMSQuantiles.java
package netflix.ocelli.stats; /* Copyright 2012 Andrew Wang (andrew@umbrant.com) 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. */ import java.util.Arrays; import java.util.LinkedList; import java.util.ListIterator; /** * Implementation of the Cormode, Korn, Muthukrishnan, and Srivastava algorithm * for streaming calculation of targeted high-percentile epsilon-approximate * quantiles. * * This is a generalization of the earlier work by Greenwald and Khanna (GK), * which essentially allows different error bounds on the targeted quantiles, * which allows for far more efficient calculation of high-percentiles. * * * See: Cormode, Korn, Muthukrishnan, and Srivastava * "Effective Computation of Biased Quantiles over Data Streams" in ICDE 2005 * * Greenwald and Khanna, * "Space-efficient online computation of quantile summaries" in SIGMOD 2001 * */ public class CKMSQuantiles implements Quantiles { /** * Total number of items in stream. */ private int count = 0; /** * Used for tracking incremental compression. */ private int compressIdx = 0; /** * Current list of sampled items, maintained in sorted order with error * bounds. */ protected LinkedList<Item> sample; /** * Buffers incoming items to be inserted in batch. */ private long[] buffer = new long[500]; private int bufferCount = 0; /** * Array of Quantiles that we care about, along with desired error. */ private final Quantile quantiles[]; public CKMSQuantiles(Quantile[] quantiles) { this.quantiles = quantiles; this.sample = new LinkedList<Item>(); } /** * Add a new value from the stream. * * @param value */ @Override public synchronized void insert(int value) { buffer[bufferCount] = value; bufferCount++; if (bufferCount == buffer.length) { insertBatch(); compress(); } } /** * Get the estimated value at the specified quantile. * * @param q * Queried quantile, e.g. 0.50 or 0.99. * @return Estimated value at that quantile. */ @Override public synchronized int get(double q) { // clear the buffer insertBatch(); compress(); if (sample.size() == 0) { return 0; } int rankMin = 0; int desired = (int) (q * count); ListIterator<Item> it = sample.listIterator(); Item prev, cur; cur = it.next(); while (it.hasNext()) { prev = cur; cur = it.next(); rankMin += prev.g; if (rankMin + cur.g + cur.delta > desired + (allowableError(desired) / 2)) { return (int) prev.value; } } // edge case of wanting max value return (int) sample.getLast().value; } /** * Specifies the allowable error for this rank, depending on which quantiles * are being targeted. * * This is the f(r_i, n) function from the CKMS paper. It's basically how * wide the range of this rank can be. * * @param rank * the index in the list of samples */ private double allowableError(int rank) { // NOTE: according to CKMS, this should be count, not size, but this // leads // to error larger than the error bounds. Leaving it like this is // essentially a HACK, and blows up memory, but does "work". // int size = count; int size = sample.size(); double minError = size + 1; for (Quantile q : quantiles) { double error; if (rank <= q.quantile * size) { error = q.u * (size - rank); } else { error = q.v * rank; } if (error < minError) { minError = error; } } return minError; } private boolean insertBatch() { if (bufferCount == 0) { return false; } Arrays.sort(buffer, 0, bufferCount); // Base case: no samples int start = 0; if (sample.size() == 0) { Item newItem = new Item(buffer[0], 1, 0); sample.add(newItem); start++; count++; } ListIterator<Item> it = sample.listIterator(); Item item = it.next(); for (int i = start; i < bufferCount; i++) { long v = buffer[i]; while (it.nextIndex() < sample.size() && item.value < v) { item = it.next(); } // If we found that bigger item, back up so we insert ourselves // before it if (item.value > v) { it.previous(); } // We use different indexes for the edge comparisons, because of the // above // if statement that adjusts the iterator int delta; if (it.previousIndex() == 0 || it.nextIndex() == sample.size()) { delta = 0; } else { delta = ((int) Math.floor(allowableError(it.nextIndex()))) - 1; } Item newItem = new Item(v, 1, delta); it.add(newItem); count++; item = newItem; } bufferCount = 0; return true; } /** * Try to remove extraneous items from the set of sampled items. This checks * if an item is unnecessary based on the desired error bounds, and merges * it with the adjacent item if it is. */ private void compress() { if (sample.size() < 2) { return; } ListIterator<Item> it = sample.listIterator(); int removed = 0; Item prev = null; Item next = it.next(); while (it.hasNext()) { prev = next; next = it.next(); if (prev.g + next.g + next.delta <= allowableError(it.previousIndex())) { next.g += prev.g; // Remove prev. it.remove() kills the last thing returned. it.previous(); it.previous(); it.remove(); // it.next() is now equal to next, skip it back forward again it.next(); removed++; } } } private class Item { public final long value; public int g; public final int delta; public Item(long value, int lower_delta, int delta) { this.value = value; this.g = lower_delta; this.delta = delta; } @Override public String toString() { return String.format("%d, %d, %d", value, g, delta); } } public static class Quantile { public final double quantile; public final double error; public final double u; public final double v; public Quantile(double quantile, double error) { this.quantile = quantile; this.error = error; u = 2.0 * error / (1.0 - quantile); v = 2.0 * error / quantile; } @Override public String toString() { return String.format("Q{q=%.3f, eps=%.3f})", quantile, error); } } }
2,259
0
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-core/src/main/java/netflix/ocelli/stats/Quantiles.java
package netflix.ocelli.stats; /** * Contract for tracking percentiles in a dataset * * @author elandau */ public interface Quantiles { /** * Add a sample * @param value */ public void insert(int value); /** * @param get (0 .. 1.0) * @return Get the Nth percentile */ public int get(double percentile); }
2,260
0
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty/internal/LoadBalancingProviderTest.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.channel.Connection; import io.reactivex.netty.client.ConnectionFactory; import io.reactivex.netty.client.ConnectionObservable; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.Instance; import netflix.ocelli.rxnetty.FailureListener; import netflix.ocelli.rxnetty.internal.AbstractLoadBalancer.LoadBalancingProvider; import org.junit.Rule; import org.junit.Test; import org.mockito.verification.VerificationMode; import rx.Observable; import rx.functions.Func1; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.Matchers.*; import static org.mockito.Mockito.*; public class LoadBalancingProviderTest { @Rule public final LoadBalancerRule loadBalancerRule = new LoadBalancerRule(); @Test(timeout = 60000) public void testRoundRobin() throws Exception { List<Instance<SocketAddress>> hosts = loadBalancerRule.setupDefault(); assertThat("Unexpected hosts found.", hosts, hasSize(2)); AbstractLoadBalancer<String, String> loadBalancer = loadBalancerRule.getLoadBalancer(); ConnectionFactory<String, String> cfMock = loadBalancerRule.newConnectionFactoryMock(); Observable<Instance<ConnectionProvider<String, String>>> providers = loadBalancerRule.getHostsAsConnectionProviders(cfMock); LoadBalancingProvider lbProvider = newLoadBalancingProvider(loadBalancer, cfMock, providers); @SuppressWarnings("unchecked") ConnectionObservable<String, String> connectionObservable = lbProvider.nextConnection(); assertNextConnection(hosts.get(0).getValue(), cfMock, connectionObservable, times(1)); assertNextConnection(hosts.get(1).getValue(), cfMock, connectionObservable, times(1)); assertNextConnection(hosts.get(0).getValue(), cfMock, connectionObservable, times(2) /*Invoked once above with same host*/); } @Test(timeout = 60000) public void testListenerSubscription() throws Exception { final AtomicBoolean listenerCalled = new AtomicBoolean(); final TcpClientEventListener listener = new TcpClientEventListener() { @Override public void onConnectionCloseStart() { listenerCalled.set(true); } }; InetSocketAddress host = new InetSocketAddress(0); loadBalancerRule.setup(new Func1<FailureListener, TcpClientEventListener>() { @Override public TcpClientEventListener call(FailureListener failureListener) { return listener; } }, host); AbstractLoadBalancer<String, String> loadBalancer = loadBalancerRule.getLoadBalancer(); ConnectionFactory<String, String> cfMock = loadBalancerRule.newConnectionFactoryMock(); Observable<Instance<ConnectionProvider<String, String>>> providers = loadBalancerRule.getHostsAsConnectionProviders(cfMock); LoadBalancingProvider lbProvider = newLoadBalancingProvider(loadBalancer, cfMock, providers); @SuppressWarnings("unchecked") ConnectionObservable<String, String> connectionObservable = lbProvider.nextConnection(); Connection<String, String> c = assertNextConnection(host, cfMock, connectionObservable, times(1)); c.closeNow(); assertThat("Listener not called.", listenerCalled.get(), is(true)); } protected Connection<String, String> assertNextConnection(SocketAddress host, ConnectionFactory<String, String> cfMock, ConnectionObservable<String, String> connectionObservable, VerificationMode verificationMode) { Connection<String, String> c = loadBalancerRule.connect(connectionObservable); verify(cfMock, verificationMode).newConnection(host); return c; } protected LoadBalancingProvider newLoadBalancingProvider(AbstractLoadBalancer<String, String> loadBalancer, ConnectionFactory<String, String> cfMock, Observable<Instance<ConnectionProvider<String, String>>> providers) { LoadBalancingProvider lbProvider = loadBalancer.new LoadBalancingProvider(cfMock, providers); return lbProvider; } }
2,261
0
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty/internal/LoadBalancerRule.java
package netflix.ocelli.rxnetty.internal; import io.netty.channel.embedded.EmbeddedChannel; import io.reactivex.netty.channel.Connection; import io.reactivex.netty.channel.ConnectionImpl; import io.reactivex.netty.client.ConnectionFactory; import io.reactivex.netty.client.ConnectionObservable; import io.reactivex.netty.client.ConnectionObservable.OnSubcribeFunc; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.client.events.ClientEventListener; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventPublisher; import netflix.ocelli.Instance; import netflix.ocelli.LoadBalancerStrategy; import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer; import netflix.ocelli.rxnetty.FailureListener; import org.junit.rules.ExternalResource; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.mockito.Mockito; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.functions.Func1; import rx.functions.Func3; import rx.observers.TestSubscriber; import java.net.SocketAddress; import java.util.ArrayList; import java.util.List; public class LoadBalancerRule extends ExternalResource { private Observable<Instance<SocketAddress>> hosts; private Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory; private LoadBalancerStrategy<HostConnectionProvider<String, String>> loadBalancingStratgey; private AbstractLoadBalancer<String, String> loadBalancer; private Func3<Observable<Instance<SocketAddress>>, Func1<FailureListener, ? extends TcpClientEventListener>, LoadBalancerStrategy<HostConnectionProvider<String, String>>, AbstractLoadBalancer<String, String>> lbFactory; public LoadBalancerRule() { } public LoadBalancerRule(Func3<Observable<Instance<SocketAddress>>, Func1<FailureListener, ? extends TcpClientEventListener>, LoadBalancerStrategy<HostConnectionProvider<String, String>>, AbstractLoadBalancer<String, String>> lbFactory) { this.lbFactory = lbFactory; } @Override public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { base.evaluate(); } }; } public AbstractLoadBalancer<String, String> getLoadBalancer() { return loadBalancer; } public List<Instance<SocketAddress>> setupDefault() { final List<Instance<SocketAddress>> instances = new ArrayList<>(); instances.add(new DummyInstance()); instances.add(new DummyInstance()); setup(instances.get(0).getValue(), instances.get(1).getValue()); return hosts.toList().toBlocking().single(); } public AbstractLoadBalancer<String, String> setup(SocketAddress... hosts) { return setup(new Func1<FailureListener, TcpClientEventListener>() { @Override public TcpClientEventListener call(FailureListener failureListener) { return null; } }, hosts); } public AbstractLoadBalancer<String, String> setup( Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory, SocketAddress... hosts) { return setup(eventListenerFactory, new RoundRobinLoadBalancer<HostConnectionProvider<String, String>>(-1), hosts); } public AbstractLoadBalancer<String, String> setup( Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory, LoadBalancerStrategy<HostConnectionProvider<String, String>> loadBalancingStratgey, SocketAddress... hosts) { List<Instance<SocketAddress>> instances = new ArrayList<>(hosts.length); for (SocketAddress host : hosts) { instances.add(new DummyInstance(host)); } return setup(eventListenerFactory, loadBalancingStratgey, instances); } public AbstractLoadBalancer<String, String> setup( Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory, LoadBalancerStrategy<HostConnectionProvider<String, String>> loadBalancingStratgey, List<Instance<SocketAddress>> hosts) { this.hosts = Observable.from(hosts); this.eventListenerFactory = eventListenerFactory; this.loadBalancingStratgey = loadBalancingStratgey; if (null != lbFactory) { loadBalancer = lbFactory.call(this.hosts, eventListenerFactory, loadBalancingStratgey); return loadBalancer; } loadBalancer = new AbstractLoadBalancer<String, String>(this.hosts, eventListenerFactory, loadBalancingStratgey) { @Override protected ConnectionProvider<String, String> newConnectionProviderForHost(final Instance<SocketAddress> host, final ConnectionFactory<String, String> connectionFactory) { return new ConnectionProvider<String, String>(connectionFactory) { @Override public ConnectionObservable<String, String> nextConnection() { return connectionFactory.newConnection(host.getValue()); } }; } }; return getLoadBalancer(); } public Func1<FailureListener, ? extends TcpClientEventListener> getEventListenerFactory() { return eventListenerFactory; } public Observable<Instance<SocketAddress>> getHosts() { return hosts; } public Observable<Instance<ConnectionProvider<String, String>>> getHostsAsConnectionProviders( final ConnectionFactory<String, String> cfMock) { return hosts.map(new Func1<Instance<SocketAddress>, Instance<ConnectionProvider<String, String>>>() { @Override public Instance<ConnectionProvider<String, String>> call(final Instance<SocketAddress> i) { final ConnectionProvider<String, String> cp = new ConnectionProvider<String, String>(cfMock) { @Override public ConnectionObservable<String, String> nextConnection() { return cfMock.newConnection(i.getValue()); } }; return new Instance<ConnectionProvider<String, String>>() { @Override public Observable<Void> getLifecycle() { return i.getLifecycle(); } @Override public ConnectionProvider<String, String> getValue() { return cp; } }; } }); } public LoadBalancerStrategy<HostConnectionProvider<String, String>> getLoadBalancingStratgey() { return loadBalancingStratgey; } public Connection<String, String> connect(ConnectionObservable<String, String> connectionObservable) { TestSubscriber<Connection<String, String>> testSub = new TestSubscriber<>(); connectionObservable.subscribe(testSub); testSub.awaitTerminalEvent(); testSub.assertNoErrors(); testSub.assertValueCount(1); return testSub.getOnNextEvents().get(0); } public ConnectionFactory<String, String> newConnectionFactoryMock() { @SuppressWarnings("unchecked") final ConnectionFactory<String, String> cfMock = Mockito.mock(ConnectionFactory.class); List<Instance<SocketAddress>> instances = hosts.toList().toBlocking().single(); for (Instance<SocketAddress> instance : instances) { EmbeddedChannel channel = new EmbeddedChannel(); final TcpClientEventPublisher eventPublisher = new TcpClientEventPublisher(); final Connection<String, String> mockConnection = ConnectionImpl.create(channel, eventPublisher, eventPublisher); Mockito.when(cfMock.newConnection(instance.getValue())) .thenReturn(ConnectionObservable.createNew(new OnSubcribeFunc<String, String>() { @Override public Subscription subscribeForEvents(ClientEventListener eventListener) { return eventPublisher.subscribe((TcpClientEventListener) eventListener); } @Override public void call(Subscriber<? super Connection<String, String>> subscriber) { subscriber.onNext(mockConnection); subscriber.onCompleted(); } })); } return cfMock; } private static class DummyInstance extends Instance<SocketAddress> { private final SocketAddress socketAddress; private DummyInstance() { socketAddress = new SocketAddress() { private static final long serialVersionUID = 711795406919943230L; @Override public String toString() { return "Dummy socket address: " + hashCode(); } }; } private DummyInstance(SocketAddress socketAddress) { this.socketAddress = socketAddress; } @Override public Observable<Void> getLifecycle() { return Observable.never(); } @Override public SocketAddress getValue() { return socketAddress; } } }
2,262
0
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/test/java/netflix/ocelli/rxnetty/internal/AbstractLoadBalancerTest.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.client.ConnectionFactory; import io.reactivex.netty.client.ConnectionObservable; import io.reactivex.netty.client.ConnectionProvider; import netflix.ocelli.Instance; import org.junit.Rule; import org.junit.Test; import org.mockito.Mockito; import java.net.SocketAddress; import java.util.List; public class AbstractLoadBalancerTest { @Rule public final LoadBalancerRule lbRule = new LoadBalancerRule(); @Test(timeout = 60000) public void testRoundRobin() throws Exception { List<Instance<SocketAddress>> hosts = lbRule.setupDefault(); AbstractLoadBalancer<String, String> loadBalancer = lbRule.getLoadBalancer(); ConnectionFactory<String, String> cfMock = lbRule.newConnectionFactoryMock(); ConnectionProvider<String, String> cp = loadBalancer.toConnectionProvider(cfMock); ConnectionObservable<String, String> co = cp.nextConnection(); lbRule.connect(co); Mockito.verify(cfMock).newConnection(hosts.get(0).getValue()); Mockito.verifyNoMoreInteractions(cfMock); cp = loadBalancer.toConnectionProvider(cfMock); co = cp.nextConnection(); lbRule.connect(co); Mockito.verify(cfMock).newConnection(hosts.get(1).getValue()); Mockito.verifyNoMoreInteractions(cfMock); } }
2,263
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/FailureListener.java
package netflix.ocelli.rxnetty; import rx.Scheduler; import java.util.concurrent.TimeUnit; /** * A contract for taking actions upon detecting an unhealthy host. A failure listener instance is always associated with * a unique host, so any action taken on this listener will directly be applied to the associated host. */ public interface FailureListener { /** * This action will remove the host associated with this listener from the load balancing pool. */ void remove(); /** * This action quarantines the host associated with this listener from the load balancing pool, for the passed * {@code quarantineDuration}. The host will be added back to the load balancing pool after the quarantine duration * is elapsed. * * @param quarantineDuration Duration for keeping the host quarantined. * @param timeUnit Time unit for the duration. */ void quarantine(long quarantineDuration, TimeUnit timeUnit); /** * This action quarantines the host associated with this listener from the load balancing pool, for the passed * {@code quarantineDuration}. The host will be added back to the load balancing pool after the quarantine duration * is elapsed. * * @param quarantineDuration Duration for keeping the host quarantined. * @param timeUnit Time unit for the duration. * @param timerScheduler Scheduler to be used for the quarantine duration timer. */ void quarantine(long quarantineDuration, TimeUnit timeUnit, Scheduler timerScheduler); }
2,264
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/internal/AbstractLoadBalancer.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.channel.Connection; import io.reactivex.netty.client.ConnectionFactory; import io.reactivex.netty.client.ConnectionObservable; import io.reactivex.netty.client.ConnectionObservable.AbstractOnSubscribeFunc; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.client.pool.PooledConnectionProvider; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.Instance; import netflix.ocelli.LoadBalancerStrategy; import netflix.ocelli.rxnetty.FailureListener; import rx.Observable; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; import java.net.SocketAddress; import java.util.List; import java.util.NoSuchElementException; /** * An abstract load balancer for all TCP based protocols. * * <h2>Failure detection</h2> * * For every host that this load balancer connects, it provides a way to register a {@link TcpClientEventListener} * instance that can detect failures based on the various events received. Upon detecting the failure, an appropriate * action can be taken for the host, using the provided {@link FailureListener}. * * <h2>Use with RxNetty clients</h2> * * In order to use this load balancer with RxNetty clients, one has to convert it to an instance of * {@link ConnectionProvider} by calling {@link #toConnectionProvider()} * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. */ public abstract class AbstractLoadBalancer<W, R> { protected final Observable<Instance<SocketAddress>> hosts; protected final LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer; protected final Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory; protected AbstractLoadBalancer(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory, LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer) { this.hosts = hosts; this.eventListenerFactory = eventListenerFactory; this.loadBalancer = loadBalancer; } /** * Converts this load balancer to a {@link ConnectionProvider} to be used with RxNetty clients. * * @return {@link ConnectionProvider} for this load balancer. */ public ConnectionProvider<W, R> toConnectionProvider() { return ConnectionProvider.create(new Func1<ConnectionFactory<W, R>, ConnectionProvider<W, R>>() { @Override public ConnectionProvider<W, R> call(final ConnectionFactory<W, R> connectionFactory) { return toConnectionProvider(connectionFactory); } }); } /*Visible for testing*/ ConnectionProvider<W, R> toConnectionProvider(final ConnectionFactory<W, R> factory) { final Observable<Instance<ConnectionProvider<W, R>>> providerStream = hosts.map(new Func1<Instance<SocketAddress>, Instance<ConnectionProvider<W, R>>>() { @Override public Instance<ConnectionProvider<W, R>> call(final Instance<SocketAddress> host) { final ConnectionProvider<W, R> pcp = newConnectionProviderForHost(host, factory); return new Instance<ConnectionProvider<W, R>>() { @Override public Observable<Void> getLifecycle() { return host.getLifecycle(); } @Override public ConnectionProvider<W, R> getValue() { return pcp; } }; } }); return new LoadBalancingProvider(factory, providerStream); } protected ConnectionProvider<W, R> newConnectionProviderForHost(Instance<SocketAddress> host, ConnectionFactory<W, R> connectionFactory) { /* * Bounds on the concurrency (concurrent connections) should be enforced at the request * processing level, providing a bound on number of connections is a difficult number * to determine. */ return PooledConnectionProvider.createUnbounded(connectionFactory, host.getValue()); } /*Visible for testing*/class LoadBalancingProvider extends ConnectionProvider<W, R> { private final HostHolder<W, R> hostHolder; public LoadBalancingProvider(ConnectionFactory<W, R> connectionFactory, Observable<Instance<ConnectionProvider<W, R>>> providerStream) { super(connectionFactory); hostHolder = new HostHolder<>(providerStream, eventListenerFactory); } @Override public ConnectionObservable<R, W> nextConnection() { return ConnectionObservable.createNew(new AbstractOnSubscribeFunc<R, W>() { @Override protected void doSubscribe(Subscriber<? super Connection<R, W>> sub, Action1<ConnectionObservable<R, W>> subscribeAllListenersAction) { final List<HostConnectionProvider<W, R>> providers = hostHolder.getProviders(); if (null == providers || providers.isEmpty()) { sub.onError(new NoSuchElementException("No hosts available.")); } HostConnectionProvider<W, R> hcp = loadBalancer.choose(providers); ConnectionObservable<R, W> nextConnection = hcp.getProvider().nextConnection(); if (hcp.getEventsListener() != null) { nextConnection.subscribeForEvents(hcp.getEventsListener()); } subscribeAllListenersAction.call(nextConnection); nextConnection.unsafeSubscribe(sub); } }); } @Override protected Observable<Void> doShutdown() { return hostHolder.shutdown(); } } }
2,265
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/internal/HostHolder.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.Instance; import netflix.ocelli.rxnetty.FailureListener; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.Subscription; import rx.functions.Action1; import rx.functions.Func1; import java.util.Collections; import java.util.List; class HostHolder<W, R> { private final Observable<List<HostConnectionProvider<W, R>>> providerStream; private volatile List<HostConnectionProvider<W, R>> providers; private Subscription streamSubscription; HostHolder(Observable<Instance<ConnectionProvider<W, R>>> providerStream, final Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory) { this.providerStream = providerStream.lift(new HostCollector<W, R>(eventListenerFactory)) .serialize()/*Host collector emits concurrently*/; providers = Collections.emptyList(); subscribeToHostStream(); } List<HostConnectionProvider<W, R>> getProviders() { return providers; } private void subscribeToHostStream() { streamSubscription = providerStream.subscribe(new Action1<List<HostConnectionProvider<W, R>>>() { @Override public void call(List<HostConnectionProvider<W, R>> hostConnectionProviders) { providers = hostConnectionProviders; } }); } public Observable<Void> shutdown() { return Observable.create(new OnSubscribe<Void>() { @Override public void call(Subscriber<? super Void> subscriber) { if (null != streamSubscription) { streamSubscription.unsubscribe(); } subscriber.onCompleted(); } }); } }
2,266
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/internal/HostConnectionProvider.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import java.util.Collection; public class HostConnectionProvider<W, R> { private final ConnectionProvider<W, R> provider; private final TcpClientEventListener eventsListener; private HostConnectionProvider(ConnectionProvider<W, R> provider) { this(provider, null); } HostConnectionProvider(ConnectionProvider<W, R> provider, TcpClientEventListener eventsListener) { this.provider = provider; this.eventsListener = eventsListener; } public static <W, R> boolean removeFrom(Collection<HostConnectionProvider<W, R>> c, ConnectionProvider<W, R> toRemove) { return c.remove(new HostConnectionProvider<W, R>(toRemove)); } public ConnectionProvider<W, R> getProvider() { return provider; } public TcpClientEventListener getEventsListener() { return eventsListener; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HostConnectionProvider)) { return false; } @SuppressWarnings("unchecked") HostConnectionProvider<W, R> that = (HostConnectionProvider<W, R>) o; if (provider != null? !provider.equals(that.provider) : that.provider != null) { return false; } return true; } @Override public int hashCode() { return provider != null? provider.hashCode() : 0; } }
2,267
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/internal/HostCollector.java
package netflix.ocelli.rxnetty.internal; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.Instance; import netflix.ocelli.rxnetty.FailureListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.Observable; import rx.Observable.Operator; import rx.Scheduler; import rx.Subscriber; import rx.functions.Action0; import rx.functions.Action1; import rx.functions.Actions; import rx.functions.Func1; import rx.schedulers.Schedulers; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; class HostCollector<W, R> implements Operator<List<HostConnectionProvider<W, R>>, Instance<ConnectionProvider<W, R>>> { private static final Logger logger = LoggerFactory.getLogger(HostCollector.class); protected final CopyOnWriteArrayList<HostConnectionProvider<W, R>> currentHosts = new CopyOnWriteArrayList<>(); private final Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory; HostCollector(Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory) { this.eventListenerFactory = eventListenerFactory; } @Override public Subscriber<? super Instance<ConnectionProvider<W, R>>> call(final Subscriber<? super List<HostConnectionProvider<W, R>>> o) { return new Subscriber<Instance<ConnectionProvider<W, R>>>() { @Override public void onCompleted() { o.onCompleted(); } @Override public void onError(Throwable e) { o.onError(e); } @Override public void onNext(Instance<ConnectionProvider<W, R>> i) { final ConnectionProvider<W, R> provider = i.getValue(); final TcpClientEventListener listener = eventListenerFactory.call(newFailureListener(provider, o)); final HostConnectionProvider<W, R> hcp = new HostConnectionProvider<>(i.getValue(), listener); addHost(hcp, o); bindToInstanceLifecycle(i, hcp, o); } }; } protected void removeHost(HostConnectionProvider<W, R> toRemove, Subscriber<? super List<HostConnectionProvider<W, R>>> hostListListener) { /*It's a copy-on-write list, so removal makes a copy with no interference to reads*/ currentHosts.remove(toRemove); hostListListener.onNext(currentHosts); } protected void addHost(HostConnectionProvider<W, R> toAdd, Subscriber<? super List<HostConnectionProvider<W, R>>> hostListListener) { /*It's a copy-on-write list, so addition makes a copy with no interference to reads*/ currentHosts.add(toAdd); hostListListener.onNext(currentHosts); } protected FailureListener newFailureListener(final ConnectionProvider<W, R> provider, final Subscriber<? super List<HostConnectionProvider<W, R>>> hostListListener) { return new FailureListener() { @Override public void remove() { HostConnectionProvider.removeFrom(currentHosts, provider); hostListListener.onNext(currentHosts); } @Override public void quarantine(long quarantineDuration, TimeUnit timeUnit) { quarantine(quarantineDuration, timeUnit, Schedulers.computation()); } @Override public void quarantine(long quarantineDuration, TimeUnit timeUnit, Scheduler timerScheduler) { final FailureListener fl = this; remove(); Observable.timer(quarantineDuration, timeUnit, timerScheduler) .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { TcpClientEventListener listener = eventListenerFactory.call(fl); addHost(new HostConnectionProvider<W, R>(provider, listener), hostListListener); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { logger.error("Error while adding back a quarantine instance to the load balancer.", throwable); } }); } }; } protected void bindToInstanceLifecycle(Instance<ConnectionProvider<W, R>> i, final HostConnectionProvider<W, R> hcp, final Subscriber<? super List<HostConnectionProvider<W, R>>> o) { i.getLifecycle() .finallyDo(new Action0() { @Override public void call() { removeHost(hcp, o); } }) .subscribe(Actions.empty(), new Action1<Throwable>() { @Override public void call(Throwable throwable) { // Do nothing as finallyDo takes care of both complete and error. } }); } }
2,268
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/WeightComparator.java
package netflix.ocelli.rxnetty.protocol; import netflix.ocelli.rxnetty.internal.HostConnectionProvider; import java.util.Comparator; /** * A comparator for {@link WeightAware} */ public class WeightComparator<W, R> implements Comparator<HostConnectionProvider<W, R>> { @Override public int compare(HostConnectionProvider<W, R> cp1, HostConnectionProvider<W, R> cp2) { WeightAware wa1 = (WeightAware) cp1.getEventsListener(); WeightAware wa2 = (WeightAware) cp2.getEventsListener(); return wa1.getWeight() > wa2.getWeight() ? 1 : -1; } }
2,269
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/WeightAware.java
package netflix.ocelli.rxnetty.protocol; import io.reactivex.netty.client.ConnectionProvider; import netflix.ocelli.loadbalancer.RandomWeightedLoadBalancer; /** * A property for RxNetty listeners that are used to also define weights for a particular host, typically in a * {@link RandomWeightedLoadBalancer} */ public interface WeightAware { /** * Returns the current weight of the associated host with this object. * <b>This method will be called every time {@link ConnectionProvider#nextConnection()} is called for every active * hosts, so it is recommended to not do any costly processing in this method, it should typically be a lookup of * an already calculated value.</b> * * @return The current weight. */ int getWeight(); }
2,270
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/tcp/WeightedTcpClientListener.java
package netflix.ocelli.rxnetty.protocol.tcp; import io.reactivex.netty.protocol.http.client.events.HttpClientEventsListener; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.rxnetty.protocol.WeightAware; /** * An {@link TcpClientEventListener} contract with an additional property defined by {@link WeightAware} */ public abstract class WeightedTcpClientListener extends HttpClientEventsListener implements WeightAware { }
2,271
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/tcp/TcpLoadBalancer.java
package netflix.ocelli.rxnetty.protocol.tcp; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.tcp.client.TcpClient; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.Instance; import netflix.ocelli.LoadBalancerStrategy; import netflix.ocelli.loadbalancer.ChoiceOfTwoLoadBalancer; import netflix.ocelli.loadbalancer.RandomWeightedLoadBalancer; import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer; import netflix.ocelli.loadbalancer.weighting.LinearWeightingStrategy; import netflix.ocelli.rxnetty.FailureListener; import netflix.ocelli.rxnetty.internal.AbstractLoadBalancer; import netflix.ocelli.rxnetty.internal.HostConnectionProvider; import netflix.ocelli.rxnetty.protocol.WeightComparator; import netflix.ocelli.rxnetty.protocol.http.WeightedHttpClientListener; import rx.Observable; import rx.functions.Func1; import java.net.SocketAddress; /** * An HTTP load balancer to be used with {@link TcpClient}. * * <h2>Failure detection</h2> * * For every host that this load balancer connects, it provides a way to register a {@link TcpClientEventListener} * instance that can detect failures based on the various events received. Upon detecting the failure, an appropriate * action can be taken for the host, using the provided {@link FailureListener}. * * <h2>Use with {@link TcpClient}</h2> * * In order to use this load balancer with RxNetty clients, one has to convert it to an instance of * {@link ConnectionProvider} by calling {@link #toConnectionProvider()} * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. */ public class TcpLoadBalancer<W, R> extends AbstractLoadBalancer<W, R> { private static final Func1<FailureListener, TcpClientEventListener> NO_LISTENER_FACTORY = new Func1<FailureListener, TcpClientEventListener>() { @Override public TcpClientEventListener call(FailureListener failureListener) { return null; } }; private TcpLoadBalancer(Observable<Instance<SocketAddress>> hosts, LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer) { this(hosts, loadBalancer, NO_LISTENER_FACTORY); } /** * Typically, static methods in this class would be used to create new instances of the load balancer with known * load balancing strategies. However, for any custom load balancing schemes, one can use this constructor directly. * * @param hosts Stream of hosts to use for load balancing. * @param loadBalancer The load balancing strategy. * @param eventListenerFactory A factory for creating new {@link TcpClientEventListener} per host. */ public TcpLoadBalancer(Observable<Instance<SocketAddress>> hosts, LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer, Func1<FailureListener, ? extends TcpClientEventListener> eventListenerFactory) { super(hosts, eventListenerFactory, loadBalancer); } /** * Creates a new load balancer using a round-robin load balancing strategy ({@link RoundRobinLoadBalancer}) over the * passed stream of hosts. The hosts ({@link SocketAddress}) emitted by the passed stream are used till their * lifecycle ends ({@code Observable} returned by {@link Instance#getLifecycle()} terminates). * * For using any failure detection schemes for the hosts, use {@link #roundRobin(Observable, Func1)} instead. * * @param hosts Stream of hosts to use for load balancing. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> TcpLoadBalancer<W, R> roundRobin(Observable<Instance<SocketAddress>> hosts) { return new TcpLoadBalancer<>(hosts, new RoundRobinLoadBalancer<HostConnectionProvider<W, R>>()); } /** * Creates a new load balancer using a round-robin load balancing strategy ({@link RoundRobinLoadBalancer}) over the * passed stream of hosts. The hosts ({@link SocketAddress}) emitted by the passed stream are used till their * lifecycle ends ({@code Observable} returned by {@link Instance#getLifecycle()} terminates) or are explicitly * removed by the passed failure detector. * * @param hosts Stream of hosts to use for load balancing. * @param failureDetector A factory for creating a {@link TcpClientEventListener} per host. The listeners based on * any criterion can then remove the host from the load balancing pool. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> TcpLoadBalancer<W, R> roundRobin(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, TcpClientEventListener> failureDetector) { return new TcpLoadBalancer<>(hosts, new RoundRobinLoadBalancer<HostConnectionProvider<W, R>>(), failureDetector); } /** * Creates a new load balancer using a weighted random load balancing strategy ({@link RandomWeightedLoadBalancer}) * over the passed stream of hosts. * * @param hosts Stream of hosts to use for load balancing. * @param listenerFactory A factory for creating {@link WeightedTcpClientListener} per active host. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> TcpLoadBalancer<W, R> weigthedRandom(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, WeightedTcpClientListener> listenerFactory) { LinearWeightingStrategy<HostConnectionProvider<W, R>> ws = new LinearWeightingStrategy<>( new Func1<HostConnectionProvider<W, R>, Integer>() { @Override public Integer call(HostConnectionProvider<W, R> cp) { WeightedHttpClientListener el = (WeightedHttpClientListener) cp.getEventsListener(); return el.getWeight(); } }); return new TcpLoadBalancer<W, R>(hosts, new RandomWeightedLoadBalancer<HostConnectionProvider<W, R>>(ws), listenerFactory); } /** * Creates a new load balancer using a power of two choices load balancing strategy ({@link ChoiceOfTwoLoadBalancer}) * over the passed stream of hosts. * * @param hosts Stream of hosts to use for load balancing. * @param listenerFactory A factory for creating {@link WeightedTcpClientListener} per active host. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> TcpLoadBalancer<W, R> choiceOfTwo(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, WeightedTcpClientListener> listenerFactory) { return new TcpLoadBalancer<W, R>(hosts, new ChoiceOfTwoLoadBalancer<>(new WeightComparator<W, R>()), listenerFactory); } }
2,272
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/tcp/ComparableTcpClientListener.java
package netflix.ocelli.rxnetty.protocol.tcp; import io.reactivex.netty.protocol.tcp.client.events.TcpClientEventListener; import netflix.ocelli.loadbalancer.ChoiceOfTwoLoadBalancer; /** * An {@link TcpClientEventListener} contract which is also a {@link Comparable}. These listeners are typically used * with a load balancer that chooses the best among two servers, eg: {@link ChoiceOfTwoLoadBalancer} */ public abstract class ComparableTcpClientListener extends TcpClientEventListener implements Comparable<ComparableTcpClientListener> { }
2,273
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/http/WeightedHttpClientListener.java
package netflix.ocelli.rxnetty.protocol.http; import io.reactivex.netty.protocol.http.client.events.HttpClientEventsListener; import netflix.ocelli.rxnetty.protocol.WeightAware; /** * An {@link HttpClientEventsListener} contract with an additional property defined by {@link WeightAware} */ public abstract class WeightedHttpClientListener extends HttpClientEventsListener implements WeightAware { }
2,274
0
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol
Create_ds/ocelli/ocelli-rxnetty/src/main/java/netflix/ocelli/rxnetty/protocol/http/HttpLoadBalancer.java
package netflix.ocelli.rxnetty.protocol.http; import io.reactivex.netty.client.ConnectionProvider; import io.reactivex.netty.protocol.http.client.HttpClient; import io.reactivex.netty.protocol.http.client.events.HttpClientEventsListener; import netflix.ocelli.Instance; import netflix.ocelli.LoadBalancerStrategy; import netflix.ocelli.loadbalancer.ChoiceOfTwoLoadBalancer; import netflix.ocelli.loadbalancer.RandomWeightedLoadBalancer; import netflix.ocelli.loadbalancer.RoundRobinLoadBalancer; import netflix.ocelli.loadbalancer.weighting.LinearWeightingStrategy; import netflix.ocelli.rxnetty.FailureListener; import netflix.ocelli.rxnetty.internal.AbstractLoadBalancer; import netflix.ocelli.rxnetty.internal.HostConnectionProvider; import netflix.ocelli.rxnetty.protocol.WeightComparator; import rx.Observable; import rx.functions.Func1; import java.net.SocketAddress; /** * An HTTP load balancer to be used with {@link HttpClient}. * * <h2>Failure detection</h2> * * For every host that this load balancer connects, it provides a way to register a {@link HttpClientEventsListener} * instance that can detect failures based on the various events received. Upon detecting the failure, an appropriate * action can be taken for the host, using the provided {@link FailureListener}. * * <h2>Use with {@link HttpClient}</h2> * * In order to use this load balancer with RxNetty clients, one has to convert it to an instance of * {@link ConnectionProvider} by calling {@link #toConnectionProvider()} * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. */ public class HttpLoadBalancer<W, R> extends AbstractLoadBalancer<W, R> { private static final Func1<FailureListener, HttpClientEventsListener> NO_LISTENER_FACTORY = new Func1<FailureListener, HttpClientEventsListener>() { @Override public HttpClientEventsListener call(FailureListener failureListener) { return null; } }; private HttpLoadBalancer(Observable<Instance<SocketAddress>> hosts, LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer) { this(hosts, loadBalancer, NO_LISTENER_FACTORY); } /** * Typically, static methods in this class would be used to create new instances of the load balancer with known * load balancing strategies. However, for any custom load balancing schemes, one can use this constructor directly. * * @param hosts Stream of hosts to use for load balancing. * @param loadBalancer The load balancing strategy. * @param eventListenerFactory A factory for creating new {@link HttpClientEventsListener} per host. */ public HttpLoadBalancer(Observable<Instance<SocketAddress>> hosts, LoadBalancerStrategy<HostConnectionProvider<W, R>> loadBalancer, Func1<FailureListener, ? extends HttpClientEventsListener> eventListenerFactory) { super(hosts, eventListenerFactory, loadBalancer); } /** * Creates a new load balancer using a round-robin load balancing strategy ({@link RoundRobinLoadBalancer}) over the * passed stream of hosts. The hosts ({@link SocketAddress}) emitted by the passed stream are used till their * lifecycle ends ({@code Observable} returned by {@link Instance#getLifecycle()} terminates). * * For using any failure detection schemes for the hosts, use {@link #roundRobin(Observable, Func1)} instead. * * @param hosts Stream of hosts to use for load balancing. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> HttpLoadBalancer<W, R> roundRobin(Observable<Instance<SocketAddress>> hosts) { return new HttpLoadBalancer<W, R>(hosts, new RoundRobinLoadBalancer<HostConnectionProvider<W, R>>()); } /** * Creates a new load balancer using a round-robin load balancing strategy ({@link RoundRobinLoadBalancer}) over the * passed stream of hosts. The hosts ({@link SocketAddress}) emitted by the passed stream are used till their * lifecycle ends ({@code Observable} returned by {@link Instance#getLifecycle()} terminates) or are explicitly * removed by the passed failure detector. * * @param hosts Stream of hosts to use for load balancing. * @param failureDetector A factory for creating a {@link HttpClientEventsListener} per host. The listeners based on * any criterion can then remove the host from the load balancing pool. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> HttpLoadBalancer<W, R> roundRobin(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, HttpClientEventsListener> failureDetector) { return new HttpLoadBalancer<>(hosts, new RoundRobinLoadBalancer<HostConnectionProvider<W, R>>(), failureDetector); } /** * Creates a new load balancer using a weighted random load balancing strategy ({@link RandomWeightedLoadBalancer}) * over the passed stream of hosts. * * @param hosts Stream of hosts to use for load balancing. * @param listenerFactory A factory for creating {@link WeightedHttpClientListener} per active host. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> HttpLoadBalancer<W, R> weigthedRandom(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, WeightedHttpClientListener> listenerFactory) { LinearWeightingStrategy<HostConnectionProvider<W, R>> ws = new LinearWeightingStrategy<>( new Func1<HostConnectionProvider<W, R>, Integer>() { @Override public Integer call(HostConnectionProvider<W, R> cp) { WeightedHttpClientListener el = (WeightedHttpClientListener) cp.getEventsListener(); return el.getWeight(); } }); return new HttpLoadBalancer<W, R>(hosts, new RandomWeightedLoadBalancer<HostConnectionProvider<W, R>>(ws), listenerFactory); } /** * Creates a new load balancer using a power of two choices load balancing strategy ({@link ChoiceOfTwoLoadBalancer}) * over the passed stream of hosts. * * @param hosts Stream of hosts to use for load balancing. * @param listenerFactory A factory for creating {@link WeightedHttpClientListener} per active host. * * @param <W> Type of Objects written on the connections created by this load balancer. * @param <R> Type of Objects read from the connections created by this load balancer. * * @return New load balancer instance. */ public static <W, R> HttpLoadBalancer<W, R> choiceOfTwo(Observable<Instance<SocketAddress>> hosts, Func1<FailureListener, WeightedHttpClientListener> listenerFactory) { return new HttpLoadBalancer<W, R>(hosts, new ChoiceOfTwoLoadBalancer<>(new WeightComparator<W, R>()), listenerFactory); } }
2,275
0
Create_ds/ocelli/ocelli-eureka2/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-eureka2/src/test/java/netflix/ocelli/eureka2/Eureka2InterestManagerTest.java
package netflix.ocelli.eureka2; import com.netflix.eureka2.client.EurekaInterestClient; import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.interests.Interest; import com.netflix.eureka2.interests.Interests; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.ServicePort; import netflix.ocelli.Instance; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import rx.Observable; import java.net.SocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.concurrent.TimeUnit; @RunWith(MockitoJUnitRunner.class) public class Eureka2InterestManagerTest { @Mock private EurekaInterestClient clientMock; private Eureka2InterestManager membershipSource; public static final InstanceInfo INSTANCE_1 = new InstanceInfo.Builder() .withId("id_serviceA") .withApp("ServiceA") .withAppGroup("ServiceA_1") .withStatus(InstanceInfo.Status.UP) .withPorts(new HashSet<ServicePort>(Collections.singletonList(new ServicePort(8000, false)))) .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) .build(); public static final InstanceInfo INSTANCE_2 = new InstanceInfo.Builder() .withId("id_serviceA_2") .withApp("ServiceA") .withAppGroup("ServiceA_1") .withStatus(InstanceInfo.Status.UP) .withPorts(new HashSet<ServicePort>(Collections.singletonList(new ServicePort(8001, false)))) .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) .build(); public static final ChangeNotification<InstanceInfo> ADD_INSTANCE_1 = new ChangeNotification<InstanceInfo>(ChangeNotification.Kind.Add, INSTANCE_1); public static final ChangeNotification<InstanceInfo> ADD_INSTANCE_2 = new ChangeNotification<InstanceInfo>(ChangeNotification.Kind.Add, INSTANCE_2); @Before public void setUp() throws Exception { membershipSource = new Eureka2InterestManager(clientMock); } @Test public void testVipBasedInterest() throws Exception { Interest<InstanceInfo> interest = Interests.forVips("test-vip"); Mockito.when(clientMock.forInterest(interest)).thenReturn(Observable.just(ADD_INSTANCE_1, ADD_INSTANCE_2)); List<Instance<SocketAddress>> instances = membershipSource .forInterest(interest) .take(2) .toList().toBlocking() .toFuture() .get(1, TimeUnit.SECONDS); Assert.assertEquals(2, instances.size()); System.out.println("instances = " + instances); } }
2,276
0
Create_ds/ocelli/ocelli-eureka2/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-eureka2/src/main/java/netflix/ocelli/eureka2/Eureka2InterestManager.java
package netflix.ocelli.eureka2; import com.netflix.eureka2.client.EurekaInterestClient; import com.netflix.eureka2.client.Eurekas; import com.netflix.eureka2.client.resolver.ServerResolver; import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.interests.Interest; import com.netflix.eureka2.interests.Interests; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.ServicePort; import netflix.ocelli.Instance; import netflix.ocelli.InstanceManager; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.functions.Action1; import rx.functions.Func1; import javax.inject.Inject; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.HashSet; /** * @author Nitesh Kant */ public class Eureka2InterestManager { private final EurekaInterestClient client; private static final DefaultMapper defaultMapper = new DefaultMapper(); public Eureka2InterestManager(ServerResolver eurekaResolver) { client = Eurekas.newInterestClientBuilder().withServerResolver(eurekaResolver).build(); } @Inject public Eureka2InterestManager(EurekaInterestClient client) { this.client = client; } public Observable<Instance<SocketAddress>> forVip(String... vips) { return forInterest(Interests.forVips(vips)); } public Observable<Instance<SocketAddress>> forInterest(Interest<InstanceInfo> interest) { return forInterest(interest, defaultMapper); } public Observable<Instance<SocketAddress>> forInterest(final Interest<InstanceInfo> interest, final Func1<InstanceInfo, SocketAddress> instanceInfoToHost) { return Observable.create(new OnSubscribe<Instance<SocketAddress>>() { @Override public void call(Subscriber<? super Instance<SocketAddress>> s) { final InstanceManager<SocketAddress> subject = InstanceManager.create(); s.add(client .forInterest(interest) .subscribe(new Action1<ChangeNotification<InstanceInfo>>() { @Override public void call(ChangeNotification<InstanceInfo> notification) { SocketAddress host = instanceInfoToHost.call(notification.getData()); switch (notification.getKind()) { case Add: subject.add(host); break; case Delete: subject.remove(host); break; case Modify: subject.remove(host); subject.add(host); break; default: break; } } })); subject.subscribe(s); } }); } protected static class DefaultMapper implements Func1<InstanceInfo, SocketAddress> { @Override public SocketAddress call(InstanceInfo instanceInfo) { String ipAddress = instanceInfo.getDataCenterInfo().getDefaultAddress().getIpAddress(); HashSet<ServicePort> servicePorts = instanceInfo.getPorts(); ServicePort portToUse = servicePorts.iterator().next(); return new InetSocketAddress(ipAddress, portToUse.getPort()); } } }
2,277
0
Create_ds/ocelli/ocelli-eureka/src/test/java/netflix/ocelli
Create_ds/ocelli/ocelli-eureka/src/test/java/netflix/ocelli/eureka/EurekaInterestManagerTest.java
package netflix.ocelli.eureka; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import junit.framework.Assert; import netflix.ocelli.InstanceCollector; import netflix.ocelli.util.RxUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import rx.schedulers.TestScheduler; import com.google.common.collect.Sets; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.discovery.DiscoveryClient; import com.netflix.discovery.shared.Application; @RunWith(MockitoJUnitRunner.class) public class EurekaInterestManagerTest { @Mock private DiscoveryClient client; @Mock private Application application; @Test public void testAddRemoveInstances() { InstanceInfo i1 = createInstance(1); InstanceInfo i2 = createInstance(2); InstanceInfo i3 = createInstance(3); InstanceInfo i4 = createInstance(4); Mockito.when(client.getApplication("foo")).thenReturn(application); AtomicReference<List<InstanceInfo>> result = new AtomicReference<List<InstanceInfo>>(); TestScheduler scheduler = new TestScheduler(); EurekaInterestManager eureka = new EurekaInterestManager(client); eureka.newInterest() .forApplication("foo") .withRefreshInterval(1, TimeUnit.SECONDS) .withScheduler(scheduler) .asObservable() .compose(InstanceCollector.<InstanceInfo>create()) .subscribe(RxUtil.set(result)); Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i1, i2)); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); Assert.assertEquals(Sets.newHashSet(i2, i1), Sets.newHashSet(result.get())); Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i1, i2, i3)); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); Assert.assertEquals(Sets.newHashSet(i3, i2, i1), Sets.newHashSet(result.get())); Mockito.when(application.getInstances()).thenReturn(Arrays.asList(i3, i4)); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); Assert.assertEquals(Sets.newHashSet(i3, i4), Sets.newHashSet(result.get())); Mockito.when(application.getInstances()).thenReturn(Arrays.<InstanceInfo>asList()); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); Assert.assertEquals(Sets.newHashSet(), Sets.newHashSet(result.get())); } InstanceInfo createInstance(int id) { return InstanceInfo.Builder.newBuilder() .setHostName("localhost:800" + id) .setAppName("foo") .setStatus(InstanceStatus.UP) .build(); } }
2,278
0
Create_ds/ocelli/ocelli-eureka/src/main/java/netflix/ocelli
Create_ds/ocelli/ocelli-eureka/src/main/java/netflix/ocelli/eureka/EurekaInterestManager.java
package netflix.ocelli.eureka; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.DiscoveryClient; import netflix.ocelli.Instance; import netflix.ocelli.SnapshotToInstance; import rx.Observable; import rx.Scheduler; import rx.functions.Func0; import rx.functions.Func1; import rx.schedulers.Schedulers; import javax.inject.Inject; import java.util.List; import java.util.concurrent.TimeUnit; /** * Wrapper for v1 DisoveryClient which offers a convenient DSL to express interests * in host streams. * * {@code * <pre> * RoundRobinLoadBalancer lb = RoundRobinLoadBalancer.create(); * * EurekaInterestManager manager = new EurekaInterestMangaer(discoveryClient); * Subscription sub = manager * .newInterest() * .forApplication("applicationName") * .withRefreshInterval(30, TimeUnit.SECONDS) * .withScheduler(scheduler) * .asObservable() * .compose(InstanceCollector.<InstanceInfo>create()) * .subscribe(lb); * * lb.flatMap(operation); * </pre> * } * * @author elandau */ public class EurekaInterestManager { private static final int DEFAULT_REFRESH_RATE = 30; private final DiscoveryClient client; @Inject public EurekaInterestManager(DiscoveryClient client) { this.client = client; } public InterestDsl newInterest() { return new InterestDsl(client); } /** * DSL to simplify specifying the interest * * @author elandau */ public static class InterestDsl { private final DiscoveryClient client; private String appName; private String vip; private boolean secure = false; private String region; private long interval = DEFAULT_REFRESH_RATE; private TimeUnit intervalUnits = TimeUnit.SECONDS; private Scheduler scheduler = Schedulers.computation(); private InterestDsl(DiscoveryClient client) { this.client = client; } public InterestDsl withScheduler(Scheduler scheduler) { this.scheduler = scheduler; return this; } public InterestDsl withRefreshInterval(long interval, TimeUnit units) { this.interval = interval; this.intervalUnits = units; return this; } public InterestDsl forApplication(String appName) { this.appName = appName; return this; } public InterestDsl forVip(String vip) { this.vip = vip; return this; } public InterestDsl forRegion(String region) { this.region = region; return this; } public InterestDsl isSecure(boolean secure) { this.secure = secure; return this; } public Observable<Instance<InstanceInfo>> asObservable() { return create(createLister()); } private Observable<Instance<InstanceInfo>> create(final Func0<List<InstanceInfo>> lister) { return Observable .interval(interval, intervalUnits, scheduler) .onBackpressureDrop() .flatMap(new Func1<Long, Observable<List<InstanceInfo>>>() { @Override public Observable<List<InstanceInfo>> call(Long t1) { try { return Observable.just(lister.call()); } catch (Exception e) { return Observable.empty(); } } }, 1) .serialize() .compose(new SnapshotToInstance<InstanceInfo>()); } private Func0<List<InstanceInfo>> createLister() { if (appName != null) { if (vip != null) { return _forVipAndApplication(vip, appName, secure); } else { if (region != null) { return _forApplicationAndRegion(appName, region); } else { return _forApplication(appName); } } } else if (vip != null) { if (region != null) { return _forVip(vip, secure); } else { return _forVipAndRegion(vip, secure, region); } } throw new IllegalArgumentException("Interest combination not supported"); } private Func0<List<InstanceInfo>> _forApplication(final String appName) { return new Func0<List<InstanceInfo>>() { @Override public List<InstanceInfo> call() { return client.getApplication(appName).getInstances(); } }; } private Func0<List<InstanceInfo>> _forApplicationAndRegion(final String appName, final String region) { return new Func0<List<InstanceInfo>>() { @Override public List<InstanceInfo> call() { return client.getApplicationsForARegion(region).getRegisteredApplications(appName).getInstances(); } }; } private Func0<List<InstanceInfo>> _forVip(final String vip, final boolean secure) { return new Func0<List<InstanceInfo>>() { @Override public List<InstanceInfo> call() { return client.getInstancesByVipAddress(vip, secure); } }; } private Func0<List<InstanceInfo>> _forVipAndRegion(final String vip, final boolean secure, final String region) { return new Func0<List<InstanceInfo>>() { @Override public List<InstanceInfo> call() { return client.getInstancesByVipAddress(vip, secure, region); } }; } private Func0<List<InstanceInfo>> _forVipAndApplication(final String vip, final String appName, final boolean secure) { return new Func0<List<InstanceInfo>>() { @Override public List<InstanceInfo> call() { return client.getInstancesByVipAddressAndAppName(vip, appName, secure); } }; } } }
2,279
0
Create_ds/datasketches-memory/tools/scripts
Create_ds/datasketches-memory/tools/scripts/assets/CheckMemoryJar.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.tools.scripts; import java.io.File; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.apache.datasketches.memory.MapHandle; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableHandle; import org.apache.datasketches.memory.WritableMemory; public class CheckMemoryJar { public void printJDK() { String JdkVersionString = System.getProperty("java.version"); int JdkMajorVersion = getJavaMajorVersion(JdkVersionString); println("JDK Full Version : " + JdkVersionString); println("JDK Major Version: " + JdkMajorVersion); println(""); } public void checkHeapWritableMemory() { try { String str = "1 - Heap WritableMemory Successful"; WritableMemory mem = WritableMemory.allocate(2 * str.length()); writeReadAndPrintString(mem, str); } catch (Exception ex) { exitOnError("Heap Writable Memory", ex); } } public void checkAllocateDirect() throws Exception { try { String str = "2 - Allocate Direct Successful"; WritableHandle wh = WritableMemory.allocateDirect(2 * str.length()); WritableMemory wmem = wh.getWritable(); writeReadAndPrintString(wmem, str); wh.close(); } catch (Exception ex) { exitOnError("Allocate Direct", ex); } } public void checkByteBuffer() throws Exception { try { String str = "3 - Map ByteBuffer Successful"; ByteBuffer bb = ByteBuffer.allocateDirect(2 * str.length()); bb.order(ByteOrder.nativeOrder()); WritableMemory wmem = WritableMemory.writableWrap(bb); writeReadAndPrintString(wmem, str); } catch (Exception ex) { exitOnError("Map ByteBuffer", ex); } } public void checkMap(String mappedFilePath) throws Exception { try { String str = "4 - Memory Map Successful"; File file = new File(mappedFilePath); MapHandle mh = Memory.map(file); Memory mem = mh.get(); mh.close(); println(str); } catch (Exception ex) { exitOnError("Memory Map", ex); } } public static void main(final String[] args) throws Exception { if (args.length < 1) { System.out.println("Please provide the full path to the memory mapped file!"); System.exit(1); } String mappedFilePath = args[0]; CheckMemoryJar check = new CheckMemoryJar(); check.printJDK(); check.checkHeapWritableMemory(); check.checkAllocateDirect(); check.checkByteBuffer(); check.checkMap(mappedFilePath); println(""); println("All checks passed."); } /**********************/ private static void writeReadAndPrintString(WritableMemory wmem, String str) { int len = str.length(); char[] cArr1 = str.toCharArray(); wmem.putCharArray(0, cArr1, 0, len); char[] cArr2 = new char[len]; wmem.getCharArray(0, cArr2, 0, len); String s2 = String.valueOf(cArr2); println(s2); } private static void exitOnError(String checkName, Exception ex){ println(checkName + " check failed. Error: " + ex.toString()); System.exit(1); } private static int getJavaMajorVersion(final String jdkVersion) { int[] verArr = parseJavaVersion(jdkVersion); return (verArr[0] == 1) ? verArr[1] : verArr[0]; } /** * Returns first two number groups of the java version string. * @param jdkVersion the java version string from System.getProperty("java.version"). * @return first two number groups of the java version string. */ private static int[] parseJavaVersion(final String jdkVersion) { final int p0, p1; try { String[] parts = jdkVersion.trim().split("[^0-9\\.]");//grab only number groups and "." parts = parts[0].split("\\."); //split out the number groups p0 = Integer.parseInt(parts[0]); //the first number group p1 = (parts.length > 1) ? Integer.parseInt(parts[1]) : 0; //2nd number group, or 0 } catch (final NumberFormatException | ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Improper Java -version string: " + jdkVersion + "\n" + e); } return new int[] {p0, p1}; } private static void println(Object obj) { System.out.println(obj.toString()); } }
2,280
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/module-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ module org.apache.datasketches.memory { requires java.base; requires java.logging; requires jdk.unsupported; exports org.apache.datasketches.memory; }
2,281
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory;
2,282
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/MemoryException.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory; /** * Specific RuntimeExceptions for the datasketches-memory component. * * @author Lee Rhodes * */ public class MemoryException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs a new runtime exception with the specified detail message. The cause is not * initialized, and may subsequently be initialized by a call to * Throwable.initCause(java.lang.Throwable). * * @param message the detail message. The detail message is saved for later retrieval by the * Throwable.getMessage() method. */ public MemoryException(final String message) { super(message); } }
2,283
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/VirtualMachineMemory.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Extracts a version-dependent reference to the `jdk.internal.misc.VM` into a standalone * class. The package name for VM has changed in later versions. The appropriate * class will be loaded by the class loader depending on the Java version that is used. * For more information, see: https://openjdk.java.net/jeps/238 */ public final class VirtualMachineMemory { private static final Class<?> VM_CLASS; private static final Method VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD; private static final boolean isPageAligned; static { try { VM_CLASS = Class.forName("jdk.internal.misc.VM"); VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD = VM_CLASS.getDeclaredMethod("isDirectMemoryPageAligned"); VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD.setAccessible(true); isPageAligned = (boolean) VM_IS_DIRECT_MEMORY_PAGE_ALIGNED_METHOD.invoke(null); //static method } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { throw new RuntimeException("Could not acquire jdk.internal.misc.VM: " + e.getClass()); } } /** * Returns true if the direct buffers should be page aligned. * @return flag that determines whether direct buffers should be page aligned. */ public static boolean getIsPageAligned() { return isPageAligned; } }
2,284
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/MemoryCleaner.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import jdk.internal.ref.Cleaner; /** * Extracts a version-dependent reference to the `jdk.internal.ref.Cleaner` into * a standalone class. The package name for Cleaner has changed in * later versions. The appropriate class will be loaded by the class loader * depending on the Java version that is used. * For more information, see: https://openjdk.java.net/jeps/238 */ //@SuppressWarnings("restriction") public class MemoryCleaner { private final Cleaner cleaner; /** * Creates a new `jdk.internal.ref.Cleaner`. * @param referent the object to be cleaned * @param deallocator - the cleanup code to be run when the cleaner is invoked. * return MemoryCleaner */ public MemoryCleaner(final Object referent, final Runnable deallocator) { cleaner = Cleaner.create(referent, deallocator); } /** * Runs this cleaner, if it has not been run before. */ public void clean() { cleaner.clean(); } }
2,285
0
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java11/src/main/java/org/apache/datasketches/memory/internal/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal;
2,286
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/DruidIssue11544Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.apache.datasketches.memory.DefaultMemoryRequestServer; import org.apache.datasketches.memory.MemoryRequestServer; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; /** * The original design provided the MemoryRequestServer callback only for Memory segments allocated via * <i>WritableMemory.allocateDirect(...)</i> calls. Memory segments allocated via * <i>WritableMemory.wrap(ByteBuffer)</i> did not have this capability. This was a major oversight since * all off-heap memory in Druid is allocated using ByteBuffers! It is unusual that no one has * uncovered this until August 2021. Nonetheless, the fix involves instrumenting all the paths involved * in providing this callback mechanism for wrapped ByteBuffers. * * <p>This issue was first identified in Druid Issue #11544 and then posted as DataSketches-java Issue #358. * But the actual source of the problem was in Memory.</p> * * <p>This test mimics the Druid issue but at a much smaller scale.</p> * * @author Lee Rhodes * */ public class DruidIssue11544Test { @Test public void withByteBuffer() { int initialLongs = 1000; int size1 = initialLongs * 8; //Start with a ByteBuffer ByteBuffer bb = ByteBuffer.allocateDirect(size1); bb.order(ByteOrder.nativeOrder()); //Wrap bb into WritableMemory WritableMemory mem1 = WritableMemory.writableWrap(bb); assertTrue(mem1.isDirectResource()); //confirm mem1 is off-heap //Acquire the DefaultMemoryRequestServer //NOTE: it is a policy decision to allow the DefaultMemoryServer to be set as a default. // It might be set to null. So we need to check what the current policy is. MemoryRequestServer svr = mem1.getMemoryRequestServer(); if (svr == null) { svr = new DefaultMemoryRequestServer(); } assertNotNull(svr); //Request Bigger Memory int size2 = size1 * 2; WritableMemory mem2 = svr.request(mem1, size2); //Confirm that mem2 is on the heap (the default) and 2X size1 assertFalse(mem2.isDirectResource()); assertEquals(mem2.getCapacity(), size2); //Move data to new memory mem1.copyTo(0, mem2, 0, size1); //Prepare to request deallocation //In the DefaultMemoryRequestServer, this is a no-op, so nothing is actually deallocated. svr.requestClose(mem1, mem2); assertTrue(mem1.isValid()); assertTrue(mem2.isValid()); //Now we are on the heap and need to grow again: int size3 = size2 * 2; WritableMemory mem3 = svr.request(mem2, size3); //Confirm that mem3 is still on the heap and 2X of size2 assertFalse(mem3.isDirectResource()); assertEquals(mem3.getCapacity(), size3); //Move data to new memory mem2.copyTo(0, mem3, 0, size2); //Prepare to request deallocation svr.requestClose(mem2, mem3); //No-op assertTrue(mem2.isValid()); assertTrue(mem3.isValid()); } }
2,287
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/NativeWritableBufferImplTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.apache.datasketches.memory.Buffer; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.MemoryBoundsException; import org.apache.datasketches.memory.ReadOnlyException; import org.apache.datasketches.memory.WritableBuffer; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; public class NativeWritableBufferImplTest { //Simple Native direct @Test public void checkNativeCapacityAndClose() { int memCapacity = 64; WritableMemory wmem = WritableMemory.allocateDirect(memCapacity); WritableBuffer wbuf = wmem.asWritableBuffer(); assertEquals(wbuf.getCapacity(), memCapacity); wmem.close(); //intentional assertFalse(wbuf.isValid()); } //Simple Heap arrays @Test public void checkBooleanArray() { boolean[] srcArray = { true, false, true, false, false, true, true, false }; boolean[] dstArray = new boolean[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getBooleanArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getBooleanArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } assertTrue(buf.isHeapResource()); } @Test public void checkByteArray() { byte[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; byte[] dstArray = new byte[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getByteArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getByteArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkCharArray() { char[] srcArray = { 1, 2, 3, 4, 5, 6, 7, 8 }; char[] dstArray = new char[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getCharArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getCharArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkShortArray() { short[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; short[] dstArray = new short[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getShortArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getShortArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkIntArray() { int[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; int[] dstArray = new int[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getIntArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getIntArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkLongArray() { long[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; long[] dstArray = new long[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getLongArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getLongArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkFloatArray() { float[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; float[] dstArray = new float[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getFloatArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getFloatArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkDoubleArray() { double[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; double[] dstArray = new double[8]; Buffer buf = Memory.wrap(srcArray).asBuffer(); buf.getDoubleArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); wbuf.getDoubleArray(dstArray, 0, 8); for (int i = 0; i < 8; i++) { assertEquals(dstArray[i], srcArray[i]); } } @Test public void checkNativeBaseBound() { int memCapacity = 64; try (WritableMemory wmem = WritableMemory.allocateDirect(memCapacity)) { WritableBuffer wbuf = wmem.asWritableBuffer(); wbuf.toHexString("Bounds Exception", memCapacity, 8); //Bounds Exception fail("Should have thrown MemoryBoundsException"); } catch (MemoryBoundsException e) { //ok } } @Test public void checkNativeSrcArrayBound() { long memCapacity = 64; try (WritableMemory wmem = WritableMemory.allocateDirect(memCapacity)) { WritableBuffer wbuf = wmem.asWritableBuffer(); byte[] srcArray = { 1, -2, 3, -4 }; wbuf.putByteArray(srcArray, 0, 5); //should be 4! fail("Should have thrown MemoryBoundsException"); } catch (MemoryBoundsException e) { //pass } } @Test(expectedExceptions = MemoryBoundsException.class) public void checkRegionBounds() { int memCapacity = 64; try (WritableMemory wmem = WritableMemory.allocateDirect(memCapacity)) { WritableBuffer wbuf = wmem.asWritableBuffer(); wbuf.writableRegion(1, 64, wbuf.getByteOrder()); //off by one } } @Test public void checkByteBufferWrap() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocate(memCapacity); byteBuf.order(ByteOrder.nativeOrder()); for (int i = 0; i < memCapacity; i++) { byteBuf.put(i, (byte) i); } WritableBuffer wbuf = WritableBuffer.writableWrap(byteBuf); for (int i = 0; i < memCapacity; i++) { assertEquals(wbuf.getByte(), byteBuf.get(i)); } assertTrue(wbuf.isByteBufferResource()); ByteBuffer byteBuf2 = ((ResourceImpl)wbuf).getByteBuffer(); assertEquals(byteBuf2, byteBuf); //println( mem.toHexString("HeapBB", 0, memCapacity)); } @Test public void checkWrapWithBBReadonly1() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocate(memCapacity); byteBuf.order(ByteOrder.nativeOrder()); for (int i = 0; i < memCapacity; i++) { byteBuf.put(i, (byte) i); } Buffer buf = WritableBuffer.writableWrap(byteBuf); for (int i = 0; i < memCapacity; i++) { assertEquals(buf.getByte(), byteBuf.get(i)); } //println(mem.toHexString("HeapBB", 0, memCapacity)); } @Test(expectedExceptions = ReadOnlyException.class) public void checkWrapWithBBReadonly2() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocate(memCapacity); byteBuf.order(ByteOrder.nativeOrder()); ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer(); byteBufRO.order(ByteOrder.nativeOrder()); assertTrue(true); WritableBuffer wbuf = WritableBuffer.writableWrap(byteBufRO); assertTrue(wbuf.isReadOnly()); } @Test public void checkWrapWithDirectBBReadonly() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity); byteBuf.order(ByteOrder.nativeOrder()); for (int i = 0; i < memCapacity; i++) { byteBuf.put(i, (byte) i); } ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer(); byteBufRO.order(ByteOrder.nativeOrder()); Buffer buf = Buffer.wrap(byteBufRO); for (int i = 0; i < memCapacity; i++) { assertEquals(buf.getByte(), byteBuf.get(i)); } //println(mem.toHexString("HeapBB", 0, memCapacity)); } @Test(expectedExceptions = ReadOnlyException.class) public void checkWrapWithDirectBBReadonlyPut() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity); ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer(); byteBufRO.order(ByteOrder.nativeOrder()); WritableBuffer.writableWrap(byteBufRO); } @Test public void checkByteBufferWrapDirectAccess() { int memCapacity = 64; ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity); byteBuf.order(ByteOrder.nativeOrder()); for (int i = 0; i < memCapacity; i++) { byteBuf.put(i, (byte) i); } Buffer buf = Buffer.wrap(byteBuf); for (int i = 0; i < memCapacity; i++) { assertEquals(buf.getByte(), byteBuf.get(i)); } //println( mem.toHexString("HeapBB", 0, memCapacity)); } @Test public void checkIsDirect() { int memCapacity = 64; WritableBuffer mem = WritableMemory.allocate(memCapacity).asWritableBuffer(); assertFalse(mem.isDirectResource()); try (WritableMemory mem2 = WritableMemory.allocateDirect(memCapacity)) { WritableBuffer wbuf = mem2.asWritableBuffer(); assertTrue(wbuf.isDirectResource()); } } @Test public void checkIsReadOnly() { long[] srcArray = { 1, -2, 3, -4, 5, -6, 7, -8 }; WritableBuffer wbuf = WritableMemory.writableWrap(srcArray).asWritableBuffer(); assertFalse(wbuf.isReadOnly()); Buffer buf = wbuf; assertFalse(buf.isReadOnly()); for (int i = 0; i < srcArray.length; i++) { assertEquals(buf.getLong(), srcArray[i]); } } @Test public void checkGoodBounds() { ResourceImpl.checkBounds(50, 50, 100); } @Test public void checkCompareToHeap() { byte[] arr1 = new byte[] {0, 1, 2, 3}; byte[] arr2 = new byte[] {0, 1, 2, 4}; byte[] arr3 = new byte[] {0, 1, 2, 3, 4}; Buffer buf1 = Memory.wrap(arr1).asBuffer(); Buffer buf2 = Memory.wrap(arr2).asBuffer(); Buffer buf3 = Memory.wrap(arr3).asBuffer(); int comp = buf1.compareTo(0, 3, buf2, 0, 3); assertEquals(comp, 0); comp = buf1.compareTo(0, 4, buf2, 0, 4); assertEquals(comp, -1); comp = buf2.compareTo(0, 4, buf1, 0, 4); assertEquals(comp, 1); //different lengths comp = buf1.compareTo(0, 4, buf3, 0, 5); assertEquals(comp, -1); comp = buf3.compareTo(0, 5, buf1, 0, 4); assertEquals(comp, 1); } @Test public void checkCompareToDirect() { byte[] arr1 = new byte[] {0, 1, 2, 3}; byte[] arr2 = new byte[] {0, 1, 2, 4}; byte[] arr3 = new byte[] {0, 1, 2, 3, 4}; try (WritableMemory mem1 = WritableMemory.allocateDirect(4); WritableMemory mem2 = WritableMemory.allocateDirect(4); WritableMemory mem3 = WritableMemory.allocateDirect(5)) { mem1.putByteArray(0, arr1, 0, 4); mem2.putByteArray(0, arr2, 0, 4); mem3.putByteArray(0, arr3, 0, 5); Buffer buf1 = mem1.asBuffer(); Buffer buf2 = mem2.asBuffer(); Buffer buf3 = mem3.asBuffer(); int comp = buf1.compareTo(0, 3, buf2, 0, 3); assertEquals(comp, 0); comp = buf1.compareTo(0, 4, buf2, 0, 4); assertEquals(comp, -1); comp = buf2.compareTo(0, 4, buf1, 0, 4); assertEquals(comp, 1); //different lengths comp = buf1.compareTo(0, 4, buf3, 0, 5); assertEquals(comp, -1); comp = buf3.compareTo(0, 5, buf1, 0, 4); assertEquals(comp, 1); } } @Test public void checkAsBuffer() { WritableMemory wmem = WritableMemory.allocate(64); WritableBuffer wbuf = wmem.asWritableBuffer(); wbuf.setPosition(32); for (int i = 32; i < 64; i++) { wbuf.putByte((byte)i); } //println(wbuf.toHexString("Buf", 0, (int)wbuf.getCapacity())); Buffer buf = wmem.asBuffer(); buf.setPosition(32); for (int i = 32; i < 64; i++) { assertEquals(buf.getByte(), i); } } @Test public void checkDuplicate() { WritableMemory wmem = WritableMemory.allocate(64); for (int i = 0; i < 64; i++) { wmem.putByte(i, (byte)i); } WritableBuffer wbuf = wmem.asWritableBuffer().writableDuplicate(); ((ResourceImpl)wbuf).checkValidAndBounds(0, 64); for (int i = 0; i < 64; i++) { assertEquals(wbuf.getByte(), i); } Buffer buf = wmem.asBuffer().duplicate(); for (int i = 0; i < 64; i++) { assertEquals(buf.getByte(), i); } WritableMemory wmem2 = wbuf.asWritableMemory(); for (int i = 0; i < 64; i++) { assertEquals(wmem2.getByte(i), i); } WritableMemory wmem3 = wbuf.asWritableMemory(); ((ResourceImpl)wmem3).checkValidAndBounds(0, 64); } @Test public void checkCumAndRegionOffset() { WritableMemory wmem = WritableMemory.allocate(64); WritableMemory reg = wmem.writableRegion(32, 32); WritableBuffer buf = reg.asWritableBuffer(); assertEquals(buf.getTotalOffset(), 32); assertEquals(((ResourceImpl)buf).getCumulativeOffset(0), 32 + 16); } @Test public void checkIsSameResource() { byte[] byteArr = new byte[64]; WritableBuffer wbuf1 = WritableMemory.writableWrap(byteArr).asWritableBuffer(); WritableBuffer wbuf2 = WritableMemory.writableWrap(byteArr).asWritableBuffer(); assertTrue(wbuf1.isSameResource(wbuf2)); } @Test public void checkDegenerateRegionReturn() { Memory mem = Memory.wrap(new byte[0]); Buffer buf = mem.asBuffer(); Buffer reg = buf.region(); assertEquals(reg.getCapacity(), 0); } @Test public void checkAsWritableMemoryRO() { ByteBuffer bb = ByteBuffer.allocate(64); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); WritableMemory wmem = wbuf.asWritableMemory(); //OK assertNotNull(wmem); try { Buffer buf = Buffer.wrap(bb.asReadOnlyBuffer()); wbuf = (WritableBuffer) buf; wmem = wbuf.asWritableMemory(); fail("Should have thrown exception"); } catch (ReadOnlyException expected) { // expected } } @Test public void checkWritableDuplicateRO() { ByteBuffer bb = ByteBuffer.allocate(64); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); @SuppressWarnings("unused") WritableBuffer wdup = wbuf.writableDuplicate(); try { Buffer buf = Buffer.wrap(bb); wbuf = (WritableBuffer) buf; @SuppressWarnings("unused") WritableBuffer wdup2 = wbuf.writableDuplicate(); fail("Should have thrown exception"); } catch (ReadOnlyException expected) { // ignore } } @Test public void checkWritableRegionRO() { ByteBuffer bb = ByteBuffer.allocate(64); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); @SuppressWarnings("unused") WritableBuffer wreg = wbuf.writableRegion(); try { Buffer buf = Buffer.wrap(bb); wbuf = (WritableBuffer) buf; @SuppressWarnings("unused") WritableBuffer wreg2 = wbuf.writableRegion(); fail("Should have thrown exception"); } catch (ReadOnlyException expected) { // ignore } } @Test public void checkWritableRegionWithParamsRO() { ByteBuffer bb = ByteBuffer.allocate(64); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); @SuppressWarnings("unused") WritableBuffer wreg = wbuf.writableRegion(0, 1, wbuf.getByteOrder()); try { Buffer buf = Buffer.wrap(bb); wbuf = (WritableBuffer) buf; @SuppressWarnings("unused") WritableBuffer wreg2 = wbuf.writableRegion(0, 1, wbuf.getByteOrder()); fail("Should have thrown exception"); } catch (ReadOnlyException expected) { // ignore } } @Test public void checkZeroBuffer() { WritableMemory wmem = WritableMemory.allocate(8); WritableBuffer wbuf = wmem.asWritableBuffer(); WritableBuffer reg = wbuf.writableRegion(0, 0, wbuf.getByteOrder()); assertEquals(reg.getCapacity(), 0); } @Test public void checkDuplicateNonNative() { WritableMemory wmem = WritableMemory.allocate(64); wmem.putShort(0, (short) 1); Buffer buf = wmem.asWritableBuffer().duplicate(Util.NON_NATIVE_BYTE_ORDER); assertEquals(buf.getShort(0), 256); } @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
2,288
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/BufferReadWriteSafetyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import java.nio.ByteBuffer; import org.apache.datasketches.memory.Buffer; import org.apache.datasketches.memory.ReadOnlyException; import org.apache.datasketches.memory.WritableBuffer; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; public class BufferReadWriteSafetyTest { // Test various operations with read-only Buffer private final WritableBuffer buf = (WritableBuffer) Buffer.wrap(ByteBuffer.allocate(8)); @Test(expectedExceptions = ReadOnlyException.class) public void testPutByte() { buf.putByte(0, (byte) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBytePositional() { buf.putByte((byte) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBoolean() { buf.putBoolean(0, true); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBooleanPositional() { buf.putBoolean(true); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutShort() { buf.putShort(0, (short) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutShortPositional() { buf.putShort((short) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutChar() { buf.putChar(0, (char) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutCharPositional() { buf.putChar((char) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutInt() { buf.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutIntPositional() { buf.putInt(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutLong() { buf.putLong(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutLongPositional() { buf.putLong(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutFloat() { buf.putFloat(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutFloatPositional() { buf.putFloat(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutDouble() { buf.putDouble(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutDoublePositional() { buf.putDouble(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutByteArray() { buf.putByteArray(new byte[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBooleanArray() { buf.putBooleanArray(new boolean[] {true}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutShortArray() { buf.putShortArray(new short[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutCharArray() { buf.putCharArray(new char[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutIntArray() { buf.putIntArray(new int[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutLongArray() { buf.putLongArray(new long[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutFloatArray() { buf.putFloatArray(new float[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testDoubleByteArray() { buf.putDoubleArray(new double[] {1}, 0, 1); } // Now, test that various ways to obtain a read-only buffer produce a read-only buffer indeed @Test(expectedExceptions = ReadOnlyException.class) public void testWritableMemoryAsBuffer() { WritableBuffer buf1 = (WritableBuffer) WritableMemory.allocate(8).asBuffer(); buf1.putInt(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testWritableBufferRegion() { WritableBuffer buf1 = (WritableBuffer) WritableMemory.allocate(8).asWritableBuffer().region(); buf1.putInt(1); } @Test(expectedExceptions = ReadOnlyException.class) public void testWritableBufferDuplicate() { WritableBuffer buf1 = (WritableBuffer) WritableMemory.allocate(8).asWritableBuffer().duplicate(); buf1.putInt(1); } }
2,289
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/AllocateDirectMapMemoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Note: Lincoln's Gettysburg Address is in the public domain. See LICENSE. */ package org.apache.datasketches.memory.internal; import static org.apache.datasketches.memory.internal.Util.getResourceFile; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.File; import java.nio.ByteOrder; import org.apache.datasketches.memory.Memory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class AllocateDirectMapMemoryTest { private static final String LS = System.getProperty("line.separator"); @BeforeClass public void setReadOnly() { UtilTest.setGettysburgAddressFileToReadOnly(); } @Test(expectedExceptions = IllegalStateException.class) public void simpleMap() { File file = getResourceFile("GettysburgAddress.txt"); assertTrue(AllocateDirectWritableMap.isFileReadOnly(file)); try (Memory mem = Memory.map(file)) { mem.close(); //explicit close } //The Try-With-Resources will throw if already closed } @Test public void printGettysbergAddress() { File file = getResourceFile("GettysburgAddress.txt"); try (Memory mem = Memory.map(file)) { println("Mem Cap: " + mem.getCapacity()); println("Total Offset: " + mem.getTotalOffset()); println("Cum Offset: " + ((ResourceImpl)mem).getCumulativeOffset(0)); println("Total Offset: " + mem.getTotalOffset()); StringBuilder sb = new StringBuilder(); mem.getCharsFromUtf8(43, 176, sb); println(sb.toString()); println(""); Memory mem2 = mem.region(43 + 76, 20); println("Mem Cap: " + mem2.getCapacity()); println("Offset: " + mem.getTotalOffset()); println("Cum Offset: " + ((ResourceImpl)mem2).getCumulativeOffset(0)); println("Total Offset: " + mem2.getTotalOffset()); StringBuilder sb2 = new StringBuilder(); mem2.getCharsFromUtf8(0, 12, sb2); println(sb2.toString()); } } @Test public void testIllegalArguments() { File file = getResourceFile("GettysburgAddress.txt"); try (Memory mem = Memory.map(file, -1, Integer.MAX_VALUE, ByteOrder.nativeOrder())) { fail("Failed: Position was negative."); } catch (IllegalArgumentException e) { //ok } try (Memory mem = Memory.map(file, 0, -1, ByteOrder.nativeOrder())) { fail("Failed: Size was negative."); } catch (IllegalArgumentException e) { //ok } } @Test(expectedExceptions = IllegalStateException.class) public void testAccessAfterClose() { File file = getResourceFile("GettysburgAddress.txt"); long memCapacity = file.length(); try (Memory mem = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) { assertEquals(memCapacity, mem.getCapacity()); } //normal close via TWR Memory mem = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder()); mem.close(); //normal manual close mem.getCapacity(); //isLoaded(); //already closed, invalid } @Test(expectedExceptions = IllegalStateException.class) public void testReadFailAfterClose() { File file = getResourceFile("GettysburgAddress.txt"); long memCapacity = file.length(); Memory mem = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder()); mem.close(); mem.isLoaded(); } @Test public void testLoad() { File file = getResourceFile("GettysburgAddress.txt"); long memCapacity = file.length(); try (Memory mem = Memory.map(file, 0, memCapacity, ByteOrder.nativeOrder())) { mem.load(); assertTrue(mem.isLoaded()); } //normal TWR close } @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } static void println(final Object o) { if (o == null) { print(LS); } else { print(o.toString() + LS); } } /** * @param o value to print */ static void print(final Object o) { if (o != null) { //System.out.print(o.toString()); //disable here } } }
2,290
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/AllocateDirectMemoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.apache.datasketches.memory.DefaultMemoryRequestServer; import org.apache.datasketches.memory.MemoryRequestServer; import org.apache.datasketches.memory.Resource; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; public class AllocateDirectMemoryTest { @Test(expectedExceptions = IllegalStateException.class) public void simpleAllocateDirect() { int longs = 32; try (WritableMemory wMem = WritableMemory.allocateDirect(longs << 3)) { for (int i = 0; i < longs; i++) { wMem.putLong(i << 3, i); assertEquals(wMem.getLong(i << 3), i); } //inside the TWR block the memory should be valid ((ResourceImpl)wMem).checkValid(); wMem.close(); //explicit close } //normal TWR close will not throw if already closed } @Test public void checkDefaultMemoryRequestServer() { int longs1 = 32; int bytes1 = longs1 << 3; try (WritableMemory origWmem = WritableMemory.allocateDirect(bytes1)) { for (int i = 0; i < longs1; i++) { //puts data in wMem1 origWmem.putLong(i << 3, i); assertEquals(origWmem.getLong(i << 3), i); } println(origWmem.toHexString("Test", 0, 32 * 8)); int longs2 = 64; int bytes2 = longs2 << 3; MemoryRequestServer memReqSvr; if (Resource.defaultMemReqSvr == null) { memReqSvr = new DefaultMemoryRequestServer(); } else { memReqSvr = origWmem.getMemoryRequestServer(); } WritableMemory newWmem = memReqSvr.request(origWmem, bytes2); assertFalse(newWmem.isDirectResource()); //on heap by default for (int i = 0; i < longs2; i++) { newWmem.putLong(i << 3, i); assertEquals(newWmem.getLong(i << 3), i); } memReqSvr.requestClose(origWmem, newWmem); //The default MRS doesn't actually release because it could be easily misused. // So we let the TWR release it. } } @Test public void checkNonNativeDirect() { try (WritableMemory wmem = WritableMemory.allocateDirect(128, Util.NON_NATIVE_BYTE_ORDER, null)) { wmem.putChar(0, (char) 1); assertEquals(wmem.getByte(1), (byte) 1); } } @Test public void checkExplicitClose() { final long cap = 128; WritableMemory wMem = WritableMemory.allocateDirect(cap); assertTrue(wMem.isValid()); wMem.close(); assertFalse(wMem.isValid()); } @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
2,291
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/IsValidUtf8TestUtil.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; /** * Stripped down version of * https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/test/java/com/google/protobuf/IsValidUtf8TestUtil.java * * <p>Copyright 2008 Google Inc. All rights reserved. * https://developers.google.com/protocol-buffers/ * See LICENSE. */ public class IsValidUtf8TestUtil { // 128 - [chars 0x0000 to 0x007f] static final long ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS = (0x007f - 0x0000) + 1; // 128 static final long EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT = ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 1920 [chars 0x0080 to 0x07FF] static final long TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS = (0x07FF - 0x0080) + 1; // 18,304 static final long EXPECTED_TWO_BYTE_ROUNDTRIPPABLE_COUNT = // Both bytes are one byte characters (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 2) // The possible number of two byte characters + TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS; // 2048 static final long THREE_BYTE_SURROGATES = 2 * 1024; // 61,440 [chars 0x0800 to 0xFFFF, minus surrogates] static final long THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS = ((0xFFFF - 0x0800) + 1) - THREE_BYTE_SURROGATES; // 2,650,112 static final long EXPECTED_THREE_BYTE_ROUNDTRIPPABLE_COUNT = // All one byte characters (long) Math.pow(EXPECTED_ONE_BYTE_ROUNDTRIPPABLE_COUNT, 3) // One two byte character and a one byte character + (2 * TWO_BYTE_ROUNDTRIPPABLE_CHARACTERS * ONE_BYTE_ROUNDTRIPPABLE_CHARACTERS) // Three byte characters + THREE_BYTE_ROUNDTRIPPABLE_CHARACTERS; }
2,292
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/IgnoredArrayOverflowTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class IgnoredArrayOverflowTest { private WritableMemory memory; private static final long MAX_SIZE = (1L << 10); // use 1L << 31 to test int over range @BeforeClass public void allocate() { memory = WritableMemory.allocateDirect(MAX_SIZE); } @AfterClass public void close() { memory.close(); } @Test public void testCharArray() { int size = (int) (memory.getCapacity() / 2); char[] array = new char[size]; memory.getCharArray(0, array, 0, size); memory.asBuffer().getCharArray(array, 0, size); memory.putCharArray(0, array, 0, size); memory.asWritableBuffer().putCharArray(array, 0, size); } @Test public void testShortArray() { int size = (int) (memory.getCapacity() / 2); short[] array = new short[size]; memory.getShortArray(0, array, 0, size); memory.asBuffer().getShortArray(array, 0, size); memory.putShortArray(0, array, 0, size); memory.asWritableBuffer().putShortArray(array, 0, size); } @Test public void testIntArray() { int size = (int) (memory.getCapacity() / 4); int[] array = new int[size]; memory.getIntArray(0, array, 0, size); memory.asBuffer().getIntArray(array, 0, size); memory.putIntArray(0, array, 0, size); memory.asWritableBuffer().putIntArray(array, 0, size); } @Test public void testFloatArray() { int size = (int) (memory.getCapacity() / 4); float[] array = new float[size]; memory.getFloatArray(0, array, 0, size); memory.asBuffer().getFloatArray(array, 0, size); memory.putFloatArray(0, array, 0, size); memory.asWritableBuffer().putFloatArray(array, 0, size); } @Test public void testLongArray() { int size = (int) (memory.getCapacity() / 8); long[] array = new long[size]; memory.getLongArray(0, array, 0, size); memory.asBuffer().getLongArray(array, 0, size); memory.putLongArray(0, array, 0, size); memory.asWritableBuffer().putLongArray(array, 0, size); } @Test public void testDoubleArray() { int size = (int) (memory.getCapacity() / 8); double[] array = new double[size]; memory.getDoubleArray(0, array, 0, size); memory.asBuffer().getDoubleArray(array, 0, size); memory.putDoubleArray(0, array, 0, size); memory.asWritableBuffer().putDoubleArray(array, 0, size); } }
2,293
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/MemoryCleanerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.concurrent.atomic.AtomicBoolean; import org.testng.annotations.Test; public class MemoryCleanerTest { @Test public void cleanerDeallocates() { SimpleDeallocator deallocator = new SimpleDeallocator(); MemoryCleaner cleaner = new MemoryCleaner(this, deallocator); cleaner.clean(); assertTrue(SimpleDeallocator.getHasRun()); } @Test public void noDeallocation() { SimpleDeallocator deallocator = new SimpleDeallocator(); new MemoryCleaner(this, deallocator); assertFalse(SimpleDeallocator.getHasRun()); } static final class SimpleDeallocator implements Runnable { static final AtomicBoolean hasRun = new AtomicBoolean(); SimpleDeallocator() { hasRun.set(false); } @Override public void run() { hasRun.compareAndSet(false, true); } public static Boolean getHasRun() { return hasRun.get(); } } }
2,294
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/SpecificLeafTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.apache.datasketches.memory.Buffer; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; /** * @author Lee Rhodes */ public class SpecificLeafTest { @Test public void checkByteBufferLeaves() { int bytes = 128; ByteBuffer bb = ByteBuffer.allocate(bytes); bb.order(ByteOrder.nativeOrder()); Memory mem = Memory.wrap(bb).region(0, bytes, ByteOrder.nativeOrder()); ResourceImpl bsi = (ResourceImpl)mem; int typeId = bsi.getTypeId(); assertTrue(bsi.isByteBufferResource()); assertTrue(bsi.isNativeOrder(typeId)); assertTrue(mem.isReadOnly()); checkCrossLeafTypeIds(mem); Buffer buf = mem.asBuffer().region(0, bytes, ByteOrder.nativeOrder()); bb.order(Util.NON_NATIVE_BYTE_ORDER); Memory mem2 = Memory.wrap(bb).region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf2 = mem2.asBuffer().region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf3 = buf2.duplicate(); assertTrue(((ResourceImpl)mem).isRegionView()); assertTrue(((ResourceImpl)mem2).isRegionView()); assertTrue(((ResourceImpl)buf).isRegionView()); assertTrue(((ResourceImpl)buf2).isRegionView()); assertTrue(((ResourceImpl)buf3).isDuplicateBufferView()); } @Test public void checkDirectLeaves() { int bytes = 128; try (WritableMemory wmem = WritableMemory.allocateDirect(bytes)) { assertTrue(((ResourceImpl)wmem).isDirectResource()); assertFalse(wmem.isReadOnly()); checkCrossLeafTypeIds(wmem); WritableMemory nnwmem = wmem.writableRegion(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Memory mem = wmem.region(0, bytes, ByteOrder.nativeOrder()); Buffer buf = mem.asBuffer().region(0, bytes, ByteOrder.nativeOrder()); Memory mem2 = nnwmem.region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf2 = mem2.asBuffer().region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf3 = buf2.duplicate(); assertTrue(((ResourceImpl)mem).isRegionView()); assertTrue(((ResourceImpl)mem2).isRegionView()); assertTrue(((ResourceImpl)buf).isRegionView()); assertTrue(((ResourceImpl)buf2).isRegionView()); assertTrue(((ResourceImpl)buf3).isDuplicateBufferView()); } } @Test public void checkHeapLeaves() { int bytes = 128; Memory mem = Memory.wrap(new byte[bytes]); ResourceImpl bsi = (ResourceImpl)mem; assertTrue(bsi.isHeapResource()); assertTrue(bsi.isReadOnly()); checkCrossLeafTypeIds(mem); Memory nnreg = mem.region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Memory reg = mem.region(0, bytes, ByteOrder.nativeOrder()); Buffer buf = reg.asBuffer().region(0, bytes, ByteOrder.nativeOrder()); Buffer buf4 = buf.duplicate(); Memory reg2 = nnreg.region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf2 = reg2.asBuffer().region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf3 = buf2.duplicate(); assertFalse(((ResourceImpl)mem).isRegionView()); assertTrue(((ResourceImpl)reg2).isRegionView()); assertTrue(((ResourceImpl)buf).isRegionView()); assertTrue(((ResourceImpl)buf2).isRegionView()); assertTrue(((ResourceImpl)buf3).isDuplicateBufferView()); assertTrue(((ResourceImpl)buf4).isDuplicateBufferView()); } @Test public void checkMapLeaves() throws IOException { File file = new File("TestFile2.bin"); if (file.exists()) { try { java.nio.file.Files.delete(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } } assertTrue(file.createNewFile()); assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false assertTrue(file.isFile()); file.deleteOnExit(); //comment out if you want to examine the file. final long bytes = 128; try (WritableMemory mem = WritableMemory.writableMap(file, 0L, bytes, ByteOrder.nativeOrder())) { assertTrue(((ResourceImpl)mem).isMemoryMappedResource()); assertFalse(mem.isReadOnly()); checkCrossLeafTypeIds(mem); Memory nnreg = mem.region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Memory reg = mem.region(0, bytes, ByteOrder.nativeOrder()); Buffer buf = reg.asBuffer().region(0, bytes, ByteOrder.nativeOrder()); Buffer buf4 = buf.duplicate(); Memory reg2 = nnreg.region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf2 = reg2.asBuffer().region(0, bytes, Util.NON_NATIVE_BYTE_ORDER); Buffer buf3 = buf2.duplicate(); assertTrue(((ResourceImpl)reg).isRegionView()); assertTrue(((ResourceImpl)reg2).isRegionView()); assertTrue(((ResourceImpl)buf).isRegionView()); assertTrue(((ResourceImpl)buf2).isRegionView()); assertTrue(((ResourceImpl)buf3).isDuplicateBufferView()); assertTrue(((ResourceImpl)buf4).isDuplicateBufferView()); } } private static void checkCrossLeafTypeIds(Memory mem) { Memory reg1 = mem.region(0, mem.getCapacity()); assertTrue(((ResourceImpl)reg1).isRegionView()); Buffer buf1 = reg1.asBuffer(); assertTrue(((ResourceImpl)buf1).isRegionView()); assertTrue(((ResourceImpl)buf1).isBufferApi(((ResourceImpl)buf1).getTypeId())); assertTrue(buf1.isReadOnly()); Buffer buf2 = buf1.duplicate(); assertTrue(((ResourceImpl)buf2).isRegionView()); assertTrue(((ResourceImpl)buf2).isBufferApi(((ResourceImpl)buf2).getTypeId())); assertTrue(((ResourceImpl)buf2).isDuplicateBufferView()); assertTrue(buf2.isReadOnly()); Memory mem2 = buf1.asMemory(); // assertTrue(((ResourceImpl)mem2).isRegionView()); assertFalse(((ResourceImpl)mem2).isBufferApi(((ResourceImpl)mem2).getTypeId())); assertFalse(((ResourceImpl)mem2).isDuplicateBufferView()); assertTrue(mem2.isReadOnly()); Buffer buf3 = buf1.duplicate(Util.NON_NATIVE_BYTE_ORDER); assertTrue(((ResourceImpl)buf3).isRegionView()); assertTrue(((ResourceImpl)buf3).isBufferApi(((ResourceImpl)buf3).getTypeId())); assertTrue(((ResourceImpl)buf3).isDuplicateBufferView()); assertTrue(((ResourceImpl)buf3).isNonNativeOrder()); assertTrue(buf3.isReadOnly()); Memory mem3 = buf3.asMemory(); assertTrue(((ResourceImpl)mem3).isRegionView()); assertFalse(((ResourceImpl)mem3).isBufferApi(((ResourceImpl)mem3).getTypeId())); assertTrue(((ResourceImpl)mem3).isDuplicateBufferView()); assertTrue(((ResourceImpl)mem3).isNonNativeOrder()); assertTrue(mem3.isReadOnly()); } }
2,295
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/ResourceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.apache.datasketches.memory.internal.UnsafeUtil.ARRAY_DOUBLE_INDEX_SCALE; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.nio.ByteOrder; import org.apache.datasketches.memory.Buffer; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableBuffer; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; public class ResourceTest { @Test public void checkPrimOffset() { int off = (int)Prim.BYTE.off(); assertTrue(off > 0); } @Test public void checkIsSameResource() { WritableMemory wmem = WritableMemory.allocate(16); Memory mem = wmem; assertFalse(wmem.isSameResource(null)); assertTrue(wmem.isSameResource(mem)); WritableBuffer wbuf = wmem.asWritableBuffer(); Buffer buf = wbuf; assertFalse(wbuf.isSameResource(null)); assertTrue(wbuf.isSameResource(buf)); } @Test public void checkNotEqualTo() { byte[] arr1 = {1,2,3,4,5,6,7,8}; Memory mem1 = Memory.wrap(arr1); byte[] arr2 = {1,2,3,4,5,6,7,9}; Memory mem2 = Memory.wrap(arr2); assertFalse(mem1.equalTo(mem2)); } //StepBoolean checks @Test public void checkStepBoolean() { checkStepBoolean(true); checkStepBoolean(false); } private static void checkStepBoolean(boolean initialState) { StepBoolean step = new StepBoolean(initialState); assertTrue(step.get() == initialState); //confirm initialState step.change(); assertTrue(step.hasChanged()); //1st change was successful assertTrue(step.get() != initialState); //confirm it is different from initialState step.change(); assertTrue(step.get() != initialState); //Still different from initialState assertTrue(step.hasChanged()); //confirm it was changed from initialState value } @Test public void checkPrim() { assertEquals(Prim.DOUBLE.scale(), ARRAY_DOUBLE_INDEX_SCALE); } @Test public void checkIsByteOrderCompatible() { WritableMemory wmem = WritableMemory.allocate(8); assertTrue(wmem.isByteOrderCompatible(ByteOrder.nativeOrder())); } @Test(expectedExceptions = IllegalArgumentException.class) public void checkByteOrderNull() { Util.isNativeByteOrder(null); fail(); } @Test public void checkIsNativeByteOrder() { assertTrue(Util.isNativeByteOrder(ByteOrder.nativeOrder())); try { Util.isNativeByteOrder(null); fail(); } catch (final IllegalArgumentException e) { } } @Test public void checkXxHash64() { WritableMemory mem = WritableMemory.allocate(8); long out = mem.xxHash64(mem.getLong(0), 1L); assertTrue(out != 0); } @Test public void checkTypeDecode() { for (int i = 0; i < 128; i++) { ResourceImpl.typeDecode(i); } } /********************/ @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } /** * @param s value to print */ static void println(String s) { //System.out.println(s); //disable here } }
2,296
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/MemoryReadWriteSafetyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.ReadOnlyException; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; public class MemoryReadWriteSafetyTest { // Test various operations with read-only Memory final WritableMemory mem = (WritableMemory) Memory.wrap(new byte[8]); @Test(expectedExceptions = ReadOnlyException.class) public void testPutByte() { mem.putByte(0, (byte) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBoolean() { mem.putBoolean(0, true); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutShort() { mem.putShort(0, (short) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutChar() { mem.putChar(0, (char) 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutInt() { mem.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutLong() { mem.putLong(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutFloat() { mem.putFloat(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutDouble() { mem.putDouble(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutByteArray() { mem.putByteArray(0, new byte[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutBooleanArray() { mem.putBooleanArray(0, new boolean[] {true}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutShortArray() { mem.putShortArray(0, new short[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutCharArray() { mem.putCharArray(0, new char[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutIntArray() { mem.putIntArray(0, new int[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutLongArray() { mem.putLongArray(0, new long[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testPutFloatArray() { mem.putFloatArray(0, new float[] {1}, 0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testDoubleByteArray() { mem.putDoubleArray(0, new double[] {1}, 0, 1); } // Now, test that various ways to obtain a read-only memory produce a read-only memory indeed @Test(expectedExceptions = ReadOnlyException.class) public void testWritableMemoryRegion() { WritableMemory mem1 = (WritableMemory) WritableMemory.allocate(8).region(0, 8); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testByteArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new byte[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testByteArrayWrapWithBO() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new byte[8], ByteOrder.nativeOrder()); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testByteArrayWrapWithOffsetsAndBO() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new byte[8], 0, 4, ByteOrder.nativeOrder()); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testBooleanArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new boolean[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testShortArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new short[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testCharArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new char[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testIntArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new int[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testLongArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new long[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testFloatArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new float[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testDoubleArrayWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(new double[8]); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testByteBufferWrap() { WritableMemory mem1 = (WritableMemory) Memory.wrap(ByteBuffer.allocate(8)); mem1.putInt(0, 1); } @Test(expectedExceptions = ReadOnlyException.class) public void testMapFile() throws Exception { File tempFile; try { tempFile = File.createTempFile("test", ".tmp", null); Files.write(tempFile.toPath(), "ipsum".getBytes(), StandardOpenOption.APPEND); //tempFile.setReadOnly(); } catch (IllegalArgumentException | IOException | SecurityException e) { throw new RuntimeException(e); } try (Memory mem = Memory.map(tempFile)) { //Memory is RO ((WritableMemory) mem).putInt(0, 1); } tempFile.delete(); } @Test(expectedExceptions = ReadOnlyException.class) public void testWritableMapWithROFile() { File tempFile; try { tempFile = File.createTempFile("test", ".tmp", null); Files.write(tempFile.toPath(), "ipsum".getBytes(), StandardOpenOption.APPEND); tempFile.setReadOnly(); } catch (IllegalArgumentException | IOException | SecurityException e) { throw new RuntimeException(e); } try (WritableMemory mem = WritableMemory.writableMap(tempFile)) { //File is RO mem.putInt(0, 1); } tempFile.delete(); } @Test(expectedExceptions = ReadOnlyException.class) public void testMapFileWithOffsetsAndBO() { File tempFile; try { tempFile = File.createTempFile("test", ".tmp", null); Files.write(tempFile.toPath(), "ipsum".getBytes(), StandardOpenOption.APPEND); //tempFile.setReadOnly(); } catch (IllegalArgumentException | IOException | SecurityException e) { throw new RuntimeException(e); } try (Memory mem = Memory.map(tempFile, 0, 4, ByteOrder.nativeOrder())) { //Memory is RO ((WritableMemory) mem).putInt(0, 1); } tempFile.delete(); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMapFileBeyondTheFileSize() { File tempFile; try { tempFile = File.createTempFile("test", ".tmp", null); Files.write(tempFile.toPath(), "ipsum".getBytes(), StandardOpenOption.APPEND); //tempFile.setReadOnly(); } catch (IllegalArgumentException | IOException | SecurityException e) { throw new RuntimeException(e); } try (Memory mem = Memory.map(tempFile, 0, 16, ByteOrder.nativeOrder())) { //Read-only mode and requested map length is greater than current file length: // Requested Length = 16, Current File Length = 5 } tempFile.delete(); } }
2,297
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/BufferTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.datasketches.memory.internal; import static org.testng.Assert.assertEquals; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.List; import org.apache.datasketches.memory.Buffer; import org.apache.datasketches.memory.BufferPositionInvariantsException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableBuffer; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.Test; import org.testng.collections.Lists; public class BufferTest { @Test public void checkDirectRoundTrip() throws Exception { int n = 1024; //longs try (WritableMemory wmem = WritableMemory.allocateDirect(n * 8)) { WritableBuffer wbuf = wmem.asWritableBuffer(); for (int i = 0; i < n; i++) { wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { long v = wbuf.getLong(); assertEquals(v, i); } } } @Test public void checkAutoHeapRoundTrip() { int n = 1024; //longs WritableBuffer wbuf = WritableMemory.allocate(n * 8).asWritableBuffer(); for (int i = 0; i < n; i++) { wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { long v = wbuf.getLong(); assertEquals(v, i); } } @Test public void checkArrayWrap() { int n = 1024; //longs byte[] arr = new byte[n * 8]; WritableBuffer wbuf = WritableMemory.writableWrap(arr).asWritableBuffer(); for (int i = 0; i < n; i++) { wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { long v = wbuf.getLong(); assertEquals(v, i); } Buffer buf = Memory.wrap(arr).asBuffer(); buf.resetPosition(); for (int i = 0; i < n; i++) { long v = buf.getLong(); assertEquals(v, i); } // Check Zero length array wraps Memory mem = Memory.wrap(new byte[0]); Buffer buffZeroLengthArrayWrap = mem.asBuffer(); assertEquals(buffZeroLengthArrayWrap.getCapacity(), 0); // check 0 length array wraps List<Buffer> buffersToCheck = Lists.newArrayList(); buffersToCheck.add(WritableMemory.allocate(0).asBuffer()); buffersToCheck.add(WritableBuffer.writableWrap(ByteBuffer.allocate(0))); buffersToCheck.add(Buffer.wrap(ByteBuffer.allocate(0))); buffersToCheck.add(Memory.wrap(new boolean[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new byte[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new char[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new short[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new int[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new long[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new float[0]).asBuffer()); buffersToCheck.add(Memory.wrap(new double[0]).asBuffer()); //Check the buffer lengths for (Buffer buffer : buffersToCheck) { assertEquals(buffer.getCapacity(), 0); } } @Test public void simpleBBTest() { int n = 1024; //longs byte[] arr = new byte[n * 8]; ByteBuffer bb = ByteBuffer.wrap(arr); bb.order(ByteOrder.nativeOrder()); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); for (int i = 0; i < n; i++) { //write to wbuf wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { //read from wbuf long v = wbuf.getLong(); assertEquals(v, i); } for (int i = 0; i < n; i++) { //read from BB long v = bb.getLong(); assertEquals(v, i); } } @Test public void checkByteBufHeap() { int n = 1024; //longs byte[] arr = new byte[n * 8]; ByteBuffer bb = ByteBuffer.wrap(arr); bb.order(ByteOrder.nativeOrder()); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); for (int i = 0; i < n; i++) { //write to wbuf wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { //read from wbuf long v = wbuf.getLong(); assertEquals(v, i); } for (int i = 0; i < n; i++) { //read from BB long v = bb.getLong(i * 8); assertEquals(v, i); } Buffer buf1 = Memory.wrap(arr).asBuffer(); for (int i = 0; i < n; i++) { //read from wrapped arr long v = buf1.getLong(); assertEquals(v, i); } //convert to wbuf to RO Buffer buf = wbuf; buf.resetPosition(); for (int i = 0; i < n; i++) { long v = buf.getLong(); assertEquals(v, i); } } @Test public void checkByteBufDirect() { int n = 1024; //longs ByteBuffer bb = ByteBuffer.allocateDirect(n * 8); bb.order(ByteOrder.nativeOrder()); WritableBuffer wbuf = WritableBuffer.writableWrap(bb); for (int i = 0; i < n; i++) { //write to wmem wbuf.putLong(i); } wbuf.resetPosition(); for (int i = 0; i < n; i++) { //read from wmem long v = wbuf.getLong(); assertEquals(v, i); } for (int i = 0; i < n; i++) { //read from BB long v = bb.getLong(i * 8); assertEquals(v, i); } Buffer buf1 = Buffer.wrap(bb); for (int i = 0; i < n; i++) { //read from wrapped bb RO long v = buf1.getLong(); assertEquals(v, i); } //convert to RO Buffer buf = wbuf; buf.resetPosition(); for (int i = 0; i < n; i++) { long v = buf.getLong(); assertEquals(v, i); } } @Test public void checkByteBufBigEndianOrder() { int n = 1024; //longs ByteBuffer bb = ByteBuffer.allocate(n * 8); bb.order(ByteOrder.BIG_ENDIAN); Buffer buf = Buffer.wrap(bb); assertEquals(buf.getByteOrder(), ByteOrder.BIG_ENDIAN); } @Test public void checkReadOnlyHeapByteBuffer() { ByteBuffer bb = ByteBuffer.allocate(128); bb.order(ByteOrder.nativeOrder()); for (int i = 0; i < 128; i++) { bb.put(i, (byte)i); } bb.position(64); ByteBuffer slice = bb.slice().asReadOnlyBuffer(); slice.order(ByteOrder.nativeOrder()); Buffer buf = Buffer.wrap(slice); for (int i = 0; i < 64; i++) { assertEquals(buf.getByte(), 64 + i); } buf.toHexString("slice", 0, slice.capacity()); //println(s); } @Test public void checkPutGetArraysHeap() { int n = 1024; //longs long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = i; } WritableBuffer wbuf = WritableMemory.allocate(n * 8).asWritableBuffer(); wbuf.putLongArray(arr, 0, n); long[] arr2 = new long[n]; wbuf.resetPosition(); wbuf.getLongArray(arr2, 0, n); for (int i = 0; i < n; i++) { assertEquals(arr2[i], i); } } @Test public void checkRORegions() { int n = 16; int n2 = n / 2; long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = i; } Buffer buf = Memory.wrap(arr).asBuffer(); buf.setPosition(n2 * 8); Buffer reg = buf.region(); for (int i = 0; i < n2; i++) { long v = reg.getLong(); assertEquals(v, i + n2); //println("" + v); } } @Test public void checkWRegions() { int n = 16; int n2 = n / 2; long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = i; } //0...n-1 WritableMemory mem = WritableMemory.writableWrap(arr); WritableBuffer wbuf = mem.asWritableBuffer(); for (int i = 0; i < n; i++) { assertEquals(wbuf.getLong(), i); //0...n-1 println("" + wbuf.getLong(i * 8)); } println(""); wbuf.setPosition(n2 * 8); WritableBuffer reg = wbuf.writableRegion(); for (int i = 0; i < n2; i++) { reg.putLong(i); } //rewrite top half wbuf.resetPosition(); for (int i = 0; i < n; i++) { println("" + wbuf.getLong(i * 8)); assertEquals(wbuf.getLong(), i % 8); } } @Test(expectedExceptions = IllegalStateException.class) public void checkParentUseAfterFree() throws Exception { int bytes = 64 * 8; WritableMemory wmem = WritableMemory.allocateDirect(bytes); WritableBuffer wbuf = wmem.asWritableBuffer(); wmem.close(); wbuf.getLong(); } @Test(expectedExceptions = IllegalStateException.class) public void checkRegionUseAfterFree() throws Exception { int bytes = 64; WritableMemory wmem = WritableMemory.allocateDirect(bytes); Buffer reg = wmem.asBuffer().region(); wmem.close(); //with -ea assert: Memory not valid. //with -da sometimes segfaults, sometimes passes! reg.getByte(); } @Test(expectedExceptions = BufferPositionInvariantsException.class) public void checkBaseBufferInvariants() { WritableBuffer wbuf = WritableMemory.allocate(64).asWritableBuffer(); wbuf.setStartPositionEnd(1, 0, 2); //out of order } @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } /** * @param s String to print */ static void println(final String s) { //System.out.println(s); } }
2,298
0
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory
Create_ds/datasketches-memory/datasketches-memory-java8/src/test/java/org/apache/datasketches/memory/internal/AllocateDirectWritableMapMemoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Note: Lincoln's Gettysburg Address is in the public domain. See LICENSE. */ package org.apache.datasketches.memory.internal; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.datasketches.memory.internal.Util.getResourceFile; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.ByteOrder; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.ReadOnlyException; import org.apache.datasketches.memory.WritableMemory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class AllocateDirectWritableMapMemoryTest { private static final String LS = System.getProperty("line.separator"); @BeforeClass public void setReadOnly() { UtilTest.setGettysburgAddressFileToReadOnly(); } @Test public void simpleMap() throws Exception { File file = getResourceFile("GettysburgAddress.txt"); try (Memory mem = Memory.map(file)) { byte[] bytes = new byte[(int)mem.getCapacity()]; mem.getByteArray(0, bytes, 0, bytes.length); String text = new String(bytes, UTF_8); println(text); try { mem.force(); fail(); } catch (ReadOnlyException e) { //OK } } } @Test public void copyOffHeapToMemoryMappedFile() throws Exception { long bytes = 1L << 10; //small for unit tests. Make it larger than 2GB if you like. long longs = bytes >>> 3; File file = new File("TestFile.bin"); if (file.exists()) { try { java.nio.file.Files.delete(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } } assertTrue(file.createNewFile()); assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false assertTrue(file.isFile()); file.deleteOnExit(); //comment out if you want to examine the file. try ( WritableMemory dstMem = WritableMemory.writableMap(file, 0, bytes, ByteOrder.nativeOrder()); WritableMemory srcMem = WritableMemory.allocateDirect(bytes)) { for (long i = 0; i < longs; i++) { srcMem.putLong(i << 3, i); //load source with consecutive longs } srcMem.copyTo(0, dstMem, 0, srcMem.getCapacity()); //off-heap to off-heap copy dstMem.force(); //push any remaining to the file //check end value assertEquals(dstMem.getLong(longs - 1L << 3), longs - 1L); } } @Test public void checkNonNativeFile() throws Exception { File file = new File("TestFile2.bin"); if (file.exists()) { try { java.nio.file.Files.delete(file.toPath()); } catch (IOException e) { throw new RuntimeException(e); } } assertTrue(file.createNewFile()); assertTrue(file.setWritable(true, false)); //writable=true, ownerOnly=false assertTrue(file.isFile()); file.deleteOnExit(); //comment out if you want to examine the file. final long bytes = 8; try (WritableMemory wmem = WritableMemory.writableMap(file, 0L, bytes, Util.NON_NATIVE_BYTE_ORDER)) { wmem.putChar(0, (char) 1); assertEquals(wmem.getByte(1), (byte) 1); } } @Test(expectedExceptions = RuntimeException.class) public void testMapException() throws IOException { File dummy = createFile("dummy.txt", ""); //zero length //throws IOException "Invalid Argument" Memory.map(dummy, 0, dummy.length(), ByteOrder.nativeOrder()); } @Test(expectedExceptions = ReadOnlyException.class) public void simpleMap2() throws IOException { File file = getResourceFile("GettysburgAddress.txt"); assertTrue(file.canRead() && !file.canWrite()); try (WritableMemory wmem = WritableMemory.writableMap(file)) { //throws // } } @Test(expectedExceptions = ReadOnlyException.class) public void checkOverLength() throws Exception { File file = getResourceFile("GettysburgAddress.txt"); WritableMemory.writableMap(file, 0, 1 << 20, ByteOrder.nativeOrder()); } @Test public void testForce() throws Exception { String origStr = "Corectng spellng mistks"; File origFile = createFile("force_original.txt", origStr); //23 assertTrue(origFile.setWritable(true, false)); long origBytes = origFile.length(); String correctStr = "Correcting spelling mistakes"; //28 byte[] correctByteArr = correctStr.getBytes(UTF_8); long corrBytes = correctByteArr.length; try (Memory map = Memory.map(origFile, 0, origBytes, ByteOrder.nativeOrder())) { map.load(); assertTrue(map.isLoaded()); //confirm orig string byte[] buf = new byte[(int)origBytes]; map.getByteArray(0, buf, 0, (int)origBytes); String bufStr = new String(buf, UTF_8); assertEquals(bufStr, origStr); } try (WritableMemory wMap = WritableMemory.writableMap(origFile, 0, corrBytes, ByteOrder.nativeOrder())) { wMap.load(); assertTrue(wMap.isLoaded()); // over write content wMap.putByteArray(0, correctByteArr, 0, (int)corrBytes); wMap.force(); //confirm correct string byte[] buf = new byte[(int)corrBytes]; wMap.getByteArray(0, buf, 0, (int)corrBytes); String bufStr = new String(buf, UTF_8); assertEquals(bufStr, correctStr); } } private static File createFile(String fileName, String text) throws FileNotFoundException { File file = new File(fileName); file.deleteOnExit(); PrintWriter writer; try { writer = new PrintWriter(file, UTF_8.name()); writer.print(text); writer.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return file; } @Test public void printlnTest() { println("PRINTING: " + this.getClass().getName()); } static void println(final Object o) { if (o == null) { print(LS); } else { print(o.toString() + LS); } } /** * @param o value to print */ static void print(final Object o) { if (o != null) { //System.out.print(o.toString()); //disable here } } }
2,299