count successes for hosts, add method to retrieve only successful hosts

This commit is contained in:
Zlatin Balevsky
2018-07-27 00:06:29 +01:00
parent 6380af7d12
commit 9bd40b01de
2 changed files with 21 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ class Host {
private static final int MAX_FAILURES = 3 private static final int MAX_FAILURES = 3
final Destination destination final Destination destination
int failures int failures,successes
public Host(Destination destination) { public Host(Destination destination) {
this.destination = destination this.destination = destination
@@ -15,13 +15,19 @@ class Host {
synchronized void onConnect() { synchronized void onConnect() {
failures = 0 failures = 0
successes++
} }
synchronized void onFailure() { synchronized void onFailure() {
failures++ failures++
successes = 0
} }
synchronized boolean isFailed() { synchronized boolean isFailed() {
failures >= MAX_FAILURES failures >= MAX_FAILURES
} }
synchronized boolean hasSucceeded() {
successes > 0
}
} }

View File

@@ -84,6 +84,18 @@ class HostCache extends Service {
rv[0..n-1] rv[0..n-1]
} }
List<Destination> getGoodHosts(int n) {
List<Destination> rv = new ArrayList<>(hosts.keySet())
rv.retainAll {
Host host = hosts[it]
allowHost(host) && host.hasSucceeded()
}
if (rv.size() <= n)
return rv
Collections.shuffle(rv)
rv[0..n-1]
}
void load() { void load() {
if (storage.exists()) { if (storage.exists()) {
JsonSlurper slurper = new JsonSlurper() JsonSlurper slurper = new JsonSlurper()
@@ -92,6 +104,7 @@ class HostCache extends Service {
Destination dest = new Destination(entry.destination) Destination dest = new Destination(entry.destination)
Host host = new Host(dest) Host host = new Host(dest)
host.failures = Integer.valueOf(String.valueOf(entry.failures)) host.failures = Integer.valueOf(String.valueOf(entry.failures))
host.successes = Integer.valueOf(String.valueOf(entry.successes))
if (allowHost(host)) if (allowHost(host))
hosts.put(dest, host) hosts.put(dest, host)
} }
@@ -125,6 +138,7 @@ class HostCache extends Service {
def map = [:] def map = [:]
map.destination = dest.toBase64() map.destination = dest.toBase64()
map.failures = host.failures map.failures = host.failures
map.successes = host.successes
def json = JsonOutput.toJson(map) def json = JsonOutput.toJson(map)
writer.println json writer.println json
} }