id stringlengths 27 31 | content stringlengths 14 287k | max_stars_repo_path stringlengths 52 57 |
|---|---|---|
crossvul-java_data_bad_3077_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3077_5 |
crossvul-java_data_good_3079_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void testUtilityStats() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals(accumulatedValue));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN, AggregationType.MAX));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink));
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version > 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
double maxAvg = 0;
double countPerMaxAvgBin = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.avg != null && bin.avg > maxAvg) {
maxAvg = bin.avg;
countPerMaxAvgBin = bin.count;
}
}
assertTrue(maxAvg > 0);
assertTrue(countPerMaxAvgBin >= 1);
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_4 |
crossvul-java_data_bad_3081_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = name.intern();
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_0 |
crossvul-java_data_bad_3082_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.http.netty.NettyHttpListener;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleNonPersistedService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test(expected = TimeoutException.class)
public void startCoreServicesSynchronouslyWithTimeout() throws Throwable {
setUp(false);
// use reflection to shorten operation timeout value
Field field = ServiceHost.class.getDeclaredField("state");
field.setAccessible(true);
ServiceHost.ServiceHostState state = (ServiceHostState) field.get(this.host);
state.operationTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(100);
this.host.startCoreServicesSynchronously(new StatelessService() {
@SuppressWarnings("unused")
public static final String SELF_LINK = "/foo";
@Override
public void handleStart(Operation startPost) {
// do not complete
}
});
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState[] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String[] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis * 5));
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, slowMaintInterval);
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
long end = System.nanoTime() / 1000;
double expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all slow minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
ServiceStat http1AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountDaily));
return false;
}
ServiceStat http1AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountHourly));
return false;
}
ServiceStat http2AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountDaily));
return false;
}
ServiceStat http2AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(100));
// no INSTRUMENTATION, as it prevents cache eviction
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// wait for some host maintenance intervals
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// verify services have stopped
this.host.waitFor("wait for services to stop.", () -> {
for (Service service : services) {
if (this.host.getServiceStage(service.getSelfLink()) != null) {
return false;
}
}
return true;
});
// reset cache clear delay to default value
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_SERVICE_CACHE_CLEAR_DELAY_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(services.size());
for (Service service : services) {
Operation get = Operation.createGet(service.getUri()).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * services.size());
for (Service service : services) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(service.getUri()).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
// verify cache miss count
ServiceStat cacheMissStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertTrue(cacheMissStat.latestValue >= this.serviceCount);
// verify cache hit count
ServiceStat cacheHitStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_HIT_COUNT);
assertNotNull(cacheHitStat);
assertTrue(cacheHitStat.latestValue >= requestCount * this.serviceCount);
// now set host cache clear delay to a short value but the services' cached clear
// delay to a long value, and verify that the services are stopped only after
// the long value
List<Service> cachedServices = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
for (Service service : cachedServices) {
service.setCacheClearDelayMicros(TimeUnit.SECONDS.toMicros(5));
}
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(100));
double newMaintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > newMaintCount + 1;
});
for (Service service : cachedServices) {
assertEquals(ProcessingStage.AVAILABLE,
this.host.getServiceStage(service.getSelfLink()));
}
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > newMaintCount + 5;
});
for (Service service : cachedServices) {
ProcessingStage processingStage = this.host.getServiceStage(service.getSelfLink());
assertTrue(processingStage == null || processingStage == ProcessingStage.STOPPED);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[]{
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS};
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
@Test
public void serviceStopDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service stop
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
String factoryLink = OnDemandLoadFactoryService.create(this.host);
URI factoryURI = UriUtils.buildUri(this.host, factoryLink);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will stop all the services
// we just created since the memory limit was set so low.
long expectedStopTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedStopTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify stopped services get started.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting stop to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be started
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely stopped) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
}
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop service more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should succeed, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectSuccess(deleteOp);
// create a service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped.
// This verifies that a service will stop while it is idle for some duration
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
int requestCount = 10;
int requestDelayMills = 40;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping the service to induce collision
// of stop with active requests. First prevent automatic stop by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a start
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
// temporarily disabled - https://jira-hzn.eng.vmware.com/browse/VRXEN-21
/*
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
*/
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
@Test
public void queryServiceUrisWithAuth() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new ExampleNonPersistedService());
this.host.waitForServiceAvailable(ExampleNonPersistedService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
// create user foo@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserFoo = this.host.testCreate(1);
String userFoo = "foo@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userFoo)
.setUserSelfLink(userFoo)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "foo")
.build())
.setCompletion(createUserFoo.getCompletion())
.start();
createUserFoo.await();
// create user bar@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserBar = this.host.testCreate(1);
String userBar = "bar@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userBar)
.setUserSelfLink(userBar)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build())
.setCompletion(createUserBar.getCompletion())
.start();
createUserBar.await();
// create foo & bar documents
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
ExampleServiceState exampleBar = new ExampleServiceState();
exampleBar.name = "bar";
exampleBar.documentSelfLink = "bar";
List<Operation> posts = new ArrayList<>();
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleFoo));
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleBar));
sender.sendAndWait(posts);
AuthTestUtils.resetAuthorizationContext(this.host);
// login as foo
AuthTestUtils.loginAndSetToken(this.host, "foo@example.com", "password");
Operation factoryGetFoo = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultFoo = sender.sendAndWait(factoryGetFoo, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultFoo.documentLinks.size());
assertEquals("/core/nonpersist-examples/foo", factoryGetResultFoo.documentLinks.get(0));
// login as bar
AuthTestUtils.loginAndSetToken(this.host, "bar@example.com", "password");
Operation factoryGetBar = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultBar = sender.sendAndWait(factoryGetBar, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultBar.documentLinks.size());
assertEquals("/core/nonpersist-examples/bar", factoryGetResultBar.documentLinks.get(0));
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void findOwnerNode() throws Throwable {
setUp(false);
int nodeCount = 3;
int pathVerificationCount = 3;
this.host.setUpPeerHosts(nodeCount);
this.host.joinNodesAndVerifyConvergence(nodeCount, true);
this.host.setNodeGroupQuorum(nodeCount);
// each host should say same owner for the path
for (int i = 0; i < pathVerificationCount; i++) {
String path = UUID.randomUUID().toString();
Map<String, String> map = new HashMap<>();
Set<String> ownerIds = new HashSet<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String ownerId = h.findOwnerNode(null, path).ownerNodeId;
map.put(h.getId(), ownerId);
ownerIds.add(ownerId);
}
assertThat(ownerIds).as("all peers say same owner for %s. %s", path, map).hasSize(1);
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@Test
public void findLocalRootNamespaceServiceViaURI() throws Throwable {
setUp(false);
// full URI for the localhost (ex: http://127.0.0.1:50000)
URI rootUri = this.host.getUri();
// ex: http://127.0.0.1:50000/
URI rootUriWithPath = UriUtils.buildUri(this.host.getUri(), UriUtils.URI_PATH_CHAR);
// Accessing localhost with URI will short-circuit the call to direct method invocation. (No netty layer)
// This should resolve the RootNamespaceService
this.host.getTestRequestSender().sendAndWait(Operation.createGet(rootUri));
// same for the URI with path-character
this.host.getTestRequestSender().sendAndWait(Operation.createGet(rootUriWithPath));
}
@Test
public void cors() throws Throwable {
// CORS config for http://example.com
CorsConfig corsConfig = CorsConfigBuilder.forOrigin("http://example.com")
.allowedRequestMethods(HttpMethod.PUT)
.allowedRequestHeaders("x-xenon")
.build();
this.host = new VerificationHost() {
@Override
protected void configureHttpListener(ServiceRequestListener httpListener) {
// enable CORS
((NettyHttpListener) httpListener).setCorsConfig(corsConfig);
}
};
VerificationHost.initialize(this.host, VerificationHost.buildDefaultServiceHostArguments(0));
this.host.start();
TestRequestSender sender = this.host.getTestRequestSender();
Operation get;
Operation preflight;
Operation response;
// Request from http://example.com
get = Operation.createGet(this.host, "/")
.addRequestHeader("origin", "http://example.com")
.forceRemote();
response = sender.sendAndWait(get);
assertEquals("http://example.com", response.getResponseHeader("access-control-allow-origin"));
// Request from http://not-example.com
get = Operation.createGet(this.host, "/")
.addRequestHeader("origin", "http://not-example.com")
.forceRemote();
response = sender.sendAndWait(get);
assertNull(response.getResponseHeader("access-control-allow-origin"));
// Preflight from http://example.com
preflight = Operation.createOptions(this.host, "/")
.addRequestHeader("origin", "http://example.com")
.addRequestHeader("Access-Control-Request-Method", "POST")
.forceRemote();
response = sender.sendAndWait(preflight);
assertEquals("http://example.com", response.getResponseHeader("access-control-allow-origin"));
assertEquals("PUT", response.getResponseHeader("access-control-allow-methods"));
assertEquals("x-xenon", response.getResponseHeader("access-control-allow-headers"));
// Preflight from http://not-example.com
preflight = Operation.createOptions(this.host, "/")
.addRequestHeader("origin", "http://not-example.com")
.addRequestHeader("Access-Control-Request-Method", "POST")
.addRequestHeader(Operation.CONNECTION_HEADER, "close")
.setKeepAlive(false)
.forceRemote();
response = sender.sendAndWait(preflight);
assertNull(response.getResponseHeader("access-control-allow-origin"));
assertNull(response.getResponseHeader("access-control-allow-methods"));
assertNull(response.getResponseHeader("access-control-allow-headers"));
}
@After
public void tearDown() {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
if (!this.host.isStopping()) {
AuthTestUtils.logout(this.host);
}
this.host.tearDown();
this.host = null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_3 |
crossvul-java_data_good_3079_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
return createRoles(target, email, true);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email, boolean createUserGroupByEmail) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
String userGroupLink = null;
// Create user group
if (createUserGroupByEmail) {
userGroupLink = createUserGroup(target, getUserGroupName(email), Builder.create()
.addFieldClause(
"email",
email)
.build());
} else {
String groupName = getUserGroupName(email);
userGroupLink = createUserGroup(target, groupName, Builder.create()
.addFieldClause(
QuerySpecification
.buildCollectionItemName(UserState.FIELD_NAME_USER_GROUP_LINKS),
UriUtils.buildUriPath(UserGroupService.FACTORY_LINK, groupName))
.build());
}
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = new UserGroupState();
userGroupState.documentSelfLink = selfLink;
userGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.documentSelfLink = selfLink;
resourceGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = new RoleState();
roleState.documentSelfLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink);
roleState.userGroupLink = userGroupLink;
roleState.resourceGroupLink = resourceGroupLink;
roleState.verbs = verbs;
roleState.policy = Policy.ALLOW;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_5 |
crossvul-java_data_good_3080_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
} finally {
h.stop();
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT);
if (http1PendingCount == null) {
this.host.log("http1 pending op stats not present");
return false;
}
ServiceStat http2PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT);
if (http2PendingCount == null) {
this.host.log("http2 pending op stats not present");
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertTrue(this.host.getServiceStage(servicePath) == ProcessingStage.AVAILABLE);
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Service
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
1,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
URI serviceUri = states.keySet().iterator().next();
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
// Subscribe to created service
TestContext ctx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
TestContext notifyCtx = this.host.testCreate(2);
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
this.host.testWait(ctx);
// do a PATCH, to trigger a notification
TestContext patchCtx = this.host.testCreate(1);
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
this.host.testWait(patchCtx);
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> this.host.getServiceStage(serviceUri.getPath()) == null);
// Let's do a PATCH again
st.name = "secondPatch";
patchCtx = this.host.testCreate(1);
patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
this.host.testWait(patchCtx);
// Wait for the patch notifications. This will exit only
// when both notifications have been received.
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void getAvailableServicesWithOptions() throws Throwable {
setUp(false);
int serviceCount = 5;
List<URI> exampleURIs = new ArrayList<>();
this.host.createExampleServices(this.host, serviceCount, exampleURIs,
Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_3 |
crossvul-java_data_bad_3083_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_1 |
crossvul-java_data_bad_3082_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SynchronizationRequest;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION)) {
handleSynchRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleSynchRequest(Operation op) {
if (op.getAction() != Action.PATCH && op.getAction() != Action.PUT) {
Operation.failActionNotSupported(op);
return;
}
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
SynchronizationRequest synchRequest = op.getBody(SynchronizationRequest.class);
if (synchRequest.kind == null || !synchRequest.kind.equals(Utils.buildKind(SynchronizationRequest.class))) {
op.fail(new IllegalArgumentException(String.format(
"Invalid 'kind' in the request body")));
return;
}
if (!synchRequest.documentSelfLink.equals(this.parent.getSelfLink())) {
op.fail(new IllegalArgumentException("Invalid param in the body: " + synchRequest.documentSelfLink));
return;
}
// Synchronize the FactoryService
if (this.parent instanceof FactoryService) {
((FactoryService)this.parent).synchronizeChildServicesIfOwner(new Operation());
op.complete();
return;
}
if (this.parent instanceof StatelessService) {
op.fail(new IllegalArgumentException("Nothing to synchronize for stateless service: " +
synchRequest.documentSelfLink));
return;
}
// Synchronize the single child service.
synchronizeChildService(this.parent.getSelfLink(), op);
}
private void synchronizeChildService(String link, Operation op) {
// To trigger synchronization of the child-service, we make
// a SYNCH-OWNER request. The request body is an empty document
// with just the documentSelfLink property set to the link
// of the child-service. This is done so that the FactoryService
// routes the request to the DOCUMENT_OWNER.
ServiceDocument d = new ServiceDocument();
d.documentSelfLink = UriUtils.getLastPathSegment(link);
String factoryLink = UriUtils.getParentPath(link);
Operation.CompletionHandler c = (o, e) -> {
if (e != null) {
String msg = String.format("Synchronization failed for service %s with status code %d, message %s",
o.getUri().getPath(), o.getStatusCode(), e.getMessage());
this.parent.getHost().log(Level.WARNING, msg);
op.fail(new IllegalStateException(msg));
return;
}
op.complete();
};
Operation.createPost(this, factoryLink)
.setBody(d)
.setCompletion(c)
.setReferer(getUri())
.setConnectionSharing(true)
.setConnectionTag(ServiceClient.CONNECTION_TAG_SYNCHRONIZATION)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.sendWith(this.parent);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT || op.getAction() == Action.POST) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public void setProcessingStage(ProcessingStage initialized) {
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public void setCacheClearDelayMicros(long micros) {
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public long getCacheClearDelayMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_0 |
crossvul-java_data_good_3075_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.setSystemAuthorizationContext();
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
this.host.resetAuthorizationContext();
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_2 |
crossvul-java_data_bad_3075_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid aith subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.forceRemote()
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
this.host.testStart(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// issue a GET on a factory with no auth context, no documents should be returned
this.host.testStart(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email, true);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_1 |
crossvul-java_data_good_3077_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_0 |
crossvul-java_data_bad_3078_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_3 |
crossvul-java_data_bad_3082_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testODLGetWithAuthorization() throws Throwable {
long cacheDelayInterval = TimeUnit.MILLISECONDS.toMicros(100);
this.host.setMaintenanceIntervalMicros(cacheDelayInterval);
this.host.setServiceCacheClearDelayMicros(cacheDelayInterval);
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
Query resourceGroupQuery = Query.Builder.create().addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK, "*", MatchType.WILDCARD).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, email, resourceGroupQuery);
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// verify services have stopped
this.host.waitFor("wait for services to stop.", () -> {
for (Service service : services) {
if (this.host.getServiceStage(service.getSelfLink()) != null) {
return false;
}
}
return true;
});
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectFailure(
Operation.createGet(UriUtils.buildUri(this.host, services.get(0).getSelfLink())));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.of(Action.GET));
// Assume identity, GET should now succeed
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, services.get(0).getSelfLink())));
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
URI uri = UriUtils.buildUri(this.host, selfLink);
Operation patchOperation =
Operation.createPatch(uri)
.setBody(exampleServices.get(uri))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3082_1 |
crossvul-java_data_bad_3081_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_4 |
crossvul-java_data_good_3082_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SynchronizationRequest;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION)) {
handleSynchRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleSynchRequest(Operation op) {
if (op.getAction() != Action.PATCH && op.getAction() != Action.PUT) {
Operation.failActionNotSupported(op);
return;
}
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
SynchronizationRequest synchRequest = op.getBody(SynchronizationRequest.class);
if (synchRequest.kind == null || !synchRequest.kind.equals(Utils.buildKind(SynchronizationRequest.class))) {
op.fail(new IllegalArgumentException(String.format(
"Invalid 'kind' in the request body")));
return;
}
if (!synchRequest.documentSelfLink.equals(this.parent.getSelfLink())) {
op.fail(new IllegalArgumentException("Invalid param in the body: " + synchRequest.documentSelfLink));
return;
}
// Synchronize the FactoryService
if (this.parent instanceof FactoryService) {
((FactoryService)this.parent).synchronizeChildServicesIfOwner(new Operation());
op.complete();
return;
}
if (this.parent instanceof StatelessService) {
op.fail(new IllegalArgumentException("Nothing to synchronize for stateless service: " +
synchRequest.documentSelfLink));
return;
}
// Synchronize the single child service.
synchronizeChildService(this.parent.getSelfLink(), op);
}
private void synchronizeChildService(String link, Operation op) {
// To trigger synchronization of the child-service, we make
// a SYNCH-OWNER request. The request body is an empty document
// with just the documentSelfLink property set to the link
// of the child-service. This is done so that the FactoryService
// routes the request to the DOCUMENT_OWNER.
ServiceDocument d = new ServiceDocument();
d.documentSelfLink = UriUtils.getLastPathSegment(link);
String factoryLink = UriUtils.getParentPath(link);
Operation.CompletionHandler c = (o, e) -> {
if (e != null) {
String msg = String.format("Synchronization failed for service %s with status code %d, message %s",
o.getUri().getPath(), o.getStatusCode(), e.getMessage());
this.parent.getHost().log(Level.WARNING, msg);
op.fail(new IllegalStateException(msg));
return;
}
op.complete();
};
Operation.createPost(this, factoryLink)
.setBody(d)
.setCompletion(c)
.setReferer(getUri())
.setConnectionSharing(true)
.setConnectionTag(ServiceClient.CONNECTION_TAG_SYNCHRONIZATION)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.sendWith(this.parent);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT || op.getAction() == Action.POST) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public void setProcessingStage(ProcessingStage initialized) {
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public void setCacheClearDelayMicros(long micros) {
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public long getCacheClearDelayMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_0 |
crossvul-java_data_good_3082_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_4 |
crossvul-java_data_good_3077_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_6 |
crossvul-java_data_good_3075_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.services.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.AuthorizationSetupHelper;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.FactoryService;
import com.vmware.xenon.common.NodeSelectorService.SelectAndForwardRequest;
import com.vmware.xenon.common.NodeSelectorService.SelectOwnerResponse;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationJoin;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceHost.HttpScheme;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.StatefulService;
import com.vmware.xenon.common.SynchronizationTaskService;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.RoundRobinIterator;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleTaskService.ExampleTaskServiceState;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupBroadcastResult.PeerNodeResult;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceErrorResponse;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceState;
import com.vmware.xenon.services.common.ResourceGroupService.PatchQueryRequest;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestNodeGroupService {
public static class PeriodicExampleFactoryService extends FactoryService {
public static final String SELF_LINK = "test/examples-periodic";
public PeriodicExampleFactoryService() {
super(ExampleServiceState.class);
}
@Override
public Service createServiceInstance() throws Throwable {
ExampleService s = new ExampleService();
s.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
return s;
}
}
public static class ExampleServiceWithCustomSelector extends StatefulService {
public ExampleServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.REPLICATION, true);
super.toggleOption(ServiceOption.OWNER_SELECTION, true);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ExampleFactoryServiceWithCustomSelector extends FactoryService {
public ExampleFactoryServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.setPeerNodeSelectorPath(CUSTOM_GROUP_NODE_SELECTOR);
}
@Override
public Service createServiceInstance() throws Throwable {
return new ExampleServiceWithCustomSelector();
}
}
private static final String CUSTOM_EXAMPLE_SERVICE_KIND = "xenon:examplestate";
private static final String CUSTOM_NODE_GROUP_NAME = "custom";
private static final String CUSTOM_NODE_GROUP = UriUtils.buildUriPath(
ServiceUriPaths.NODE_GROUP_FACTORY,
CUSTOM_NODE_GROUP_NAME);
private static final String CUSTOM_GROUP_NODE_SELECTOR = UriUtils.buildUriPath(
ServiceUriPaths.NODE_SELECTOR_PREFIX,
CUSTOM_NODE_GROUP_NAME);
public static final long DEFAULT_MAINT_INTERVAL_MICROS = TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
private VerificationHost host;
/**
* Command line argument specifying number of times to run the same test method.
*/
public int testIterationCount = 1;
/**
* Command line argument specifying default number of in process service hosts
*/
public int nodeCount = 3;
/**
* Command line argument specifying request count
*/
public int updateCount = 10;
/**
* Command line argument specifying service instance count
*/
public int serviceCount = 10;
/**
* Command line argument specifying test duration
*/
public long testDurationSeconds;
/**
* Command line argument specifying iterations per test method
*/
public long iterationCount = 1;
/**
* Command line argument used by replication long running tests
*/
public long totalOperationLimit = Long.MAX_VALUE;
private NodeGroupConfig nodeGroupConfig = new NodeGroupConfig();
private EnumSet<ServiceOption> postCreationServiceOptions = EnumSet.noneOf(ServiceOption.class);
private boolean expectFailure;
private long expectedFailureStartTimeMicros;
private List<URI> expectedFailedHosts = new ArrayList<>();
private String replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
private String replicationNodeSelector = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
private long replicationFactor;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
if (!this.host.isRemotePeerTest() &&
!CUSTOM_EXAMPLE_SERVICE_KIND.equals(current.documentKind)) {
return false;
}
return current.name.equals(initial.name);
};
private Function<ExampleServiceState, Void> exampleStateUpdateBodySetter = (
ExampleServiceState state) -> {
state.name = Utils.getNowMicrosUtc() + "";
return null;
};
private boolean isPeerSynchronizationEnabled = true;
private boolean isAuthorizationEnabled = false;
private HttpScheme replicationUriScheme;
private boolean skipAvailabilityChecks = false;
private boolean isMultiLocationTest = false;
private void setUp(int localHostCount) throws Throwable {
if (this.host != null) {
return;
}
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
this.host.setAuthorizationEnabled(this.isAuthorizationEnabled);
VerificationHost.createAndAttachSSLClient(this.host);
if (this.replicationUriScheme == HttpScheme.HTTPS_ONLY) {
// disable HTTP, forcing host.getPublicUri() to return a HTTPS schemed URI. This in
// turn forces the node group to use HTTPS for join, replication, etc
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// the default is disable (-1) so we must set port to 0, to enable SSL and make the
// runtime pick a random HTTPS port
this.host.setSecurePort(0);
}
if (this.testDurationSeconds > 0) {
// for long running tests use the default interval to match production code
this.host.maintenanceIntervalMillis = TimeUnit.MICROSECONDS.toMillis(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
}
this.host.start();
if (this.host.isAuthorizationEnabled()) {
this.host.setSystemAuthorizationContext();
}
CommandLineArgumentParser.parseFromProperties(this.host);
this.host.setStressTest(this.host.isStressTest);
this.host.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
this.host.setMultiLocationTest(this.isMultiLocationTest);
this.host.setUpPeerHosts(localHostCount);
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
setUpPeerHostWithAdditionalServices(h1);
}
// If the peer hosts are remote, then we undo CUSTOM_EXAMPLE_SERVICE_KIND
// from the KINDS cache and use the real documentKind of ExampleService.
if (this.host.isRemotePeerTest()) {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
}
}
private void setUpPeerHostWithAdditionalServices(VerificationHost h1) throws Throwable {
h1.setStressTest(this.host.isStressTest);
h1.waitForServiceAvailable(ExampleService.FACTORY_LINK);
Replication1xExampleFactoryService exampleFactory1x = new Replication1xExampleFactoryService();
h1.startServiceAndWait(exampleFactory1x,
Replication1xExampleFactoryService.SELF_LINK,
null);
Replication3xExampleFactoryService exampleFactory3x = new Replication3xExampleFactoryService();
h1.startServiceAndWait(exampleFactory3x,
Replication3xExampleFactoryService.SELF_LINK,
null);
// start the replication test factory service with OWNER_SELECTION
ReplicationFactoryTestService ownerSelRplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(ownerSelRplFactory,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK,
null);
// start the replication test factory service with STRICT update checking
ReplicationFactoryTestService strictReplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(strictReplFactory,
ReplicationFactoryTestService.STRICT_SELF_LINK, null);
// start the replication test factory service with simple replication, no owner selection
ReplicationFactoryTestService replFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(replFactory,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK, null);
}
private Map<URI, URI> getFactoriesPerNodeGroup(String factoryLink) {
Map<URI, URI> map = this.host.getNodeGroupToFactoryMap(factoryLink);
for (URI h : this.expectedFailedHosts) {
URI e = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
// do not send messages through hosts that will be stopped: this allows all messages to
// end the node group and the succeed or fail based on the test goals. If we let messages
// route through a host that we will abruptly stop, the message might timeout, which is
// OK for the expected failure case when quorum is not met, but will prevent is from confirming
// in the non eager consistency case, that all updates were written to at least one host
map.remove(e);
}
return map;
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
Utils.registerKind(ExampleServiceState.class, CUSTOM_EXAMPLE_SERVICE_KIND);
}
private void setUpOnDemandLoad() throws Throwable {
setUp();
// we need at least 5 nodes, because we're going to stop 2
// nodes and we need majority quorum
this.nodeCount = Math.max(5, this.nodeCount);
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
// create node group, join nodes and set majority quorum
setUp(this.nodeCount);
toggleOnDemandLoad();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.host.getPeerCount() / 2 + 1);
}
private void toggleOnDemandLoad() {
for (URI nodeUri : this.host.getNodeGroupMap().keySet()) {
URI factoryUri = UriUtils.buildUri(nodeUri, ExampleService.FACTORY_LINK);
this.host.toggleServiceOptions(factoryUri, EnumSet.of(ServiceOption.ON_DEMAND_LOAD),
null);
}
}
@After
public void tearDown() throws InterruptedException {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
if (this.host == null) {
return;
}
if (this.host.isRemotePeerTest()) {
try {
this.host.logNodeProcessLogs(this.host.getNodeGroupMap().keySet(),
ServiceUriPaths.PROCESS_LOG);
} catch (Throwable e) {
this.host.log("Failure retrieving process logs: %s", Utils.toString(e));
}
try {
this.host.logNodeManagementState(this.host.getNodeGroupMap().keySet());
} catch (Throwable e) {
this.host.log("Failure retrieving management state: %s", Utils.toString(e));
}
}
this.host.tearDownInProcessPeers();
this.host.toggleNegativeTestMode(false);
this.host.tearDown();
this.host = null;
System.clearProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS);
}
@Test
public void synchronizationCollisionWithPosts() throws Throwable {
// POST requests go through the FactoryService
// and do not get queued with Synchronization
// requests, so if synchronization was running
// while POSTs were happening for the same factory
// service, we could run into collisions. This test
// verifies that xenon handles such collisions and
// POST requests are always successful.
// Join the nodes with full quorum and wait for nodes to
// converge and synchronization to complete.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// Find the owner node for /core/examples. We will
// use it to start on-demand synchronization for
// this factory
URI factoryUri = UriUtils.buildUri(this.host.getPeerHost(), ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(factoryUri, this.replicationNodeSelector);
String taskPath = UriUtils.buildUriPath(
SynchronizationTaskService.FACTORY_LINK,
UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
VerificationHost owner = null;
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
if (peer.isOwner(ExampleService.FACTORY_LINK, ServiceUriPaths.DEFAULT_NODE_SELECTOR)) {
owner = peer;
break;
}
}
this.host.log(Level.INFO, "Owner of synch-task is %s", owner.getId());
// Get the membershipUpdateTimeMicros so that we can
// kick-off the synch-task on-demand.
URI taskUri = UriUtils.buildUri(owner, taskPath);
SynchronizationTaskService.State taskState = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
long membershipUpdateTimeMicros = taskState.membershipUpdateTimeMicros;
// Start posting and in the middle also start
// synchronization. All POSTs should succeed!
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
TestContext ctx = this.host.testCreate((this.serviceCount * 10) + 1);
for (int i = 0; i < this.serviceCount * 10; i++) {
if (i == 5) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK);
task.factorySelfLink = ExampleService.FACTORY_LINK;
task.factoryStateKind = Utils.buildKind(ExampleService.ExampleServiceState.class);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros + 1;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
Operation post = Operation
.createPost(owner, SynchronizationTaskService.FACTORY_LINK)
.setBody(task)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
Operation post = Operation
.createPost(factoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void recognizeSelfInPeerNodesByPublicUri() throws Throwable {
String id = "node-" + VerificationHost.hostNumber.incrementAndGet();
String publicUri = "http://myhostname.local:";
// In order not to hardcode a port, 0 is used which will pick random port.
// The value of the random port is then used to set the initialPeerNodes and publicUri is if they
// used the assigned port to begin with.
ExampleServiceHost nodeA = new ExampleServiceHost() {
@Override
public List<URI> getInitialPeerHosts() {
try {
Field field = ServiceHost.class.getDeclaredField("state");
field.setAccessible(true);
ServiceHostState s = (ServiceHostState) field.get(this);
s.initialPeerNodes = new String[] { publicUri + getPort() };
s.publicUri = URI.create(publicUri + getPort());
} catch (Exception e) {
throw new RuntimeException(e);
}
return super.getInitialPeerHosts();
}
};
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
try {
String[] args = {
"--port=0",
"--id=" + id,
"--publicUri=" + publicUri,
"--bindAddress=127.0.0.1",
"--sandbox=" + tmpFolderA.getRoot().getAbsolutePath()
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP, null);
TestRequestSender sender = new TestRequestSender(nodeA);
Operation op = Operation.createGet(nodeGroupUri)
.setReferer(nodeA.getUri());
NodeGroupState nodeGroupState = sender.sendAndWait(op, NodeGroupState.class);
assertEquals(1, nodeGroupState.nodes.size());
assertEquals(1, nodeGroupState.nodes.values().iterator().next().membershipQuorum);
} finally {
tmpFolderA.delete();
nodeA.stop();
}
}
@Test
public void commandLineJoinRetries() throws Throwable {
this.host = VerificationHost.create(0);
this.host.start();
ExampleServiceHost nodeA = null;
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
this.setUp(1);
try {
// start a node, supplying a bogus peer. Verify we retry, up to expiration which is
// the operation timeout
nodeA = new ExampleServiceHost();
String id = "nodeA-" + VerificationHost.hostNumber.incrementAndGet();
int bogusPort = 1;
String[] args = {
"--port=0",
"--id=" + id,
"--bindAddress=127.0.0.1",
"--sandbox=" + tmpFolderA.getRoot().getAbsolutePath(),
"--peerNodes=" + "http://127.0.0.1:" + bogusPort
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
// verify we see a specific retry stat
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI statsUri = UriUtils.buildStatsUri(nodeGroupUri);
this.host.waitFor("expected stat did not converge", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsUri);
ServiceStat st = stats.entries.get(NodeGroupService.STAT_NAME_JOIN_RETRY_COUNT);
if (st == null || st.latestValue < 1) {
return false;
}
return true;
});
} finally {
if (nodeA != null) {
nodeA.stop();
tmpFolderA.delete();
}
}
}
@Test
public void synchronizationOnDemandLoad() throws Throwable {
// Setup peer nodes
setUp(this.nodeCount);
long intervalMicros = TimeUnit.MILLISECONDS.toMicros(200);
// Start the ODL Factory service on all the peers.
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
// Reduce cache clear delay to short duration
// to cause ODL service stops.
h.setServiceCacheClearDelayMicros(h.getMaintenanceIntervalMicros());
// create an on demand load factory and services
OnDemandLoadFactoryService.create(h);
}
// join the nodes and set full quorum.
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Create a few child-services.
VerificationHost h = this.host.getPeerHost();
Map<URI, ExampleServiceState> childServices = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = UUID.randomUUID().toString();
o.setBody(initialState);
},
UriUtils.buildFactoryUri(h, OnDemandLoadFactoryService.class));
// Verify that each peer host reports the correct value for ODL stop count.
for (VerificationHost vh : this.host.getInProcessHostMap().values()) {
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(vh, this.serviceCount));
}
// Add a new host to the cluster.
VerificationHost newHost = this.host.setUpLocalPeerHost(0, h.getMaintenanceIntervalMicros(),
null);
newHost.setServiceCacheClearDelayMicros(intervalMicros);
OnDemandLoadFactoryService.create(newHost);
this.host.joinNodesAndVerifyConvergence(this.nodeCount + 1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Do GETs on each previously created child services by calling the newly added host.
// This will trigger synchronization for the child services.
this.host.log(Level.INFO, "Verifying synchronization for ODL services");
for (Entry<URI, ExampleServiceState> childService : childServices.entrySet()) {
String childServicePath = childService.getKey().getPath();
ExampleServiceState state = this.host.getServiceState(null,
ExampleServiceState.class, UriUtils.buildUri(newHost, childServicePath));
assertNotNull(state);
}
// Verify that the new peer host reports the correct value for ODL stop count.
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(newHost, this.serviceCount));
}
private boolean checkOdlServiceStopCount(VerificationHost host, int serviceCount)
throws Throwable {
ServiceStat stopCount = host
.getServiceStats(host.getManagementServiceUri())
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
if (stopCount == null || stopCount.latestValue < serviceCount) {
this.host.log(Level.INFO,
"Current stopCount is %s",
(stopCount != null) ? String.valueOf(stopCount.latestValue) : "null");
return false;
}
return true;
}
@Test
public void customNodeGroupWithObservers() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
Logger.getAnonymousLogger().info("Iteration: " + i);
verifyCustomNodeGroupWithObservers();
tearDown();
}
}
private void verifyCustomNodeGroupWithObservers() throws Throwable {
setUp(this.nodeCount);
// on one of the hosts create the custom group but with self as an observer. That peer should
// never receive replicated or broadcast requests
URI observerHostUri = this.host.getPeerHostUri();
ServiceHostState observerHostState = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_MANAGEMENT));
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerHostState.id;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerHostUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
final String customFactoryLink = "custom-factory";
// start a node selector attached to the custom group
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
NodeSelectorState initialState = new NodeSelectorState();
initialState.nodeGroupLink = CUSTOM_NODE_GROUP;
h.startServiceAndWait(new ConsistentHashingNodeSelectorService(),
CUSTOM_GROUP_NODE_SELECTOR, initialState);
// start the factory that is attached to the custom group selector
h.startServiceAndWait(ExampleFactoryServiceWithCustomSelector.class, customFactoryLink);
}
URI customNodeGroupServiceOnObserver = UriUtils
.buildUri(observerHostUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
expectedOptionsPerNode.put(customNodeGroupServiceOnObserver,
observerSelfState.options);
this.host.joinNodesAndVerifyConvergence(CUSTOM_NODE_GROUP, this.nodeCount,
this.nodeCount, expectedOptionsPerNode);
// one of the nodes is observer, so we must set quorum to 2 explicitly
this.host.setNodeGroupQuorum(2, customNodeGroupServiceOnObserver);
this.host.waitForNodeSelectorQuorumConvergence(CUSTOM_GROUP_NODE_SELECTOR, 2);
this.host.waitForNodeGroupIsAvailableConvergence(CUSTOM_NODE_GROUP);
int restartCount = 0;
// verify that the observer node shows up as OBSERVER on all peers, including self
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI customNodeGroupUri = UriUtils.buildUri(hostUri, CUSTOM_NODE_GROUP);
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
customNodeGroupUri);
for (NodeState ns : ngs.nodes.values()) {
if (ns.id.equals(observerHostState.id)) {
assertTrue(ns.options.contains(NodeOption.OBSERVER));
} else {
assertTrue(ns.options.contains(NodeOption.PEER));
}
}
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(customNodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", restartCount, 0);
// join all the nodes through the default group, making sure another group still works
this.host.joinNodesAndVerifyConvergence(this.nodeCount, true);
URI observerFactoryUri = UriUtils.buildUri(observerHostUri, customFactoryLink);
waitForReplicatedFactoryServiceAvailable(observerFactoryUri, CUSTOM_GROUP_NODE_SELECTOR);
// create N services on the custom group, verify none of them got created on the observer.
// We actually post directly to the observer node, which should forward to the other nodes
Map<URI, ExampleServiceState> serviceStatesOnPost = this.host.doFactoryChildServiceStart(
null, this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = Utils.getNowMicrosUtc() + "";
o.setBody(body);
},
observerFactoryUri);
ServiceDocumentQueryResult r = this.host.getFactoryState(observerFactoryUri);
assertEquals(0, r.documentLinks.size());
// do a GET on each service and confirm the owner id is never that of the observer node
Map<URI, ExampleServiceState> serviceStatesFromGet = this.host.getServiceState(
null, ExampleServiceState.class, serviceStatesOnPost.keySet());
for (ExampleServiceState s : serviceStatesFromGet.values()) {
if (observerHostState.id.equals(s.documentOwner)) {
throw new IllegalStateException("Observer node reported state for service");
}
}
// create additional example services which are not associated with the custom node group
// and verify that they are always included in queries which target the custom node group
// (e.g. that the query is never executed on the OBSERVER node).
createExampleServices(observerHostUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI serviceUri = UriUtils.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
URI forwardQueryUri = UriUtils.buildForwardRequestUri(serviceUri, null,
CUSTOM_GROUP_NODE_SELECTOR);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(forwardQueryUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Forwarded query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
}
task.querySpec.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.BROADCAST);
task.nodeSelectorLink = CUSTOM_GROUP_NODE_SELECTOR;
URI queryPostUri = UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_QUERY_TASKS);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(queryPostUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Broadcast query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
URI existingNodeGroup = this.host.getPeerNodeGroupUri();
// start more nodes, insert them to existing group, but with no synchronization required
// start some additional nodes
Collection<VerificationHost> existingHosts = this.host.getInProcessHostMap().values();
int additionalHostCount = this.nodeCount;
this.host.setUpPeerHosts(additionalHostCount);
List<ServiceHost> newHosts = Collections.synchronizedList(new ArrayList<>());
newHosts.addAll(this.host.getInProcessHostMap().values());
newHosts.removeAll(existingHosts);
expectedOptionsPerNode.clear();
// join new nodes with existing node group.
TestContext testContext = this.host.testCreate(newHosts.size());
for (ServiceHost h : newHosts) {
URI newCustomNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
JoinPeerRequest joinBody = JoinPeerRequest.create(existingNodeGroup, null);
joinBody.localNodeOptions = EnumSet.of(NodeOption.PEER);
this.host.send(Operation.createPost(newCustomNodeGroupUri)
.setBody(joinBody)
.setCompletion(testContext.getCompletion()));
expectedOptionsPerNode.put(newCustomNodeGroupUri, joinBody.localNodeOptions);
}
testContext.await();
this.host.waitForNodeGroupConvergence(this.host.getNodeGroupMap().values(),
this.host.getNodeGroupMap().size(),
this.host.getNodeGroupMap().size(),
expectedOptionsPerNode, false);
restartCount = 0;
// do another restart check. None of the new nodes should have reported restarts
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI nodeGroupUri = UriUtils.buildUri(hostUri, ServiceUriPaths.DEFAULT_NODE_GROUP);
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(nodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", 0,
restartCount);
}
@Test
public void verifyGossipForObservers() throws Throwable {
setUp(this.nodeCount);
Iterator<Entry<URI, URI>> nodeGroupIterator = this.host.getNodeGroupMap().entrySet()
.iterator();
URI observerUri = nodeGroupIterator.next().getKey();
String observerId = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerUri, ServiceUriPaths.CORE_MANAGEMENT)).id;
// Create a custom node group. Mark one node as OBSERVER and rest as PEER
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerId;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
// Pick a PEER and join it to each node in the node-group
URI peerUri = nodeGroupIterator.next().getKey();
URI peerCustomUri = UriUtils.buildUri(peerUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
Set<URI> customNodeUris = new HashSet<>();
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI nodeCustomUri = UriUtils.buildUri(nodeUri, CUSTOM_NODE_GROUP);
JoinPeerRequest request = new JoinPeerRequest();
request.memberGroupReference = nodeCustomUri;
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(peerCustomUri)
.setBody(request)
.setReferer(this.host.getReferer())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
ctx.await();
expectedOptionsPerNode.put(nodeCustomUri,
EnumSet.of((nodeUri == observerUri)
? NodeOption.OBSERVER : NodeOption.PEER));
customNodeUris.add(nodeCustomUri);
}
// Verify that gossip will propagate the single OBSERVER and the PEER nodes
// to every node in the custom node-group.
this.host.waitForNodeGroupConvergence(
customNodeUris, this.nodeCount, this.nodeCount, expectedOptionsPerNode, false);
}
@Test
public void synchronizationOneByOneWithAbruptNodeShutdown() throws Throwable {
setUp(this.nodeCount);
this.replicationTargetFactoryLink = PeriodicExampleFactoryService.SELF_LINK;
// start the periodic example service factory on each node
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.startServiceAndWait(PeriodicExampleFactoryService.class,
PeriodicExampleFactoryService.SELF_LINK);
}
// On one host, add some services. They exist only on this host and we expect them to synchronize
// across all hosts once this one joins with the group
VerificationHost initialHost = this.host.getPeerHost();
URI hostUriWithInitialState = initialHost.getUri();
Map<String, ExampleServiceState> exampleStatesPerSelfLink = createExampleServices(
hostUriWithInitialState);
URI hostWithStateNodeGroup = UriUtils.buildUri(hostUriWithInitialState,
ServiceUriPaths.DEFAULT_NODE_GROUP);
// before start joins, verify isolated factory synchronization is done
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
// join a node, with no state, one by one, to the host with state.
// The steps are:
// 1) set quorum to node group size + 1
// 2) Join new empty node with existing node group
// 3) verify convergence of factory state
// 4) repeat
List<URI> joinedHosts = new ArrayList<>();
Map<URI, URI> factories = new HashMap<>();
factories.put(hostWithStateNodeGroup, UriUtils.buildUri(hostWithStateNodeGroup,
this.replicationTargetFactoryLink));
joinedHosts.add(hostWithStateNodeGroup);
int fullQuorum = 1;
for (URI nodeGroupUri : this.host.getNodeGroupMap().values()) {
// skip host with state
if (hostWithStateNodeGroup.equals(nodeGroupUri)) {
continue;
}
this.host.log("Setting quorum to %d, already joined: %d",
fullQuorum + 1, joinedHosts.size());
// set quorum to expected full node group size, for the setup hosts
this.host.setNodeGroupQuorum(++fullQuorum);
this.host.testStart(1);
// join empty node, with node with state
this.host.joinNodeGroup(hostWithStateNodeGroup, nodeGroupUri, fullQuorum);
this.host.testWait();
joinedHosts.add(nodeGroupUri);
factories.put(nodeGroupUri, UriUtils.buildUri(nodeGroupUri,
this.replicationTargetFactoryLink));
this.host.waitForNodeGroupConvergence(joinedHosts, fullQuorum, fullQuorum, true);
this.host.waitForNodeGroupIsAvailableConvergence(nodeGroupUri.getPath(), joinedHosts);
this.waitForReplicatedFactoryChildServiceConvergence(
factories,
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker, exampleStatesPerSelfLink.size(),
0);
// Do updates, which will verify that the services are converged in terms of ownership.
// Since we also synchronize on demand, if there was any discrepancy, after updates, the
// services will converge
doExampleServicePatch(exampleStatesPerSelfLink,
joinedHosts.get(0));
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink, initialHost, joinedHosts, 0, 1,
ownerIds.size() - 1);
}
doNodeStopWithUpdates(exampleStatesPerSelfLink);
}
private void doExampleServicePatch(Map<String, ExampleServiceState> states,
URI nodeGroupOnSomeHost) throws Throwable {
this.host.log("Starting PATCH to %d example services", states.size());
TestContext ctx = this.host
.testCreate(this.updateCount * states.size());
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
for (int i = 0; i < this.updateCount; i++) {
for (Entry<String, ExampleServiceState> e : states.entrySet()) {
ExampleServiceState st = Utils.clone(e.getValue());
st.counter = (long) i;
Operation patch = Operation
.createPatch(UriUtils.buildUri(nodeGroupOnSomeHost, e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
this.host.log("Done with PATCH to %d example services", states.size());
}
public void doNodeStopWithUpdates(Map<String, ExampleServiceState> exampleStatesPerSelfLink)
throws Throwable {
this.host.log("Starting to stop nodes and send updates");
VerificationHost remainingHost = this.host.getPeerHost();
Collection<VerificationHost> hostsToStop = new ArrayList<>(this.host.getInProcessHostMap()
.values());
hostsToStop.remove(remainingHost);
List<URI> targetServices = new ArrayList<>();
for (String link : exampleStatesPerSelfLink.keySet()) {
// build the URIs using the host we plan to keep, so the maps we use below to lookup
// stats from URIs, work before and after node stop
targetServices.add(UriUtils.buildUri(remainingHost, link));
}
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(this.host.getTimeoutSeconds() / 3);
}
// capture current stats from each service
Map<URI, ServiceStats> prevStats = verifyMaintStatsAfterSynchronization(targetServices,
null);
stopHostsAndVerifyQueuing(hostsToStop, remainingHost, targetServices);
// its important to verify document ownership before we do any updates on the services.
// This is because we verify, that even without any on demand synchronization,
// the factory driven synchronization set the services in the proper state
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
List<URI> remainingHosts = new ArrayList<>(this.host.getNodeGroupMap().keySet());
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink,
this.host.getInProcessHostMap().values().iterator().next(),
remainingHosts, 0, 1,
ownerIds.size() - 1);
// confirm maintenance is back up and running on all services
verifyMaintStatsAfterSynchronization(targetServices, prevStats);
// nodes are stopped, do updates again, quorum is relaxed, they should work
doExampleServicePatch(exampleStatesPerSelfLink, remainingHost.getUri());
this.host.log("Done with stop nodes and send updates");
}
private void verifyDynamicMaintOptionToggle(Map<String, ExampleServiceState> childStates) {
List<URI> targetServices = new ArrayList<>();
childStates.keySet().forEach((l) -> targetServices.add(this.host.getPeerServiceUri(l)));
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
Map<URI, ServiceConfiguration> configPerService = this.host.getServiceState(
null, ServiceConfiguration.class, targetServiceConfig);
for (ServiceConfiguration cfg : configPerService.values()) {
assertTrue(!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE));
}
for (URI child : targetServices) {
this.host.toggleServiceOptions(child,
EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE),
null);
}
verifyMaintStatsAfterSynchronization(targetServices, null);
}
private Map<URI, ServiceStats> verifyMaintStatsAfterSynchronization(List<URI> targetServices,
Map<URI, ServiceStats> statsPerService) {
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
if (statsPerService == null) {
statsPerService = new HashMap<>();
}
final Map<URI, ServiceStats> previousStatsPerService = statsPerService;
this.host.waitFor(
"maintenance not enabled",
() -> {
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, targetServiceStats);
for (Entry<URI, ServiceStats> currentEntry : stats.entrySet()) {
ServiceStats previousStats = previousStatsPerService.get(currentEntry
.getKey());
ServiceStats currentStats = currentEntry.getValue();
ServiceStat previousMaintStat = previousStats == null ? new ServiceStat()
: previousStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
double previousValue = previousMaintStat == null ? 0L
: previousMaintStat.latestValue;
ServiceStat maintStat = currentStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null || maintStat.latestValue <= previousValue) {
return false;
}
}
previousStatsPerService.putAll(stats);
return true;
});
return statsPerService;
}
private Map<String, ExampleServiceState> createExampleServices(URI hostUri) throws Throwable {
URI factoryUri = UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink);
this.host.log("POSTing children to %s", hostUri);
// add some services on one of the peers, so we can verify the get synchronized after they all join
Map<URI, ExampleServiceState> exampleStates = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
}, factoryUri);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
for (ExampleServiceState s : exampleStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
return exampleStatesPerSelfLink;
}
@Test
public void synchronizationWithPeerNodeListAndDuplicates() throws Throwable {
ExampleServiceHost h = null;
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
setUp(this.nodeCount);
// the hosts are started, but not joined. We need to relax the quorum for any updates
// to go through
this.host.setNodeGroupQuorum(1);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
// add the *same* service instance, all *all* peers, so we force synchronization and epoch
// change on an instance that exists everywhere
int dupServiceCount = this.serviceCount;
AtomicInteger counter = new AtomicInteger();
Map<URI, ExampleServiceState> dupStates = new HashMap<>();
for (VerificationHost v : this.host.getInProcessHostMap().values()) {
counter.set(0);
URI factoryUri = UriUtils.buildFactoryUri(v,
ExampleService.class);
dupStates = this.host.doFactoryChildServiceStart(
null,
dupServiceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.documentSelfLink = "duplicateExampleInstance-"
+ counter.incrementAndGet();
s.name = s.documentSelfLink;
o.setBody(s);
}, factoryUri);
}
for (ExampleServiceState s : dupStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
// increment to account for link found on all nodes
this.serviceCount = exampleStatesPerSelfLink.size();
// create peer argument list, all the nodes join.
Collection<URI> peerNodeGroupUris = new ArrayList<>();
StringBuilder peerNodes = new StringBuilder();
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peerNodeGroupUris.add(UriUtils.buildUri(peer, ServiceUriPaths.DEFAULT_NODE_GROUP));
peerNodes.append(peer.getUri().toString()).append(",");
}
CountDownLatch notifications = new CountDownLatch(this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
this.host.subscribeForNodeGroupConvergence(nodeGroup, this.nodeCount + 1,
(o, e) -> {
if (e != null) {
this.host.log("Error in notificaiton: %s", Utils.toString(e));
return;
}
notifications.countDown();
});
}
// now start a new Host and supply the already created peer, then observe the automatic
// join
h = new ExampleServiceHost();
int quorum = this.host.getPeerCount() + 1;
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--port=0",
"--id=" + mainHostId,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + peerNodes.toString()
};
h.initialize(args);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
h.start();
URI mainHostNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
int totalCount = this.nodeCount + 1;
peerNodeGroupUris.add(mainHostNodeGroupUri);
this.host.waitForNodeGroupIsAvailableConvergence();
this.host.waitForNodeGroupConvergence(peerNodeGroupUris, totalCount,
totalCount, true);
this.host.setNodeGroupQuorum(quorum, mainHostNodeGroupUri);
this.host.setNodeGroupQuorum(quorum);
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
int peerNodeCount = h.getInitialPeerHosts().size();
// include self in peers
assertTrue(totalCount >= peerNodeCount + 1);
// Before factory synch is complete, make sure POSTs to existing services fail,
// since they are not marked idempotent.
verifyReplicatedInConflictPost(dupStates);
// now verify all nodes synchronize and see the example service instances that existed on the single
// host
waitForReplicatedFactoryChildServiceConvergence(
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker,
this.serviceCount, 0);
// Send some updates after the full group has formed and verify the updates are seen by services on all nodes
doStateUpdateReplicationTest(Action.PATCH, this.serviceCount, this.updateCount, 0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
exampleStatesPerSelfLink);
URI exampleFactoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(exampleFactoryUri, ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
} finally {
this.host.log("test finished");
if (h != null) {
h.stop();
tmpFolder.delete();
}
}
}
private void verifyReplicatedInConflictPost(Map<URI, ExampleServiceState> dupStates)
throws Throwable {
// Its impossible to guarantee that this runs during factory synch. It might run before,
// it might run during, it might run after. Since we runs 1000s of tests per day, CI
// will let us know if the production code works. Here, we add a small sleep so we increase
// chance we overlap with factory synchronization.
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(
this.host.getPeerHost().getMaintenanceIntervalMicros()));
// Issue a POST for a service we know exists and expect failure, since the example service
// is not marked IDEMPOTENT. We expect CONFLICT error code, but if synchronization is active
// we want to confirm we dont get 500, but the 409 is preserved
TestContext ctx = this.host.testCreate(dupStates.size());
for (ExampleServiceState st : dupStates.values()) {
URI factoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
Operation post = Operation.createPost(factoryUri).setBody(st)
.setCompletion((o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
ctx.failIteration(new IllegalStateException(
"Expected conflict status, got " + o.getStatusCode()));
return;
}
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"Expected failure on duplicate POST"));
});
this.host.send(post);
}
this.host.testWait(ctx);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopOnDemandLoad() throws Throwable {
tearDown();
for (int i = 0; i < this.testIterationCount; i++) {
setUpOnDemandLoad();
int hostStopCount = 2;
doReplicationWithQuorumAfterAbruptNodeStop(hostStopCount);
this.host.log("Done with iteration %d", i);
tearDown();
this.host = null;
}
}
private void doReplicationWithQuorumAfterAbruptNodeStop(int hostStopCount)
throws Throwable {
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop minority number of hosts - quorum is still intact
int i = 0;
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(e.getValue());
if (++i >= hostStopCount) {
break;
}
}
// do some updates with strong quorum enabled
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopMultiLocation()
throws Throwable {
// we need 6 nodes, 3 in each location
this.nodeCount = 6;
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
this.isMultiLocationTest = true;
if (this.host == null) {
// create node group, join nodes and set local majority quorum
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(2);
}
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop hosts in location "L2"
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
VerificationHost h = e.getValue();
if (h.getLocation().equals(VerificationHost.LOCATION2)) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(h);
}
}
// do some updates
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
/**
* This test validates that if a host, joined in a peer node group, stops/fails and another
* host, listening on the same address:port, rejoins, the existing peer members will mark the
* OLD host instance as FAILED, and mark the new instance, with the new ID as HEALTHY
*
* @throws Throwable
*/
@Test
public void nodeRestartWithSameAddressDifferentId() throws Throwable {
int failedNodeCount = 1;
int afterFailureQuorum = this.nodeCount - failedNodeCount;
setUp(this.nodeCount);
setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(5));
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.log("Stopping node");
// relax quorum for convergence check
this.host.setNodeGroupQuorum(afterFailureQuorum);
// we should now have N nodes, that see each other. Stop one of the
// nodes, and verify the other host's node group deletes the entry
List<ServiceHostState> hostStates = stopHostsToSimulateFailure(failedNodeCount);
URI remainingPeerNodeGroup = this.host.getPeerNodeGroupUri();
// wait for convergence of the remaining peers, before restarting. The failed host
// should be marked FAILED, otherwise we will not converge
this.host.waitForNodeGroupConvergence(this.nodeCount - failedNodeCount);
ServiceHostState stoppedHostState = hostStates.get(0);
// start a new HOST, with a new ID, but with the same address:port as the one we stopped
this.host.testStart(1);
VerificationHost newHost = this.host.setUpLocalPeerHost(stoppedHostState.httpPort,
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null);
this.host.testWait();
// re-join the remaining peers
URI newHostNodeGroupService = UriUtils
.buildUri(newHost.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.joinNodeGroup(newHostNodeGroupService, remainingPeerNodeGroup);
this.host.testWait();
// now wait for convergence. If the logic is correct, the old HOST, that listened on the
// same port as the new host, should stay in the FAILED state, but the new host should
// be marked as HEALTHY
this.host.waitForNodeGroupConvergence(this.nodeCount);
}
public void setMaintenanceIntervalMillis(long defaultMaintIntervalMillis) {
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
// set short interval so failure detection and convergence happens quickly
h1.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(defaultMaintIntervalMillis));
}
}
@Test
public void synchronizationRequestQueuing() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
VerificationHost peerHost = this.host.getPeerHost();
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(peerHost, 1, exampleUris, null);
URI instanceUri = exampleUris.get(0);
ExampleServiceState synchState = new ExampleServiceState();
synchState.documentSelfLink = UriUtils.getLastPathSegment(instanceUri);
TestContext ctx = this.host.testCreate(this.updateCount);
for (int i = 0; i < this.updateCount; i++) {
Operation op = Operation.createPost(peerHost, ExampleService.FACTORY_LINK)
.setBody(synchState)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(op);
}
ctx.await();
}
@Test
public void enforceHighQuorumWithNodeConcurrentStop()
throws Throwable {
int hostRestartCount = 2;
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(1);
}
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.host.setNodeGroupQuorum((this.nodeCount + 1) / 2);
// do some replication with strong quorum enabled
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
long now = Utils.getNowMicrosUtc();
validatePerOperationReplicationQuorum(childStates, now);
// expect failure, since we will stop some hosts, break quorum
this.expectFailure = true;
// when quorum is not met the runtime will just queue requests until expiration, so
// we set expiration to something quick. Some requests will make it past queuing
// and will fail because replication quorum is not met
long opTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(500);
setOperationTimeoutMicros(opTimeoutMicros);
int i = 0;
for (URI h : this.host.getInProcessHostMap().keySet()) {
this.expectedFailedHosts.add(h);
if (++i >= hostRestartCount) {
break;
}
}
// stop one host right away
stopHostsToSimulateFailure(1);
// concurrently with the PATCH requests below, stop another host
Runnable r = () -> {
stopHostsToSimulateFailure(hostRestartCount - 1);
// add a small bit of time slop since its feasible a host completed a operation *after* we stopped it,
// the netty handlers are stopped in async (not forced) mode
this.expectedFailureStartTimeMicros = Utils.getNowMicrosUtc()
+ TimeUnit.MILLISECONDS.toMicros(250);
};
this.host.schedule(r, 1, TimeUnit.MILLISECONDS);
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
this.updateCount,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), this.updateCount,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), 1,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
private void validatePerOperationReplicationQuorum(Map<String, ExampleServiceState> childStates,
long now) throws Throwable {
Random r = new Random();
// issue a patch, with per operation quorum set, verify it applied
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(body);
// add an explicit replication count header, using either the "all" value, or an
// explicit node count
if (r.nextBoolean()) {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
} else {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
this.nodeCount + "");
}
this.host.send(patch);
this.host.testWait(ctx);
// Go to each peer, directly to their index, and verify update is present. This is not
// proof the per operation quorum was applied "synchronously", before the response
// was sent, but over many runs, if there is a race or its applied asynchronously,
// we will see failures
for (URI hostBaseUri : this.host.getNodeGroupMap().keySet()) {
URI indexUri = UriUtils.buildUri(hostBaseUri, ServiceUriPaths.CORE_DOCUMENT_INDEX);
indexUri = UriUtils.buildIndexQueryUri(indexUri,
e.getKey(), true, false, ServiceOption.PERSISTENCE);
ExampleServiceState afterState = this.host.getServiceState(null,
ExampleServiceState.class, indexUri);
assertEquals(body.counter, afterState.counter);
}
}
this.host.toggleNegativeTestMode(true);
// verify that if we try to set per operation quorum too high, request will fail
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
(this.nodeCount * 2) + "")
.setCompletion(ctx.getExpectedFailureCompletion())
.setBody(body);
this.host.send(patch);
this.host.testWait(ctx);
break;
}
this.host.toggleNegativeTestMode(false);
}
private void setOperationTimeoutMicros(long opTimeoutMicros) {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setOperationTimeOutMicros(opTimeoutMicros);
}
this.host.setOperationTimeOutMicros(opTimeoutMicros);
}
/**
* This test creates N local service hosts, each with K instances of a replicated service. The
* service will create a query task, also replicated, and self patch itself. The test makes sure
* all K instances, on all N hosts see the self PATCHs AND that the query tasks exist on all
* hosts
*
* @throws Throwable
*/
@Test
public void replicationWithCrossServiceDependencies() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI hostUri = this.host.getPeerServiceUri(null);
URI factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> ownerSelectedServices = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri, ReplicationFactoryTestService.STRICT_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ReplicationTestServiceState.class));
q.query.addBooleanClause(kindClause);
Query nameClause = new Query();
nameClause.setTermPropertyName("stringField")
.setTermMatchValue("*")
.setTermMatchType(MatchType.WILDCARD);
q.query.addBooleanClause(nameClause);
// expect results for strict and regular service instances
int expectedServiceCount = this.serviceCount * 3;
Date exp = this.host.getTestExpiration();
while (exp.after(new Date())) {
// create N direct query tasks. Direct tasks complete in the context of the POST to the
// query task factory
int count = 10;
URI queryFactoryUri = UriUtils.extendUri(hostUri,
ServiceUriPaths.CORE_QUERY_TASKS);
TestContext testContext = this.host.testCreate(count);
Map<String, QueryTask> taskResults = new ConcurrentSkipListMap<>();
for (int i = 0; i < count; i++) {
QueryTask qt = QueryTask.create(q);
qt.taskInfo.isDirect = true;
qt.documentSelfLink = UUID.randomUUID().toString();
Operation startPost = Operation
.createPost(queryFactoryUri)
.setBody(qt)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
qt.results = rsp.results;
qt.documentOwner = rsp.documentOwner;
taskResults.put(rsp.documentSelfLink, qt);
testContext.complete();
});
this.host.send(startPost);
}
testContext.await();
this.host.logThroughput();
boolean converged = true;
for (QueryTask qt : taskResults.values()) {
if (qt.results == null || qt.results.documentLinks == null) {
throw new IllegalStateException("Missing results");
}
if (qt.results.documentLinks.size() != expectedServiceCount) {
this.host.log("%s", Utils.toJsonHtml(qt));
converged = false;
break;
}
}
if (!converged) {
Thread.sleep(250);
continue;
}
break;
}
if (exp.before(new Date())) {
throw new TimeoutException();
}
// Negative tests: Make sure custom error response body is preserved
URI childUri = ownerSelectedServices.keySet().iterator().next();
TestContext testContext = this.host.testCreate(1);
ReplicationTestServiceState badRequestBody = new ReplicationTestServiceState();
this.host
.send(Operation
.createPatch(childUri)
.setBody(badRequestBody)
.setCompletion(
(o, e) -> {
if (e == null) {
testContext.fail(new IllegalStateException(
"Expected failure"));
return;
}
ReplicationTestServiceErrorResponse rsp = o
.getBody(ReplicationTestServiceErrorResponse.class);
if (!ReplicationTestServiceErrorResponse.KIND
.equals(rsp.documentKind)) {
testContext.fail(new IllegalStateException(
"Expected custom response body"));
return;
}
testContext.complete();
}));
testContext.await();
// verify that each owner selected service reports stats from the same node that reports state
Map<URI, ReplicationTestServiceState> latestState = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
Map<String, String> ownerIdPerLink = new HashMap<>();
List<URI> statsUris = new ArrayList<>();
for (ReplicationTestServiceState state : latestState.values()) {
URI statsUri = this.host.getPeerServiceUri(UriUtils.buildUriPath(
state.documentSelfLink, ServiceHost.SERVICE_URI_SUFFIX_STATS));
ownerIdPerLink.put(state.documentSelfLink, state.documentOwner);
statsUris.add(statsUri);
}
Map<URI, ServiceStats> latestStats = this.host.getServiceState(null, ServiceStats.class,
statsUris);
for (ServiceStats perServiceStats : latestStats.values()) {
String serviceLink = UriUtils.getParentPath(perServiceStats.documentSelfLink);
String expectedOwnerId = ownerIdPerLink.get(serviceLink);
if (expectedOwnerId.equals(perServiceStats.documentOwner)) {
continue;
}
throw new IllegalStateException("owner routing issue with stats: "
+ Utils.toJsonHtml(perServiceStats));
}
exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
// verify all factories report same number of children
for (VerificationHost peerHost : this.host.getInProcessHostMap().values()) {
factoryUri = UriUtils.buildUri(peerHost,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
ServiceDocumentQueryResult rsp = this.host.getFactoryState(factoryUri);
if (rsp.documentLinks.size() != latestState.size()) {
this.host.log("Factory %s reporting %d children, expected %d", factoryUri,
rsp.documentLinks.size(), latestState.size());
isConverged = false;
break;
}
}
if (!isConverged) {
Thread.sleep(250);
continue;
}
break;
}
if (new Date().after(exp)) {
throw new TimeoutException("factories did not converge");
}
this.host.log("Inducing synchronization");
// Induce synchronization on stable node group. No changes should be observed since
// all nodes should have identical state
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
// give synchronization a chance to run, its 100% asynchronous so we can't really tell when each
// child is done, but a small delay should be sufficient for 99.9% of test environments, even under
// load
Thread.sleep(2000);
// verify that example states did not change due to the induced synchronization
Map<URI, ReplicationTestServiceState> latestStateAfter = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
for (Entry<URI, ReplicationTestServiceState> afterEntry : latestStateAfter.entrySet()) {
ReplicationTestServiceState beforeState = latestState.get(afterEntry.getKey());
ReplicationTestServiceState afterState = afterEntry.getValue();
assertEquals(beforeState.documentVersion, afterState.documentVersion);
}
verifyOperationJoinAcrossPeers(latestStateAfter);
}
private Map<URI, ReplicationTestServiceState> doReplicatedServiceFactoryPost(int serviceCount,
Consumer<Operation> setBodyCallback, URI factoryUri) throws Throwable,
InterruptedException, TimeoutException {
ServiceDocumentDescription sdd = this.host
.buildDescription(ReplicationTestServiceState.class);
Map<URI, ReplicationTestServiceState> serviceMap = this.host.doFactoryChildServiceStart(
null, serviceCount, ReplicationTestServiceState.class, setBodyCallback, factoryUri);
Date expiration = this.host.getTestExpiration();
boolean isConverged = true;
Map<URI, String> uriToSignature = new HashMap<>();
while (new Date().before(expiration)) {
isConverged = true;
uriToSignature.clear();
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
URI baseUri = e.getKey();
VerificationHost h = e.getValue();
URI u = UriUtils.buildUri(baseUri, factoryUri.getPath());
u = UriUtils.buildExpandLinksQueryUri(u);
ServiceDocumentQueryResult r = this.host.getFactoryState(u);
if (r.documents.size() != serviceCount) {
this.host.log("instance count mismatch, expected %d, got %d, from %s",
serviceCount, r.documents.size(), u);
isConverged = false;
break;
}
for (URI instanceUri : serviceMap.keySet()) {
ReplicationTestServiceState initialState = serviceMap.get(instanceUri);
ReplicationTestServiceState newState = Utils.fromJson(
r.documents.get(instanceUri.getPath()),
ReplicationTestServiceState.class);
if (newState.documentVersion == 0) {
this.host.log("version mismatch, expected %d, got %d, from %s", 0,
newState.documentVersion, instanceUri);
isConverged = false;
break;
}
if (initialState.stringField.equals(newState.stringField)) {
this.host.log("field mismatch, expected %s, got %s, from %s",
initialState.stringField, newState.stringField, instanceUri);
isConverged = false;
break;
}
if (newState.queryTaskLink == null) {
this.host.log("missing query task link from %s", instanceUri);
isConverged = false;
break;
}
// Only instances with OWNER_SELECTION patch string field with self link so bypass this check
if (!newState.documentSelfLink
.contains(ReplicationFactoryTestService.STRICT_SELF_LINK)
&& !newState.documentSelfLink
.contains(ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK)
&& !newState.stringField.equals(newState.documentSelfLink)) {
this.host.log("State not in final state");
isConverged = false;
break;
}
String sig = uriToSignature.get(instanceUri);
if (sig == null) {
sig = Utils.computeSignature(newState, sdd);
uriToSignature.put(instanceUri, sig);
} else {
String newSig = Utils.computeSignature(newState, sdd);
if (!sig.equals(newSig)) {
isConverged = false;
this.host.log("signature mismatch, expected %s, got %s, from %s",
sig, newSig, instanceUri);
}
}
ProcessingStage ps = h.getServiceStage(newState.queryTaskLink);
if (ps == null || ps != ProcessingStage.AVAILABLE) {
this.host.log("missing query task service from %s", newState.queryTaskLink,
instanceUri);
isConverged = false;
break;
}
}
if (isConverged == false) {
break;
}
}
if (isConverged == true) {
break;
}
Thread.sleep(100);
}
if (!isConverged) {
throw new TimeoutException("States did not converge");
}
return serviceMap;
}
@Test
public void replicationWithOutOfOrderPostAndUpdates() throws Throwable {
// This test verifies that if a replica receives
// replication requests of POST and PATCH/PUT
// out-of-order, xenon can still handle it
// by doing retries for failed out-of-order
// updates. To verify this, we setup a node
// group and set quorum to just 1, so that the post
// returns as soon as the owner commits the post,
// so that we increase the chance of out-of-order
// update replication requests.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
state.counter = 1L;
VerificationHost peer = this.host.getPeerHost();
TestContext ctx = this.host.testCreate(this.serviceCount * this.updateCount);
for (int i = 0; i < this.serviceCount; i++) {
Operation post = Operation
.createPost(peer, ExampleService.FACTORY_LINK)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
for (int k = 0; k < this.updateCount; k++) {
ExampleServiceState update = new ExampleServiceState();
state.counter = (long) k;
Operation patch = Operation
.createPatch(peer, rsp.documentSelfLink)
.setBody(update)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
});
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void replication() throws Throwable {
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replicationSsl() throws Throwable {
this.replicationUriScheme = ServiceHost.HttpScheme.HTTPS_ONLY;
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replication1x() throws Throwable {
this.replicationFactor = 1L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication1xExampleFactoryService.SELF_LINK;
doReplication();
}
@Test
public void replication3x() throws Throwable {
this.replicationFactor = 3L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_3X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication3xExampleFactoryService.SELF_LINK;
this.nodeCount = Math.max(5, this.nodeCount);
doReplication();
}
private void doReplication() throws Throwable {
this.isPeerSynchronizationEnabled = false;
CommandLineArgumentParser.parseFromProperties(this);
Date expiration = new Date();
if (this.testDurationSeconds > 0) {
expiration = new Date(expiration.getTime()
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
}
Map<Action, Long> elapsedTimePerAction = new HashMap<>();
Map<Action, Long> countPerAction = new HashMap<>();
long totalOperations = 0;
int iterationCount = 0;
do {
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// for limited replication factor, we will still set the quorum high, and expect
// the limited replication selector to use the minimum between majority of replication
// factor, versus node group membership quorum
this.host.setNodeGroupQuorum(this.nodeCount);
// since we have disabled peer synch, trigger it explicitly so factories become available
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
waitForReplicationFactoryConvergence();
if (this.replicationUriScheme == ServiceHost.HttpScheme.HTTPS_ONLY) {
// confirm nodes are joined using HTTPS group references
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
assertTrue(UriUtils.HTTPS_SCHEME.equals(nodeGroup.getScheme()));
}
}
}
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, countPerAction, elapsedTimePerAction);
totalOperations += this.serviceCount;
if (this.testDurationSeconds == 0) {
// various validation tests, executed just once, ignored in long running test
this.host.doExampleServiceUpdateAndQueryByVersion(this.host.getPeerHostUri(),
this.serviceCount);
verifyReplicatedForcedPostAfterDelete(childStates);
verifyInstantNotFoundFailureOnBadLinks();
verifyReplicatedIdempotentPost(childStates);
verifyDynamicMaintOptionToggle(childStates);
}
totalOperations += this.serviceCount;
if (expiration == null) {
expiration = this.host.getTestExpiration();
}
int expectedVersion = this.updateCount;
if (!this.host.isStressTest()
&& (this.host.getPeerCount() > 16
|| this.serviceCount * this.updateCount > 100)) {
this.host.setStressTest(true);
}
long opCount = this.serviceCount * this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
expectedVersion += this.updateCount;
totalOperations += opCount;
childStates = doStateUpdateReplicationTest(Action.PUT, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += opCount;
Date queryExp = this.host.getTestExpiration();
if (expiration.after(queryExp)) {
queryExp = expiration;
}
while (new Date().before(queryExp)) {
Set<String> links = verifyReplicatedServiceCountWithBroadcastQueries();
if (links.size() < this.serviceCount) {
this.host.log("Found only %d links across nodes, retrying", links.size());
Thread.sleep(500);
continue;
}
break;
}
totalOperations += this.serviceCount;
if (queryExp.before(new Date())) {
throw new TimeoutException();
}
expectedVersion += 1;
doStateUpdateReplicationTest(Action.DELETE, this.serviceCount, 1,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += this.serviceCount;
// compute the binary serialized payload, and the JSON payload size
ExampleServiceState st = childStates.values().iterator().next();
String json = Utils.toJson(st);
int byteCount = KryoSerializers.serializeDocument(st, 4096).position();
int jsonByteCount = json.getBytes(Utils.CHARSET).length;
// estimate total bytes transferred between nodes. The owner receives JSON from the client
// but then uses binary serialization to the N-1 replicas
long totalBytes = jsonByteCount * totalOperations
+ (this.nodeCount - 1) * byteCount * totalOperations;
this.host.log(
"Bytes per json:%d, per binary: %d, Total operations: %d, Total bytes:%d",
jsonByteCount,
byteCount,
totalOperations,
totalBytes);
if (iterationCount++ < 2 && this.testDurationSeconds > 0) {
// ignore data during JVM warm-up, first two iterations
countPerAction.clear();
elapsedTimePerAction.clear();
}
} while (new Date().before(expiration) && this.totalOperationLimit > totalOperations);
logHostStats();
logPerActionThroughput(elapsedTimePerAction, countPerAction);
this.host.doNodeGroupStatsVerification(this.host.getNodeGroupMap());
}
private void logHostStats() {
for (URI u : this.host.getNodeGroupMap().keySet()) {
URI mgmtUri = UriUtils.buildUri(u, ServiceHostManagementService.SELF_LINK);
mgmtUri = UriUtils.buildStatsUri(mgmtUri);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, mgmtUri);
this.host.log("%s: %s", u, Utils.toJsonHtml(stats));
}
}
private void logPerActionThroughput(Map<Action, Long> elapsedTimePerAction,
Map<Action, Long> countPerAction) {
for (Action a : EnumSet.allOf(Action.class)) {
Long count = countPerAction.get(a);
if (count == null) {
continue;
}
Long elapsedMicros = elapsedTimePerAction.get(a);
double thpt = (count * 1.0) / (1.0 * elapsedMicros);
thpt *= 1000000;
this.host.log("Total ops for %s: %d, Throughput (ops/sec): %f", a, count, thpt);
}
}
private void updatePerfDataPerAction(Action a, Long startTime, Long opCount,
Map<Action, Long> countPerAction, Map<Action, Long> elapsedTime) {
if (opCount == null || countPerAction != null) {
countPerAction.merge(a, opCount, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
if (startTime == null || elapsedTime == null) {
return;
}
long delta = Utils.getNowMicrosUtc() - startTime;
elapsedTime.merge(a, delta, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
private void verifyReplicatedIdempotentPost(Map<String, ExampleServiceState> childStates)
throws Throwable {
// verify IDEMPOTENT POST conversion to PUT, with replication
// Since the factory is not idempotent by default, enable the option dynamically
Map<URI, URI> exampleFactoryUris = this.host
.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK);
for (URI factoryUri : exampleFactoryUris.values()) {
this.host.toggleServiceOptions(factoryUri,
EnumSet.of(ServiceOption.IDEMPOTENT_POST), null);
}
TestContext ctx = this.host.testCreate(childStates.size());
for (Entry<String, ExampleServiceState> entry : childStates.entrySet()) {
Operation post = Operation
.createPost(this.host.getPeerServiceUri(ExampleService.FACTORY_LINK))
.setBody(entry.getValue())
.setCompletion(ctx.getCompletion());
this.host.send(post);
}
ctx.await();
}
/**
* Verifies that DELETE actions propagate and commit, and, that forced POST actions succeed
*/
private void verifyReplicatedForcedPostAfterDelete(Map<String, ExampleServiceState> childStates)
throws Throwable {
// delete one of the children, then re-create but with a zero version, using a special
// directive that forces creation
Entry<String, ExampleServiceState> childEntry = childStates.entrySet().iterator().next();
TestContext ctx = this.host.testCreate(1);
Operation delete = Operation
.createDelete(this.host.getPeerServiceUri(childEntry.getKey()))
.setCompletion(ctx.getCompletion());
this.host.send(delete);
ctx.await();
if (!this.host.isRemotePeerTest()) {
this.host.waitFor("services not deleted", () -> {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(childEntry.getKey());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
childEntry.getKey(), h.toString(), stg);
return false;
}
}
return true;
});
}
TestContext postCtx = this.host.testCreate(1);
Operation opPost = Operation
.createPost(this.host.getPeerServiceUri(this.replicationTargetFactoryLink))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE)
.setBody(childEntry.getValue())
.setCompletion((o, e) -> {
if (e != null) {
postCtx.failIteration(e);
} else {
postCtx.completeIteration();
}
});
this.host.send(opPost);
this.host.testWait(postCtx);
}
private void waitForReplicationFactoryConvergence() throws Throwable {
// for code coverage, verify the convenience method on the host also reports available
WaitHandler wh = () -> {
TestContext ctx = this.host.testCreate(1);
boolean[] isReady = new boolean[1];
CompletionHandler ch = (o, e) -> {
if (e != null) {
isReady[0] = false;
} else {
isReady[0] = true;
}
ctx.completeIteration();
};
VerificationHost peerHost = this.host.getPeerHost();
if (peerHost == null) {
NodeGroupUtils.checkServiceAvailability(ch, this.host,
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
} else {
peerHost.checkReplicatedServiceAvailable(ch, this.replicationTargetFactoryLink);
}
ctx.await();
return isReady[0];
};
this.host.waitFor("available check timeout for " + this.replicationTargetFactoryLink, wh);
}
private Set<String> verifyReplicatedServiceCountWithBroadcastQueries()
throws Throwable {
// create a query task, which will execute on a randomly selected node. Since there is no guarantee the node
// selected to execute the query task is the one with all the replicated services, broadcast to all nodes, then
// join the results
URI nodeUri = this.host.getPeerHostUri();
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
URI queryTaskFactoryUri = UriUtils
.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
// send the POST to the forwarding service on one of the nodes, with the broadcast query parameter set
URI forwardingService = UriUtils.buildBroadcastRequestUri(queryTaskFactoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
Set<String> links = new HashSet<>();
TestContext testContext = this.host.testCreate(1);
Operation postQuery = Operation
.createPost(forwardingService)
.setBody(task)
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
NodeGroupBroadcastResponse rsp = o
.getBody(NodeGroupBroadcastResponse.class);
NodeGroupBroadcastResult broadcastResponse = NodeGroupUtils.toBroadcastResult(rsp);
if (broadcastResponse.hasFailure()) {
testContext.fail(new IllegalStateException(
"Failure from query tasks: " + Utils.toJsonHtml(rsp)));
return;
}
// verify broadcast requests should come from all discrete nodes
Set<String> ownerIds = new HashSet<>();
for (PeerNodeResult successResponse : broadcastResponse.successResponses) {
QueryTask qt = successResponse.castBodyTo(QueryTask.class);
this.host.log("Broadcast response from %s %s", qt.documentSelfLink,
qt.documentOwner);
ownerIds.add(qt.documentOwner);
if (qt.results == null) {
this.host.log("Node %s had no results", successResponse.requestUri);
continue;
}
for (String l : qt.results.documentLinks) {
links.add(l);
}
}
testContext.completeIteration();
});
this.host.send(postQuery);
testContext.await();
return links;
}
private void verifyInstantNotFoundFailureOnBadLinks() throws Throwable {
this.host.toggleNegativeTestMode(true);
TestContext testContext = this.host.testCreate(this.serviceCount);
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.complete();
return;
}
// strange, service exists, lets verify
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(o.getUri().getPath());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
o.getUri().getPath(), h.toString(), stg);
}
}
testContext.fail(new Throwable("Expected service to not exist:"
+ o.toString()));
};
// do a negative test: send request to a example child we know does not exist, but disable queuing
// so we get 404 right away
for (int i = 0; i < this.serviceCount; i++) {
URI factoryURI = this.host.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK)
.values().iterator().next();
URI bogusChild = UriUtils.extendUri(factoryURI,
Utils.getNowMicrosUtc() + UUID.randomUUID().toString());
Operation patch = Operation.createPatch(bogusChild)
.setCompletion(c)
.setBody(new ExampleServiceState());
this.host.send(patch);
}
testContext.await();
this.host.toggleNegativeTestMode(false);
}
@Test
public void factorySynchronization() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
factorySynchronizationNoChildren();
factoryDuplicatePost();
}
@Test
public void replicationWithAuthzCacheClear() throws Throwable {
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.setNodeGroupQuorum(this.nodeCount);
VerificationHost groupHost = this.host.getPeerHost();
groupHost.setSystemAuthorizationContext();
// wait for auth related services to be stabilized
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, ResourceGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, RoleService.FACTORY_LINK));
String fooUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"foo@vmware.com");
String barUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"bar@vmware.com");
String bazUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"baz@vmware.com");
// create user, user-group, resource-group, role for foo@vmware.com
// user: /core/authz/users/foo@vmware.com
// user-group: /core/authz/user-groups/foo-user-group
// resource-group: /core/authz/resource-groups/foo-resource-group
// role: /core/authz/roles/foo-role-1
TestContext testContext = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("foo@vmware.com")
.setUserEmail("foo@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setUserGroupName("foo-user-group")
.setResourceGroupName("foo-resource-group")
.setRoleName("foo-role-1")
.setCompletion(testContext.getCompletion())
.start();
testContext.await();
// create another user-group, resource-group, and role for foo@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: /core/authz/role/foo-role-2
TestContext ctxToCreateAnotherRole = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(fooUserLink)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setRoleName("foo-role-2")
.setCompletion(ctxToCreateAnotherRole.getCompletion())
.setupRole();
ctxToCreateAnotherRole.await();
// create user, user-group, resource-group, role for bar@vmware.com
// user: /core/authz/users/bar@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("bar@vmware.com")
.setUserEmail("bar@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBar.getCompletion())
.start();
ctxToCreateBar.await();
// create user, user-group, resource-group, role for baz@vmware.com
// user: /core/authz/users/baz@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBaz = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("baz@vmware.com")
.setUserEmail("baz@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBaz.getCompletion())
.start();
ctxToCreateBaz.await();
AuthorizationContext fooAuthContext = groupHost.assumeIdentity(fooUserLink);
AuthorizationContext barAuthContext = groupHost.assumeIdentity(barUserLink);
AuthorizationContext bazAuthContext = groupHost.assumeIdentity(bazUserLink);
String fooToken = fooAuthContext.getToken();
String barToken = barAuthContext.getToken();
String bazToken = bazAuthContext.getToken();
groupHost.resetSystemAuthorizationContext();
// verify GET will NOT clear cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/users/foo@vmware.com")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/resource-groups/foo-resource-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
// verify deleting role should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user-group should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
// delete the user group associated with the user
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify creating new role should clear the auth cache (using bar@vmware.com)
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
Query q = Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.build();
TestContext ctxToCreateAnotherRoleForBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(barUserLink)
.setResourceGroupName("/core/authz/resource-groups/new-rg")
.setResourceQuery(q)
.setRoleName("bar-role-2")
.setCompletion(ctxToCreateAnotherRoleForBar.getCompletion())
.setupRole();
ctxToCreateAnotherRoleForBar.await();
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
//
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
// Updating the resource group should be able to handle the fact that the user group does not exist
String newResourceGroupLink = "/core/authz/resource-groups/new-rg";
Query updateResourceGroupQuery = Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.query = updateResourceGroupQuery;
this.host.sendAndWaitExpectSuccess(
Operation.createPut(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(resourceGroupState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
// verify patching user should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
UserState userState = new UserState();
userState.userGroupLinks = new HashSet<>();
userState.userGroupLinks.add("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, fooUserLink))
.setBody(userState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user should clear the auth cache
populateAuthCacheInAllPeers(bazAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(groupHost, bazUserLink)));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(bazToken);
// verify patching ResourceGroup should clear the auth cache
// uses "new-rg" resource group that has associated to user bar
TestRequestSender sender = new TestRequestSender(this.host.getPeerHost());
groupHost.setSystemAuthorizationContext();
Operation newResourceGroupGetOp = Operation.createGet(groupHost, newResourceGroupLink);
ResourceGroupState newResourceGroupState = sender.sendAndWait(newResourceGroupGetOp, ResourceGroupState.class);
groupHost.resetSystemAuthorizationContext();
PatchQueryRequest patchBody = PatchQueryRequest.create(newResourceGroupState.query, false);
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(patchBody));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
}
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {
// send a GET request to the ExampleService factory to populate auth cache on each peer.
// since factory is not OWNER_SELECTION service, request goes to the specified node.
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setAuthorizationContext(authContext);
// based on the role created in test, all users have access to ExampleService
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(peer, ExampleService.FACTORY_LINK)));
}
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(authContext.getToken(), true));
}
private void verifyAuthCacheHasClearedInAllPeers(String userToken) {
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(userToken, false));
}
private boolean checkCacheInAllPeers(String token, boolean expectEntries) throws Throwable {
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setSystemAuthorizationContext();
MinimalTestService s = new MinimalTestService();
peer.addPrivilegedService(MinimalTestService.class);
peer.startServiceAndWait(s, UUID.randomUUID().toString(), null);
peer.resetSystemAuthorizationContext();
boolean contextFound = peer.getAuthorizationContext(s, token) != null;
if ((expectEntries && !contextFound) || (!expectEntries && contextFound)) {
return false;
}
}
return true;
}
private void factoryDuplicatePost() throws Throwable, InterruptedException, TimeoutException {
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI factoryUri = this.host
.getPeerServiceUri(ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> states = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
TestContext testContext = serviceHost.testCreate(states.size());
ReplicationTestServiceState initialState = new ReplicationTestServiceState();
for (URI uri : states.keySet()) {
initialState.documentSelfLink = uri.toString().substring(uri.toString()
.lastIndexOf(UriUtils.URI_PATH_CHAR) + 1);
Operation createPost = Operation
.createPost(factoryUri)
.setBody(initialState)
.setCompletion(
(o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
testContext.fail(
new IllegalStateException(
"Incorrect response code received"));
return;
}
testContext.complete();
});
serviceHost.send(createPost);
}
testContext.await();
}
private void factorySynchronizationNoChildren() throws Throwable {
int factoryCount = Math.max(this.serviceCount, 25);
setUp(this.nodeCount);
// start many factories, in each host, so when the nodes join there will be a storm
// of synchronization requests between the nodes + factory instances
TestContext testContext = this.host.testCreate(this.nodeCount * factoryCount);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
for (int i = 0; i < factoryCount; i++) {
Operation startPost = Operation.createPost(
UriUtils.buildUri(h,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, UUID
.randomUUID().toString())))
.setCompletion(testContext.getCompletion());
h.startService(startPost, ExampleService.createFactory());
}
}
testContext.await();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
@Test
public void forwardingAndSelection() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
for (int i = 0; i < this.iterationCount; i++) {
directOwnerSelection();
forwardingToPeerId();
forwardingToKeyHashNode();
broadcast();
}
}
public void broadcast() throws Throwable {
// Do a broadcast on a local, non replicated service. Replicated services can not
// be used with broadcast since they will duplicate the update and potentially route
// to a single node
URI nodeGroup = this.host.getPeerNodeGroupUri();
long c = this.updateCount * this.nodeCount;
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
// we broadcast one update, per service, through one peer. We expect to see
// the same update across all peers, just like with replicated services
nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildBroadcastRequestUri(serviceUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
for (URI baseHostUri : this.host.getNodeGroupMap().keySet()) {
List<URI> uris = new ArrayList<>();
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(baseHostUri, s.documentSelfLink);
uris.add(serviceUri);
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service broadcast failure");
}
}
}
}
public void forwardingToKeyHashNode() throws Throwable {
long c = this.updateCount * this.nodeCount;
Map<String, List<String>> ownersPerServiceLink = new HashMap<>();
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to owner, per service link
// 2) verify the request ended up on the owner the partitioning service predicted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
URI nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildForwardRequestUri(serviceUri,
null,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
this.host.logThroughput();
AtomicInteger assignedLinks = new AtomicInteger();
TestContext testContextForPost = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
// make sure the key is the path to the service. The initial state self link is not a
// path ...
String key = UriUtils.normalizeUriPath(s.documentSelfLink);
s.documentSelfLink = key;
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion((o, e) -> {
if (e != null) {
testContextForPost.fail(e);
return;
}
synchronized (ownersPerServiceLink) {
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
List<String> links = ownersPerServiceLink.get(rsp.ownerNodeId);
if (links == null) {
links = new ArrayList<>();
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
links.add(key);
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
assignedLinks.incrementAndGet();
testContextForPost.complete();
});
this.host.send(post);
}
testContextForPost.await();
assertTrue(assignedLinks.get() == initialStates.size());
// verify the services on the node that should be owner, has modified state
for (Entry<String, List<String>> e : ownersPerServiceLink.entrySet()) {
String nodeId = e.getKey();
List<String> links = e.getValue();
NodeState ns = this.host.getNodeStateMap().get(nodeId);
List<URI> uris = new ArrayList<>();
// make a list of URIs to the services assigned to this peer node
for (String l : links) {
uris.add(UriUtils.buildUri(ns.groupReference, l));
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service forwarding failure");
} else {
}
}
}
}
public void forwardingToPeerId() throws Throwable {
long c = this.updateCount * this.nodeCount;
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to a specific peer id, per service link
// 2) verify the request ended up on the peer we targeted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
s = Utils.clone(s);
// set the owner to be the target node. we will use this to verify it matches
// the id in the state, which is set through a forwarded PATCH
s.documentOwner = peer.getId();
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
VerificationHost peerEntryPoint = this.host.getPeerHost();
// add a custom header and make sure the service sees it in its handler, in the request
// headers, and we see a service response header in our response
String headerName = MinimalTestService.TEST_HEADER_NAME.toLowerCase();
UUID id = UUID.randomUUID();
String headerRequestValue = "request-" + id;
String headerResponseValue = "response-" + id;
TestContext testContextForPut = this.host.testCreate(initialStates.size() * this.nodeCount);
for (ServiceDocument s : initialStates) {
// send a PATCH the id for each document, to each peer. If it routes to the proper peer
// the initial state.documentOwner, will match the state.id
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
// For testing coverage, force the use of the same forwarding service instance.
// We make all request flow from one peer to others, testing both loopback p2p
// and true forwarding. Otherwise, the forwarding happens by directly contacting
// peer we want to land on!
URI localForwardingUri = UriUtils.buildUri(peerEntryPoint.getUri(),
s.documentSelfLink);
// add a query to make sure it does not affect forwarding
localForwardingUri = UriUtils.extendUriWithQuery(localForwardingUri, "k", "v",
"k1", "v1", "k2", "v2");
URI u = UriUtils.buildForwardToPeerUri(localForwardingUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR, EnumSet.noneOf(ServiceOption.class));
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = peer.getId();
this.host.send(Operation.createPut(u)
.addRequestHeader(headerName, headerRequestValue)
.setCompletion(
(o, e) -> {
if (e != null) {
testContextForPut.fail(e);
return;
}
String value = o.getResponseHeader(headerName);
if (value == null || !value.equals(headerResponseValue)) {
testContextForPut.fail(new IllegalArgumentException(
"response header not found"));
return;
}
testContextForPut.complete();
})
.setBody(body));
}
}
testContextForPut.await();
this.host.logThroughput();
TestContext ctx = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation get = Operation.createGet(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
MinimalTestServiceState rsp = o
.getBody(MinimalTestServiceState.class);
if (!rsp.id.equals(rsp.documentOwner)) {
ctx.fail(
new IllegalStateException("Expected: "
+ rsp.documentOwner + " was: " + rsp.id));
} else {
ctx.complete();
}
});
this.host.send(get);
}
}
ctx.await();
// Do a negative test: Send a request that will induce failure in the service handler and
// make sure we receive back failure, with a ServiceErrorResponse body
this.host.toggleDebuggingMode(true);
TestContext testCxtForPut = this.host.testCreate(this.host.getInProcessHostMap().size());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
ServiceDocument s = initialStates.get(0);
URI serviceUri = UriUtils.buildUri(peerEntryPoint.getUri(), s.documentSelfLink);
URI u = UriUtils.buildForwardToPeerUri(serviceUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
null);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
// setting id to null will cause validation failure.
body.id = null;
this.host.send(Operation.createPut(u)
.setCompletion(
(o, e) -> {
if (e == null) {
testCxtForPut.fail(new IllegalStateException(
"expected failure"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (rsp.message == null || rsp.message.isEmpty()) {
testCxtForPut.fail(new IllegalStateException(
"expected error response message"));
return;
}
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)
|| 0 != Double.compare(Math.PI, rsp.customErrorField)) {
testCxtForPut.fail(new IllegalStateException(
"expected custom error fields"));
return;
}
testCxtForPut.complete();
})
.setBody(body));
}
testCxtForPut.await();
this.host.toggleDebuggingMode(false);
}
private void directOwnerSelection() throws Throwable {
Map<URI, Map<String, Long>> keyToNodeAssignmentsPerNode = new HashMap<>();
List<String> keys = new ArrayList<>();
long c = this.updateCount * this.nodeCount;
// generate N keys once, then ask each node to assign to its peers. Each node should come up
// with the same distribution
for (int i = 0; i < c; i++) {
keys.add(Utils.getNowMicrosUtc() + "");
}
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
keyToNodeAssignmentsPerNode.put(nodeGroup, new HashMap<>());
}
this.host.waitForNodeGroupConvergence(this.nodeCount);
TestContext testContext = this.host.testCreate(c * this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
for (String key : keys) {
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation
.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion(
(o, e) -> {
try {
synchronized (keyToNodeAssignmentsPerNode) {
SelectOwnerResponse rsp = o
.getBody(SelectOwnerResponse.class);
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode
.get(nodeGroup);
Long l = assignmentsPerNode.get(rsp.ownerNodeId);
if (l == null) {
l = 0L;
}
assignmentsPerNode.put(rsp.ownerNodeId, l + 1);
testContext.complete();
}
} catch (Throwable ex) {
testContext.fail(ex);
}
});
this.host.send(post);
}
}
testContext.await();
this.host.logThroughput();
Map<String, Long> countPerNode = null;
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode.get(nodeGroup);
if (countPerNode == null) {
countPerNode = assignmentsPerNode;
}
this.host.log("Node group %s assignments: %s", nodeGroup, assignmentsPerNode);
for (Entry<String, Long> e : assignmentsPerNode.entrySet()) {
// we assume that with random keys, and random node ids, each node will get at least
// one key.
assertTrue(e.getValue() > 0);
Long count = countPerNode.get(e.getKey());
if (count == null) {
continue;
}
if (!count.equals(e.getValue())) {
this.host.logNodeGroupState();
throw new IllegalStateException(
"Node id got assigned the same key different number of times, on one of the nodes");
}
}
}
}
@Test
public void replicationFullQuorumMissingServiceOnPeer() throws Throwable {
// This test verifies the following scenario:
// A new node joins an existing node-group with
// services already created. Synchronization is
// still in-progress and a write request arrives.
// If the quorum is configured to FULL, the write
// request will fail on the new node with not-found
// error, since synchronization hasn't completed.
// The test verifies that when this happens, the
// owner node will try to synchronize on-demand
// and retry the original update reqeust.
// Artificially setting the replica not found timeout to
// a lower-value, to reduce the wait time before owner
// retries
System.setProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS,
Long.toString(TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS)));
this.host = VerificationHost.create(0);
this.host.setPeerSynchronizationEnabled(false);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.start();
// Setup one host and create some example
// services on it.
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(this.host, this.serviceCount, exampleUris, null);
// Add a second host with synchronization disabled,
// Join it to the existing host.
VerificationHost host2 = new VerificationHost();
try {
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--id=" + mainHostId,
"--port=0",
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + this.host.getUri()
};
host2.initialize(args);
host2.setPeerSynchronizationEnabled(false);
host2.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
host2.start();
this.host.addPeerNode(host2);
// Wait for node-group to converge
List<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.buildUri(this.host, ServiceUriPaths.DEFAULT_NODE_GROUP));
nodeGroupUris.add(UriUtils.buildUri(host2, ServiceUriPaths.DEFAULT_NODE_GROUP));
this.host.waitForNodeGroupConvergence(nodeGroupUris, 2, 2, true);
// Set the quorum to full.
this.host.setNodeGroupQuorum(2, nodeGroupUris.get(0));
host2.setNodeGroupQuorum(2);
// Filter the created examples to only those
// that are owned by host-1.
List<URI> host1Examples = exampleUris.stream()
.filter(e -> this.host.isOwner(e.getPath(), ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.collect(Collectors.toList());
// Start patching all filtered examples. Because
// synchronization is disabled each of these
// example services will not exist on the new
// node that we added resulting in a non_found
// error. However, the owner will retry this
// after on-demand synchronization and hence
// patches should succeed.
ExampleServiceState state = new ExampleServiceState();
state.counter = 1L;
if (host1Examples.size() > 0) {
this.host.log(Level.INFO, "Starting patches");
TestContext ctx = this.host.testCreate(host1Examples.size());
for (URI exampleUri : host1Examples) {
Operation patch = Operation
.createPatch(exampleUri)
.setBody(state)
.setReferer("localhost")
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
ctx.await();
}
} finally {
host2.tearDown();
}
}
@Test
public void replicationWithAuthAndNodeRestart() throws Throwable {
AuthorizationHelper authHelper;
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
authHelper = new AuthorizationHelper(this.host);
// relax quorum to allow for divergent writes, on independent nodes (not yet joined)
this.host.setSystemAuthorizationContext();
// Create the same users and roles on every peer independently
Map<ServiceHost, Collection<String>> roleLinksByHost = new HashMap<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String email = "jane@doe.com";
authHelper.createUserService(h, email);
authHelper.createRoles(h, email);
}
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = getRolesByHost(roleLinksByHost);
// Join nodes to force synchronization and convergence
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> newRoleStateByHost = getRolesByHost(roleLinksByHost);
// Verify that every host independently advances their version & epoch
for (ServiceHost h : roleStateByHost.keySet()) {
Map<URI, RoleState> roleState = roleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState oldRole = roleState.get(u);
RoleState newRole = newRoleStateByHost.get(h).get(u);
assertTrue("version should have advanced",
newRole.documentVersion > oldRole.documentVersion);
assertTrue("epoch should have advanced",
newRole.documentEpoch > oldRole.documentEpoch);
}
}
// Verify that every host converged to the same version, epoch, and owner
Map<String, Long> versions = new HashMap<>();
Map<String, Long> epochs = new HashMap<>();
Map<String, String> owners = new HashMap<>();
for (ServiceHost h : newRoleStateByHost.keySet()) {
Map<URI, RoleState> roleState = newRoleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState newRole = roleState.get(u);
if (versions.containsKey(newRole.documentSelfLink)) {
assertTrue(versions.get(newRole.documentSelfLink) == newRole.documentVersion);
} else {
versions.put(newRole.documentSelfLink, newRole.documentVersion);
}
if (epochs.containsKey(newRole.documentSelfLink)) {
assertTrue(Objects.equals(epochs.get(newRole.documentSelfLink),
newRole.documentEpoch));
} else {
epochs.put(newRole.documentSelfLink, newRole.documentEpoch);
}
if (owners.containsKey(newRole.documentSelfLink)) {
assertEquals(owners.get(newRole.documentSelfLink), newRole.documentOwner);
} else {
owners.put(newRole.documentSelfLink, newRole.documentOwner);
}
}
}
// create some example tasks, which delete example services. We dont have any
// examples services created, which is good, since we just want these tasks to
// go to finished state, then verify, after node restart, they all start
Set<String> exampleTaskLinks = new ConcurrentSkipListSet<>();
createReplicatedExampleTasks(exampleTaskLinks, null);
Set<String> exampleLinks = new ConcurrentSkipListSet<>();
verifyReplicatedAuthorizedPost(exampleLinks);
// verify restart, with authorization.
// stop one host
VerificationHost hostToStop = this.host.getInProcessHostMap().values().iterator().next();
stopAndRestartHost(exampleLinks, exampleTaskLinks, hostToStop);
}
private void createReplicatedExampleTasks(Set<String> exampleTaskLinks, String name)
throws Throwable {
URI factoryUri = UriUtils.buildFactoryUri(this.host.getPeerHost(),
ExampleTaskService.class);
this.host.setSystemAuthorizationContext();
// Sample body that this user is authorized to create
ExampleTaskServiceState exampleServiceState = new ExampleTaskServiceState();
if (name != null) {
exampleServiceState.customQueryClause = Query.Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, name).build();
}
this.host.log("creating example *task* instances");
TestContext testContext = this.host.testCreate(this.serviceCount);
for (int i = 0; i < this.serviceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
ExampleTaskServiceState rsp = o.getBody(ExampleTaskServiceState.class);
synchronized (exampleTaskLinks) {
exampleTaskLinks.add(rsp.documentSelfLink);
}
testContext.complete();
};
this.host.send(Operation
.createPost(factoryUri)
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
// ensure all tasks are in finished state
this.host.waitFor("Example tasks did not finish", () -> {
ServiceDocumentQueryResult rsp = this.host.getExpandedFactoryState(factoryUri);
for (Object o : rsp.documents.values()) {
ExampleTaskServiceState doc = Utils.fromJson(o, ExampleTaskServiceState.class);
if (TaskState.isFailed(doc.taskInfo)) {
this.host.log("task %s failed: %s", doc.documentSelfLink, doc.failureMessage);
throw new IllegalStateException("task failed");
}
if (!TaskState.isFinished(doc.taskInfo)) {
return false;
}
}
return true;
});
}
private void verifyReplicatedAuthorizedPost(Set<String> exampleLinks)
throws Throwable {
Collection<VerificationHost> hosts = this.host.getInProcessHostMap().values();
RoundRobinIterator<VerificationHost> it = new RoundRobinIterator<>(hosts);
int exampleServiceCount = this.serviceCount;
String userLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "jane@doe.com");
// Verify we can assert identity and make a request to every host
this.host.assumeIdentity(userLink);
// Sample body that this user is authorized to create
ExampleServiceState exampleServiceState = new ExampleServiceState();
exampleServiceState.name = "jane";
this.host.log("creating example instances");
TestContext testContext = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
try {
// Verify the user is set as principal
ExampleServiceState state = o.getBody(ExampleServiceState.class);
assertEquals(state.documentAuthPrincipalLink,
userLink);
exampleLinks.add(state.documentSelfLink);
testContext.complete();
} catch (Throwable e2) {
testContext.fail(e2);
}
};
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
this.host.toggleNegativeTestMode(true);
// Sample body that this user is NOT authorized to create
ExampleServiceState invalidExampleServiceState = new ExampleServiceState();
invalidExampleServiceState.name = "somebody other than jane";
this.host.log("issuing non authorized request");
TestContext testCtx = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(invalidExampleServiceState)
.setCompletion((o, e) -> {
if (e != null) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, o.getStatusCode());
testCtx.complete();
return;
}
testCtx.fail(new IllegalStateException("expected failure"));
}));
}
testCtx.await();
this.host.toggleNegativeTestMode(false);
}
private void stopAndRestartHost(Set<String> exampleLinks, Set<String> exampleTaskLinks,
VerificationHost hostToStop)
throws Throwable, InterruptedException {
// relax quorum
this.host.setNodeGroupQuorum(this.nodeCount - 1);
// expire node that went away quickly to avoid alot of log spam from gossip failures
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(1);
this.host.setNodeGroupConfig(cfg);
this.host.stopHostAndPreserveState(hostToStop);
this.host.waitForNodeGroupConvergence(2, 2);
VerificationHost existingHost = this.host.getInProcessHostMap().values().iterator().next();
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleTaskService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// create some additional tasks on the remaining two hosts, but make sure they don't delete
// any example service instances, by specifying a name value we know will not match anything
createReplicatedExampleTasks(exampleTaskLinks, UUID.randomUUID().toString());
// delete some of the task links, to test synchronization of deleted entries on the restarted
// host
Set<String> deletedExampleLinks = deleteSomeServices(exampleLinks);
// increase quorum on existing nodes, so they wait for new node
this.host.setNodeGroupQuorum(this.nodeCount);
hostToStop.setPort(0);
hostToStop.setSecurePort(0);
if (!VerificationHost.restartStatefulHost(hostToStop)) {
this.host.log("Failed restart of host, aborting");
return;
}
// restart host, rejoin it
URI nodeGroupU = UriUtils.buildUri(hostToStop, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI eNodeGroupU = UriUtils.buildUri(existingHost, ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.setSystemAuthorizationContext();
this.host.joinNodeGroup(nodeGroupU, eNodeGroupU, this.nodeCount);
this.host.testWait();
this.host.addPeerNode(hostToStop);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// set quorum on new node as well
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.resetAuthorizationContext();
this.host.waitFor("Task services not started in restarted host:" + exampleTaskLinks, () -> {
return checkChildServicesIfStarted(exampleTaskLinks, hostToStop) == 0;
});
// verify all services, not previously deleted, are restarted
this.host.waitFor("Services not started in restarted host:" + exampleLinks, () -> {
return checkChildServicesIfStarted(exampleLinks, hostToStop) == 0;
});
int deletedCount = deletedExampleLinks.size();
this.host.waitFor("Deleted services still present in restarted host", () -> {
return checkChildServicesIfStarted(deletedExampleLinks, hostToStop) == deletedCount;
});
}
private Set<String> deleteSomeServices(Set<String> exampleLinks)
throws Throwable {
int deleteCount = exampleLinks.size() / 3;
Iterator<String> itLinks = exampleLinks.iterator();
Set<String> deletedExampleLinks = new HashSet<>();
TestContext testContext = this.host.testCreate(deleteCount);
for (int i = 0; i < deleteCount; i++) {
String link = itLinks.next();
deletedExampleLinks.add(link);
exampleLinks.remove(link);
Operation delete = Operation.createDelete(this.host.getPeerServiceUri(link))
.setCompletion(testContext.getCompletion());
this.host.send(delete);
}
testContext.await();
this.host.log("Deleted links: %s", deletedExampleLinks);
return deletedExampleLinks;
}
private int checkChildServicesIfStarted(Set<String> exampleTaskLinks,
VerificationHost host) {
this.host.setSystemAuthorizationContext();
int notStartedCount = 0;
for (String s : exampleTaskLinks) {
ProcessingStage st = host.getServiceStage(s);
if (st == null) {
notStartedCount++;
}
}
this.host.resetAuthorizationContext();
if (notStartedCount > 0) {
this.host.log("%d services not started on %s (%s)", notStartedCount,
host.getPublicUri(), host.getId());
}
return notStartedCount;
}
private Map<ServiceHost, Map<URI, RoleState>> getRolesByHost(
Map<ServiceHost, Collection<String>> roleLinksByHost) throws Throwable {
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = new HashMap<>();
for (ServiceHost h : roleLinksByHost.keySet()) {
Collection<String> roleLinks = roleLinksByHost.get(h);
Collection<URI> roleURIs = new ArrayList<>();
for (String link : roleLinks) {
roleURIs.add(UriUtils.buildUri(h, link));
}
Map<URI, RoleState> serviceState = this.host.getServiceState(null, RoleState.class,
roleURIs);
roleStateByHost.put(h, serviceState);
}
return roleStateByHost;
}
private void verifyOperationJoinAcrossPeers(Map<URI, ReplicationTestServiceState> childStates)
throws Throwable {
// do a OperationJoin across N nodes, making sure join works when forwarding is involved
List<Operation> joinedOps = new ArrayList<>();
for (ReplicationTestServiceState st : childStates.values()) {
Operation get = Operation.createGet(
this.host.getPeerServiceUri(st.documentSelfLink)).setReferer(
this.host.getReferer());
joinedOps.add(get);
}
TestContext testContext = this.host.testCreate(1);
OperationJoin
.create(joinedOps)
.setCompletion(
(ops, exc) -> {
if (exc != null) {
testContext.fail(exc.values().iterator().next());
return;
}
for (Operation o : ops.values()) {
ReplicationTestServiceState state = o.getBody(
ReplicationTestServiceState.class);
if (state.stringField == null) {
testContext.fail(new IllegalStateException());
return;
}
}
testContext.complete();
})
.sendWith(this.host.getPeerHost());
testContext.await();
}
public Map<String, Set<String>> computeOwnerIdsPerLink(VerificationHost joinedHost,
Collection<String> links)
throws Throwable {
TestContext testContext = this.host.testCreate(links.size());
Map<String, Set<String>> expectedOwnersPerLink = new ConcurrentSkipListMap<>();
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
Set<String> eligibleNodeIds = new HashSet<>();
for (NodeState ns : rsp.selectedNodes) {
eligibleNodeIds.add(ns.id);
}
expectedOwnersPerLink.put(rsp.key, eligibleNodeIds);
testContext.complete();
};
for (String link : links) {
Operation selectOp = Operation.createGet(null)
.setCompletion(c)
.setExpiration(this.host.getOperationTimeoutMicros() + Utils.getNowMicrosUtc());
joinedHost.selectOwner(this.replicationNodeSelector, link, selectOp);
}
testContext.await();
return expectedOwnersPerLink;
}
public <T extends ServiceDocument> void verifyDocumentOwnerAndEpoch(Map<String, T> childStates,
VerificationHost joinedHost,
List<URI> joinedHostUris,
int minExpectedEpochRetries,
int maxExpectedEpochRetries, int expectedOwnerChanges)
throws Throwable, InterruptedException, TimeoutException {
Map<URI, NodeGroupState> joinedHostNodeGroupStates = this.host.getServiceState(null,
NodeGroupState.class, joinedHostUris);
Set<String> joinedHostOwnerIds = new HashSet<>();
for (NodeGroupState st : joinedHostNodeGroupStates.values()) {
joinedHostOwnerIds.add(st.documentOwner);
}
this.host.waitFor("ownership did not converge", () -> {
Map<String, Set<String>> ownerIdsPerLink = computeOwnerIdsPerLink(joinedHost,
childStates.keySet());
boolean isConverged = true;
Map<String, Set<Long>> epochsPerLink = new HashMap<>();
List<URI> nodeSelectorStatsUris = new ArrayList<>();
for (URI baseNodeUri : joinedHostUris) {
nodeSelectorStatsUris.add(UriUtils.buildUri(baseNodeUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
URI factoryUri = UriUtils.buildUri(
baseNodeUri, this.replicationTargetFactoryLink);
ServiceDocumentQueryResult factoryRsp = this.host
.getFactoryState(factoryUri);
if (factoryRsp.documentLinks == null
|| factoryRsp.documentLinks.size() != childStates.size()) {
isConverged = false;
// services not all started in new nodes yet;
this.host.log("Node %s does not have all services: %s", baseNodeUri,
Utils.toJsonHtml(factoryRsp));
break;
}
List<URI> childUris = new ArrayList<>();
for (String link : childStates.keySet()) {
childUris.add(UriUtils.buildUri(baseNodeUri, link));
}
// retrieve the document state directly from each service
Map<URI, ServiceDocument> childDocs = this.host.getServiceState(null,
ServiceDocument.class, childUris);
List<URI> childStatUris = new ArrayList<>();
for (ServiceDocument state : childDocs.values()) {
if (state.documentOwner == null) {
this.host.log("Owner not set in service on new node: %s",
Utils.toJsonHtml(state));
isConverged = false;
break;
}
URI statUri = UriUtils.buildUri(baseNodeUri, state.documentSelfLink,
ServiceHost.SERVICE_URI_SUFFIX_STATS);
childStatUris.add(statUri);
Set<Long> epochs = epochsPerLink.get(state.documentEpoch);
if (epochs == null) {
epochs = new HashSet<>();
epochsPerLink.put(state.documentSelfLink, epochs);
}
epochs.add(state.documentEpoch);
Set<String> eligibleNodeIds = ownerIdsPerLink.get(state.documentSelfLink);
if (!joinedHostOwnerIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not expected: %s, valid ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
if (eligibleNodeIds != null && !eligibleNodeIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not eligible: %s, eligible ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
}
int nodeGroupMaintCount = 0;
int docOwnerToggleOffCount = 0;
int docOwnerToggleCount = 0;
// verify stats were reported by owner node, not a random peer
Map<URI, ServiceStats> allChildStats = this.host.getServiceState(null,
ServiceStats.class, childStatUris);
for (ServiceStats childStats : allChildStats.values()) {
String parentLink = UriUtils.getParentPath(childStats.documentSelfLink);
Set<String> eligibleNodes = ownerIdsPerLink.get(parentLink);
if (!eligibleNodes.contains(childStats.documentOwner)) {
this.host.log("Stats for %s owner not expected. Is %s, should be %s",
parentLink, childStats.documentOwner,
ownerIdsPerLink.get(parentLink));
isConverged = false;
break;
}
ServiceStat maintStat = childStats.entries
.get(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (maintStat != null) {
nodeGroupMaintCount++;
}
ServiceStat docOwnerToggleOffStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
if (docOwnerToggleOffStat != null) {
docOwnerToggleOffCount++;
}
ServiceStat docOwnerToggleStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
if (docOwnerToggleStat != null) {
docOwnerToggleCount++;
}
}
this.host.log("Node group change maintenance observed: %d", nodeGroupMaintCount);
if (nodeGroupMaintCount < expectedOwnerChanges) {
isConverged = false;
}
this.host.log("Toggled off doc owner count: %d, toggle on count: %d",
docOwnerToggleOffCount, docOwnerToggleCount);
if (docOwnerToggleCount < childStates.size()) {
isConverged = false;
}
// verify epochs
for (Set<Long> epochs : epochsPerLink.values()) {
if (epochs.size() > 1) {
this.host.log("Documents have different epochs:%s", epochs.toString());
isConverged = false;
}
}
if (!isConverged) {
break;
}
}
return isConverged;
});
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild) throws Throwable {
return doStateUpdateReplicationTest(action, childCount, updateCount, expectedVersion,
updateBodySetter, convergenceChecker, initialStatesPerChild, null, null);
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild,
Map<Action, Long> countsPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
int testCount = childCount * updateCount;
String testName = "Replication with " + action;
TestContext testContext = this.host.testCreate(testCount);
testContext.setTestName(testName).logBefore();
if (!this.expectFailure) {
// Before we do the replication test, wait for factory availability.
for (URI fu : this.host.getNodeGroupToFactoryMap(this.replicationTargetFactoryLink)
.values()) {
// confirm that /factory/available returns 200 across all nodes
waitForReplicatedFactoryServiceAvailable(fu, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
}
long before = Utils.getNowMicrosUtc();
AtomicInteger failedCount = new AtomicInteger();
// issue an update to each child service and verify it was reflected
// among
// peers
for (T initState : initialStatesPerChild.values()) {
// change a field in the initial state of each service but keep it
// the same across all updates so potential re ordering of the
// updates does not cause spurious test breaks
updateBodySetter.apply(initState);
for (int i = 0; i < updateCount; i++) {
long sentTime = 0;
if (this.expectFailure) {
sentTime = Utils.getNowMicrosUtc();
}
URI factoryOnRandomPeerUri = this.host
.getPeerServiceUri(this.replicationTargetFactoryLink);
long finalSentTime = sentTime;
this.host
.send(Operation
.createPatch(UriUtils.buildUri(factoryOnRandomPeerUri,
initState.documentSelfLink))
.setAction(action)
.forceRemote()
.setBodyNoCloning(initState)
.setCompletion(
(o, e) -> {
if (e != null) {
if (this.expectFailure) {
failedCount.incrementAndGet();
testContext.complete();
return;
}
testContext.fail(e);
return;
}
if (this.expectFailure
&& this.expectedFailureStartTimeMicros > 0
&& finalSentTime > this.expectedFailureStartTimeMicros) {
testContext.fail(new IllegalStateException(
"Request should have failed: %s"
+ o.toString()
+ " sent at " + finalSentTime));
return;
}
testContext.complete();
}));
}
}
testContext.await();
testContext.logAfter();
updatePerfDataPerAction(action, before, (long) (childCount * updateCount), countsPerAction,
elapsedTimePerAction);
if (this.expectFailure) {
this.host.log("Failed count: %d", failedCount.get());
if (failedCount.get() == 0) {
throw new IllegalStateException(
"Possible false negative but expected at least one failure");
}
return initialStatesPerChild;
}
// All updates sent to all children within one host, now wait for
// convergence
if (action != Action.DELETE) {
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
childCount,
expectedVersion);
}
// for DELETE replication, we expect the child services to be stopped
// across hosts and their state marked "deleted". So confirm no children
// are available
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
0,
expectedVersion);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction)
throws Throwable {
return doExampleFactoryPostReplicationTest(childCount, null,
countPerAction, elapsedTimePerAction);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
EnumSet<TestProperty> props,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
this.host.toggleNegativeTestMode(true);
}
String factoryPath = this.replicationTargetFactoryLink;
Map<String, ExampleServiceState> serviceStates = new HashMap<>();
long before = Utils.getNowMicrosUtc();
TestContext testContext = this.host.testCreate(childCount);
testContext.setTestName("POST replication");
testContext.logBefore();
for (int i = 0; i < childCount; i++) {
URI factoryOnRandomPeerUri = this.host.getPeerServiceUri(factoryPath);
Operation post = Operation
.createPost(factoryOnRandomPeerUri)
.setCompletion(testContext.getCompletion());
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = "" + post.getId();
initialState.counter = Long.MIN_VALUE;
// set the self link as a hint so the child service URI is
// predefined instead of random
initialState.documentSelfLink = "" + post.getId();
// factory service is started on all hosts. Now issue a POST to one,
// to create a child service with some initial state.
post.setReferer(this.host.getReferer());
this.host.sendRequest(post.setBody(initialState));
// initial state is cloned and sent, now we can change self link per
// child to reflect its runtime URI, which will
// contain the factory service path
initialState.documentSelfLink = UriUtils.buildUriPath(factoryPath,
initialState.documentSelfLink);
serviceStates.put(initialState.documentSelfLink, initialState);
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
// do not wait for convergence of the child services. Instead
// proceed to the next test which is probably stopping hosts
// abruptly
return serviceStates;
}
testContext.await();
updatePerfDataPerAction(Action.POST, before, (long) this.serviceCount, countPerAction,
elapsedTimePerAction);
testContext.logAfter();
return waitForReplicatedFactoryChildServiceConvergence(serviceStates,
this.exampleStateConvergenceChecker,
childCount,
0L);
}
private void updateExampleServiceOptions(
Map<String, ExampleServiceState> statesPerSelfLink) throws Throwable {
if (this.postCreationServiceOptions == null || this.postCreationServiceOptions.isEmpty()) {
return;
}
TestContext testContext = this.host.testCreate(statesPerSelfLink.size());
URI nodeGroup = this.host.getNodeGroupMap().values().iterator().next();
for (String link : statesPerSelfLink.keySet()) {
URI bUri = UriUtils.buildBroadcastRequestUri(
UriUtils.buildUri(nodeGroup, link, ServiceHost.SERVICE_URI_SUFFIX_CONFIG),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
ServiceConfigUpdateRequest cfgBody = ServiceConfigUpdateRequest.create();
cfgBody.addOptions = this.postCreationServiceOptions;
this.host.send(Operation.createPatch(bUri)
.setBody(cfgBody)
.setCompletion(testContext.getCompletion()));
}
testContext.await();
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
return waitForReplicatedFactoryChildServiceConvergence(
getFactoriesPerNodeGroup(this.replicationTargetFactoryLink),
serviceStates,
stateChecker,
expectedChildCount,
expectedVersion);
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<URI, URI> factories,
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
// now poll all hosts until they converge: They all have a child service
// with the expected URI and it has the same state
Map<String, T> updatedStatesPerSelfLink = new HashMap<>();
Date expiration = new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(this.host.getTimeoutSeconds()));
do {
URI node = factories.keySet().iterator().next();
AtomicInteger getFailureCount = new AtomicInteger();
if (expectedChildCount != 0) {
// issue direct GETs to the services, we do not trust the factory
for (String link : serviceStates.keySet()) {
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(node, link))
.setReferer(this.host.getReferer())
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(5))
.setCompletion(
(o, e) -> {
if (e != null) {
getFailureCount.incrementAndGet();
}
ctx.completeIteration();
});
this.host.sendRequest(get);
this.host.testWait(ctx);
}
}
if (getFailureCount.get() > 0) {
this.host.log("Child services not propagated yet. Failure count: %d",
getFailureCount.get());
Thread.sleep(500);
continue;
}
TestContext testContext = this.host.testCreate(factories.size());
Map<URI, ServiceDocumentQueryResult> childServicesPerNode = new HashMap<>();
for (URI remoteFactory : factories.values()) {
URI factoryUriWithExpand = UriUtils.buildExpandLinksQueryUri(remoteFactory);
Operation get = Operation.createGet(factoryUriWithExpand)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.complete();
return;
}
if (!o.hasBody()) {
testContext.complete();
return;
}
ServiceDocumentQueryResult r = o
.getBody(ServiceDocumentQueryResult.class);
synchronized (childServicesPerNode) {
childServicesPerNode.put(o.getUri(), r);
}
testContext.complete();
});
this.host.send(get);
}
testContext.await();
long expectedNodeCountPerLinkMax = factories.size();
long expectedNodeCountPerLinkMin = expectedNodeCountPerLinkMax;
if (this.replicationFactor != 0) {
// We expect services to end up either on K nodes, or K + 1 nodes,
// if limited replication is enabled. The reason we might end up with services on
// an additional node, is because we elect an owner to synchronize an entire factory,
// using the factory's link, and that might end up on a node not used for any child.
// This will produce children on that node, giving us K+1 replication, which is acceptable
// given K (replication factor) << N (total nodes in group)
expectedNodeCountPerLinkMax = this.replicationFactor + 1;
expectedNodeCountPerLinkMin = this.replicationFactor;
}
if (expectedChildCount == 0) {
expectedNodeCountPerLinkMax = 0;
expectedNodeCountPerLinkMin = 0;
}
// build a service link to node map so we can tell on which node each service instance landed
Map<String, Set<URI>> linkToNodeMap = new HashMap<>();
boolean isConverged = true;
for (Entry<URI, ServiceDocumentQueryResult> entry : childServicesPerNode.entrySet()) {
for (String link : entry.getValue().documentLinks) {
if (!serviceStates.containsKey(link)) {
this.host.log("service %s not expected, node: %s", link, entry.getKey());
isConverged = false;
continue;
}
Set<URI> hostsPerLink = linkToNodeMap.get(link);
if (hostsPerLink == null) {
hostsPerLink = new HashSet<>();
}
hostsPerLink.add(entry.getKey());
linkToNodeMap.put(link, hostsPerLink);
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
// each link must exist on N hosts, where N is either the replication factor, or, if not used, all nodes
for (Entry<String, Set<URI>> e : linkToNodeMap.entrySet()) {
if (e.getValue() == null && this.replicationFactor == 0) {
this.host.log("Service %s not found on any nodes", e.getKey());
isConverged = false;
continue;
}
if (e.getValue().size() < expectedNodeCountPerLinkMin
|| e.getValue().size() > expectedNodeCountPerLinkMax) {
this.host.log("Service %s found on %d nodes, expected %d -> %d", e.getKey(), e
.getValue().size(), expectedNodeCountPerLinkMin,
expectedNodeCountPerLinkMax);
isConverged = false;
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
if (expectedChildCount == 0) {
// DELETE test, all children removed from all hosts, we are done
return updatedStatesPerSelfLink;
}
// verify /available reports correct results on the factory.
URI factoryUri = factories.values().iterator().next();
Class<?> stateType = serviceStates.values().iterator().next().getClass();
waitForReplicatedFactoryServiceAvailable(factoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// we have the correct number of services on all hosts. Now verify
// the state of each service matches what we expect
isConverged = true;
for (Entry<String, Set<URI>> entry : linkToNodeMap.entrySet()) {
String selfLink = entry.getKey();
int convergedNodeCount = 0;
for (URI nodeUri : entry.getValue()) {
ServiceDocumentQueryResult childLinksAndDocsPerHost = childServicesPerNode
.get(nodeUri);
Object jsonState = childLinksAndDocsPerHost.documents.get(selfLink);
if (jsonState == null && this.replicationFactor == 0) {
this.host
.log("Service %s not present on host %s", selfLink, entry.getKey());
continue;
}
if (jsonState == null) {
continue;
}
T initialState = serviceStates.get(selfLink);
if (initialState == null) {
continue;
}
@SuppressWarnings("unchecked")
T stateOnNode = (T) Utils.fromJson(jsonState, stateType);
if (!stateChecker.test(initialState, stateOnNode)) {
this.host
.log("State for %s not converged on node %s. Current state: %s, Initial: %s",
selfLink, nodeUri, Utils.toJsonHtml(stateOnNode),
Utils.toJsonHtml(initialState));
break;
}
if (stateOnNode.documentVersion < expectedVersion) {
this.host
.log("Version (%d, expected %d) not converged, state: %s",
stateOnNode.documentVersion,
expectedVersion,
Utils.toJsonHtml(stateOnNode));
break;
}
if (stateOnNode.documentEpoch == null) {
this.host.log("Epoch is missing, state: %s",
Utils.toJsonHtml(stateOnNode));
break;
}
// Do not check exampleState.counter, in this validation loop.
// We can not compare the counter since the replication test sends the updates
// in parallel, meaning some of them will get re-ordered and ignored due to
// version being out of date.
updatedStatesPerSelfLink.put(selfLink, stateOnNode);
convergedNodeCount++;
}
if (convergedNodeCount < expectedNodeCountPerLinkMin
|| convergedNodeCount > expectedNodeCountPerLinkMax) {
isConverged = false;
break;
}
}
if (isConverged) {
return updatedStatesPerSelfLink;
}
Thread.sleep(500);
} while (new Date().before(expiration));
throw new TimeoutException();
}
private List<ServiceHostState> stopHostsToSimulateFailure(int failedNodeCount) {
int k = 0;
List<ServiceHostState> stoppedHosts = new ArrayList<>();
for (VerificationHost hostToStop : this.host.getInProcessHostMap().values()) {
this.host.log("Stopping host %s", hostToStop);
stoppedHosts.add(hostToStop.getState());
this.host.stopHost(hostToStop);
k++;
if (k >= failedNodeCount) {
break;
}
}
return stoppedHosts;
}
public static class StopVerificationTestService extends StatefulService {
public Collection<URI> serviceTargets;
public AtomicInteger outboundRequestCompletion = new AtomicInteger();
public AtomicInteger outboundRequestFailureCompletion = new AtomicInteger();
public StopVerificationTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation deleteForStop) {
// send requests to replicated services, during stop to verify that the
// runtime prevents any outbound requests from making it out
for (URI uri : this.serviceTargets) {
ReplicationTestServiceState body = new ReplicationTestServiceState();
body.stringField = ReplicationTestServiceState.CLIENT_PATCH_HINT;
for (int i = 0; i < 10; i++) {
// send patch to self, so the select owner logic gets invoked and in theory
// queues or cancels the request
Operation op = Operation.createPatch(this, uri.getPath()).setBody(body)
.setTargetReplicated(true)
.setCompletion((o, e) -> {
if (e != null) {
this.outboundRequestFailureCompletion.incrementAndGet();
} else {
this.outboundRequestCompletion.incrementAndGet();
}
});
sendRequest(op);
}
}
}
}
private void stopHostsAndVerifyQueuing(Collection<VerificationHost> hostsToStop,
VerificationHost remainingHost,
Collection<URI> serviceTargets) throws Throwable {
this.host.log("Starting to stop hosts and verify queuing");
// reduce node expiration for unavailable hosts so gossip warning
// messages do not flood the logs
this.nodeGroupConfig.nodeRemovalDelayMicros = remainingHost.getMaintenanceIntervalMicros();
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(10));
// relax quorum to single remaining host
this.host.setNodeGroupQuorum(1);
// start a special test service that will attempt to send messages when it sees
// handleStop(). This is not expected of production code, since service authors
// should never have to worry about handleStop(). We rely on the fact that handleStop
// will be called due to node shutdown, and issue requests to replicated targets,
// then check if anyone of them actually made it out (they should not have)
List<StopVerificationTestService> verificationServices = new ArrayList<>();
// Do the inverse test. Remove all of the original hosts and this time, expect all the
// documents have owners assigned to the new hosts
for (VerificationHost h : hostsToStop) {
StopVerificationTestService s = new StopVerificationTestService();
verificationServices.add(s);
s.serviceTargets = serviceTargets;
h.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.stopHost(h);
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
for (StopVerificationTestService s : verificationServices) {
if (s.outboundRequestCompletion.get() > 0) {
throw new IllegalStateException("Replicated request succeeded");
}
if (s.outboundRequestFailureCompletion.get() < serviceTargets.size()) {
// We expect at least one failure per service target, if we have less
// keep polling.
this.host.log(
"Not converged yet: service %s on host %s has %d outbound request failures, which is lower than %d",
s.getSelfLink(), s.getHost().getId(),
s.outboundRequestFailureCompletion.get(), serviceTargets.size());
isConverged = false;
break;
}
}
if (isConverged) {
this.host.log("Done with stop hosts and verify queuing");
return;
}
Thread.sleep(250);
}
throw new TimeoutException();
}
private void waitForReplicatedFactoryServiceAvailable(URI uri, String nodeSelectorPath)
throws Throwable {
if (this.skipAvailabilityChecks) {
return;
}
if (UriUtils.isHostEqual(this.host, uri)) {
VerificationHost host = this.host;
// if uri is for in-process peers, then use the one
URI peerUri = UriUtils.buildUri(uri.toString().replace(uri.getPath(), ""));
VerificationHost peer = this.host.getInProcessHostMap().get(peerUri);
if (peer != null) {
host = peer;
}
TestContext ctx = host.testCreate(1);
CompletionHandler ch = (o, e) -> {
if (e != null) {
String msg = "Failed to check replicated factory service availability";
ctx.failIteration(new RuntimeException(msg, e));
return;
}
ctx.completeIteration();
};
host.registerForServiceAvailability(ch, nodeSelectorPath, true, uri.getPath());
ctx.await();
} else {
// for remote host
this.host.waitForReplicatedFactoryServiceAvailable(uri, nodeSelectorPath);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_7 |
crossvul-java_data_bad_3080_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_0 |
crossvul-java_data_good_4667_0 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Provides utility methods for working with {@linkplain File files}.
*
* <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
* JDK's {@link java.nio.file.Files} class.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@GwtIncompatible
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered reader
*/
@Beta
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
* java.nio.file.OpenOption...)}.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered writer
*/
@Beta
public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a new {@link ByteSource} for reading bytes from the given file.
*
* @since 14.0
*/
public static ByteSource asByteSource(File file) {
return new FileByteSource(file);
}
private static final class FileByteSource extends ByteSource {
private final File file;
private FileByteSource(File file) {
this.file = checkNotNull(file);
}
@Override
public FileInputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public Optional<Long> sizeIfKnown() {
if (file.isFile()) {
return Optional.of(file.length());
} else {
return Optional.absent();
}
}
@Override
public long size() throws IOException {
if (!file.isFile()) {
throw new FileNotFoundException(file.toString());
}
return file.length();
}
@Override
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
@Override
public String toString() {
return "Files.asByteSource(" + file + ")";
}
}
/**
* Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
* control how the file is opened for writing. When no mode is provided, the file will be
* truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
* will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static ByteSink asByteSink(File file, FileWriteMode... modes) {
return new FileByteSink(file, modes);
}
private static final class FileByteSink extends ByteSink {
private final File file;
private final ImmutableSet<FileWriteMode> modes;
private FileByteSink(File file, FileWriteMode... modes) {
this.file = checkNotNull(file);
this.modes = ImmutableSet.copyOf(modes);
}
@Override
public FileOutputStream openStream() throws IOException {
return new FileOutputStream(file, modes.contains(APPEND));
}
@Override
public String toString() {
return "Files.asByteSink(" + file + ", " + modes + ")";
}
}
/**
* Returns a new {@link CharSource} for reading character data from the given file using the given
* character set.
*
* @since 14.0
*/
public static CharSource asCharSource(File file, Charset charset) {
return asByteSource(file).asCharSource(charset);
}
/**
* Returns a new {@link CharSink} for writing character data to the given file using the given
* character set. The given {@code modes} control how the file is opened for writing. When no mode
* is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
* APPEND} mode is provided, writes will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
return asByteSink(file, modes).asCharSink(charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest possible byte array
* (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
@Beta
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
/**
* Reads all characters from a file into a {@link String}, using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static String toString(File file, Charset charset) throws IOException {
return asCharSource(file, charset).read();
}
/**
* Overwrites a file with the contents of a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
@Beta
public static void write(byte[] from, File to) throws IOException {
asByteSink(to).write(from);
}
/**
* Writes a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset).write(from);
}
/**
* Copies all bytes from a file to an output stream.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
@Beta
public static void copy(File from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Copies all the bytes from one file to another.
*
* <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process
* termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
* need to guard against those conditions, you should employ other file-level synchronization.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten
* with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i>
* file, the contents of that file will be deleted.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void copy(File from, File to) throws IOException {
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
asByteSource(from).copyTo(asByteSink(to));
}
/**
* Copies all characters from a file to an appendable object, using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static void copy(File from, Charset charset, Appendable to) throws IOException {
asCharSource(from, charset).copyTo(to);
}
/**
* Appends a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
* method is scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static void append(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, FileWriteMode.APPEND).write(from);
}
/**
* Returns true if the given files exist, are not directories, and contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
@Beta
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
* <p>Depending on the environmment that this code is run in, the system temporary directory (and
* thus the directory this method creates) may be more visible that a program would like - files
* written to this directory may be read or overwritten by hostile programs running on the same
* machine.
*
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
* @deprecated For Android users, see the <a
* href="https://developer.android.com/training/data-storage" target="_blank">Data and File
* Storage overview</a> to select an appropriate temporary directory (perhaps {@code
* context.getCacheDir()}). For developers on Java 7 or later, use {@link
* java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using {@link
* java.nio.file.Path#toFile() toFile()} if needed.
*/
@Beta
@Deprecated
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
@SuppressWarnings("GoodTime") // reading system time without TimeSource
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException(
"Failed to create directory within "
+ TEMP_DIR_ATTEMPTS
+ " attempts (tried "
+ baseName
+ "0 to "
+ baseName
+ (TEMP_DIR_ATTEMPTS - 1)
+ ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the same as the unix command of
* the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
@Beta
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified file. Note that if
* this operation fails it may have succeeded in creating some (but not all) of the necessary
* parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
* directories of the specified file could not be created.
* @since 4.0
*/
@Beta
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
* mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
* -- or even that the caller can create it, but this method makes no such guarantees even for
* non-root files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves a file from one path to another. This method can rename a file and/or move it to a
* different directory. In either case {@code to} must be the target path for the file itself; not
* just the new name for the file or the path to the new parent directory.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include line-termination characters, but
* does include other leading and trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static String readFirstLine(File file, Charset charset) throws IOException {
return asCharSource(file, charset).readFirstLine();
}
/**
* Reads all of the lines from a file. The lines do not include line-termination characters, but
* do include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Files.asCharSource(file, charset).readLines()}.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
@Beta
public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return asCharSource(file, charset)
.readLines(
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Streams lines from a {@link File}, stopping when our callback returns false, or we have read
* all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
* @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
/**
* Fully maps a file read-only in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
* MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
return mapInternal(file, mode, -1);
}
/**
* Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
* long, long)} using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
* with the requested {@code size}. Thus this method is useful for creating memory mapped files
* which do not yet exist.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
checkArgument(size >= 0, "size (%s) may not be negative", size);
return mapInternal(file, mode, size);
}
private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
Closer closer = Closer.create();
try {
RandomAccessFile raf =
closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
FileChannel channel = closer.register(raf.getChannel());
return channel.map(mode, 0, size == -1 ? channel.size() : size);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent
* to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* <p>These heuristics do not always match the behavior of the filesystem. In particular, consider
* the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
* symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
* sibling of {@code a} referred to by {@code b}.
*
* @since 11.0
*/
@Beta
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<>();
// resolve ., .., and //
for (String component : components) {
switch (component) {
case ".":
continue;
case "..":
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
break;
default:
path.add(component);
break;
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for
* the given file name, or the empty string if the file has no extension. The result does not
* include the '{@code .}'.
*
* <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's
* name as determined by {@link File#getName}. It does not account for any filesystem-specific
* behavior that the {@link File} API does not already account for. For example, on NTFS it will
* report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
* will drop the {@code ":.txt"} part of the name when the file is actually created on the
* filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>.
*
* @since 11.0
*/
@Beta
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its <a
* href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
@Beta
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
/**
* Returns a {@link TreeTraverser} instance for {@link File} trees.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* @since 15.0
* @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
* {@link #fileTraverser()} instead with the same semantics as this method.
*/
@Deprecated
static TreeTraverser<File> fileTreeTraverser() {
return FILE_TREE_TRAVERSER;
}
private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
new TreeTraverser<File>() {
@Override
public Iterable<File> children(File file) {
return fileTreeChildren(file);
}
@Override
public String toString() {
return "Files.fileTreeTraverser()";
}
};
/**
* Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
* starts from a {@link File} and will return all files and directories it encounters.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
* except that it doesn't follow symbolic links and returns {@code Path} instances.
*
* <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
* a directory, no exception will be thrown and the returned {@link Iterable} will contain a
* single element: that file.
*
* <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
* with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
* "/home/alice", ...]}
*
* @since 23.5
*/
@Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
private static final SuccessorsFunction<File> FILE_TREE =
new SuccessorsFunction<File>() {
@Override
public Iterable<File> successors(File file) {
return fileTreeChildren(file);
}
};
private static Iterable<File> fileTreeChildren(File file) {
// check isDirectory() just because it may be faster than listFiles() on a non-directory
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return Collections.unmodifiableList(Arrays.asList(files));
}
}
return Collections.emptyList();
}
/**
* Returns a predicate that returns the result of {@link File#isDirectory} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isDirectory() {
return FilePredicate.IS_DIRECTORY;
}
/**
* Returns a predicate that returns the result of {@link File#isFile} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isFile() {
return FilePredicate.IS_FILE;
}
private enum FilePredicate implements Predicate<File> {
IS_DIRECTORY {
@Override
public boolean apply(File file) {
return file.isDirectory();
}
@Override
public String toString() {
return "Files.isDirectory()";
}
},
IS_FILE {
@Override
public boolean apply(File file) {
return file.isFile();
}
@Override
public String toString() {
return "Files.isFile()";
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_4667_0 |
crossvul-java_data_good_3082_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.http.netty.NettyHttpListener;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleNonPersistedService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test(expected = TimeoutException.class)
public void startCoreServicesSynchronouslyWithTimeout() throws Throwable {
setUp(false);
// use reflection to shorten operation timeout value
Field field = ServiceHost.class.getDeclaredField("state");
field.setAccessible(true);
ServiceHost.ServiceHostState state = (ServiceHostState) field.get(this.host);
state.operationTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(100);
this.host.startCoreServicesSynchronously(new StatelessService() {
@SuppressWarnings("unused")
public static final String SELF_LINK = "/foo";
@Override
public void handleStart(Operation startPost) {
// do not complete
}
});
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState[] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String[] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[]{
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis * 5));
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, slowMaintInterval);
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
long end = System.nanoTime() / 1000;
double expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all slow minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
ServiceStat http1AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountDaily));
return false;
}
ServiceStat http1AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountHourly));
return false;
}
ServiceStat http2AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountDaily));
return false;
}
ServiceStat http2AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(100));
// no INSTRUMENTATION, as it prevents cache eviction
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// wait for some host maintenance intervals
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// verify services have stopped
this.host.waitFor("wait for services to stop.", () -> {
for (Service service : services) {
if (this.host.getServiceStage(service.getSelfLink()) != null) {
return false;
}
}
return true;
});
// reset cache clear delay to default value
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_SERVICE_CACHE_CLEAR_DELAY_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(services.size());
for (Service service : services) {
Operation get = Operation.createGet(service.getUri()).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * services.size());
for (Service service : services) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(service.getUri()).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
// verify cache miss count
ServiceStat cacheMissStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertTrue(cacheMissStat.latestValue >= this.serviceCount);
// verify cache hit count
ServiceStat cacheHitStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_HIT_COUNT);
assertNotNull(cacheHitStat);
assertTrue(cacheHitStat.latestValue >= requestCount * this.serviceCount);
// now set host cache clear delay to a short value but the services' cached clear
// delay to a long value, and verify that the services are stopped only after
// the long value
List<Service> cachedServices = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
for (Service service : cachedServices) {
service.setCacheClearDelayMicros(TimeUnit.SECONDS.toMicros(5));
}
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(100));
double newMaintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > newMaintCount + 1;
});
for (Service service : cachedServices) {
assertEquals(ProcessingStage.AVAILABLE,
this.host.getServiceStage(service.getSelfLink()));
}
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > newMaintCount + 5;
});
for (Service service : cachedServices) {
ProcessingStage processingStage = this.host.getServiceStage(service.getSelfLink());
assertTrue(processingStage == null || processingStage == ProcessingStage.STOPPED);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[]{
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS};
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
@Test
public void serviceStopDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service stop
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
String factoryLink = OnDemandLoadFactoryService.create(this.host);
URI factoryURI = UriUtils.buildUri(this.host, factoryLink);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will stop all the services
// we just created since the memory limit was set so low.
long expectedStopTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedStopTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify stopped services get started.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting stop to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be started
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely stopped) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
}
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop service more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should succeed, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectSuccess(deleteOp);
// create a service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped.
// This verifies that a service will stop while it is idle for some duration
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
int requestCount = 10;
int requestDelayMills = 40;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
this.host.waitFor("Waiting for service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping the service to induce collision
// of stop with active requests. First prevent automatic stop by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a start
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
// temporarily disabled - https://jira-hzn.eng.vmware.com/browse/VRXEN-21
/*
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
*/
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
@Test
public void queryServiceUrisWithAuth() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new ExampleNonPersistedService());
this.host.waitForServiceAvailable(ExampleNonPersistedService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
// create user foo@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserFoo = this.host.testCreate(1);
String userFoo = "foo@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userFoo)
.setUserSelfLink(userFoo)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "foo")
.build())
.setCompletion(createUserFoo.getCompletion())
.start();
createUserFoo.await();
// create user bar@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserBar = this.host.testCreate(1);
String userBar = "bar@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userBar)
.setUserSelfLink(userBar)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build())
.setCompletion(createUserBar.getCompletion())
.start();
createUserBar.await();
// create foo & bar documents
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
ExampleServiceState exampleBar = new ExampleServiceState();
exampleBar.name = "bar";
exampleBar.documentSelfLink = "bar";
List<Operation> posts = new ArrayList<>();
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleFoo));
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleBar));
sender.sendAndWait(posts);
AuthTestUtils.resetAuthorizationContext(this.host);
// login as foo
AuthTestUtils.loginAndSetToken(this.host, "foo@example.com", "password");
Operation factoryGetFoo = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultFoo = sender.sendAndWait(factoryGetFoo, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultFoo.documentLinks.size());
assertEquals("/core/nonpersist-examples/foo", factoryGetResultFoo.documentLinks.get(0));
// login as bar
AuthTestUtils.loginAndSetToken(this.host, "bar@example.com", "password");
Operation factoryGetBar = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultBar = sender.sendAndWait(factoryGetBar, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultBar.documentLinks.size());
assertEquals("/core/nonpersist-examples/bar", factoryGetResultBar.documentLinks.get(0));
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void findOwnerNode() throws Throwable {
setUp(false);
int nodeCount = 3;
int pathVerificationCount = 3;
this.host.setUpPeerHosts(nodeCount);
this.host.joinNodesAndVerifyConvergence(nodeCount, true);
this.host.setNodeGroupQuorum(nodeCount);
// each host should say same owner for the path
for (int i = 0; i < pathVerificationCount; i++) {
String path = UUID.randomUUID().toString();
Map<String, String> map = new HashMap<>();
Set<String> ownerIds = new HashSet<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String ownerId = h.findOwnerNode(null, path).ownerNodeId;
map.put(h.getId(), ownerId);
ownerIds.add(ownerId);
}
assertThat(ownerIds).as("all peers say same owner for %s. %s", path, map).hasSize(1);
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@Test
public void findLocalRootNamespaceServiceViaURI() throws Throwable {
setUp(false);
// full URI for the localhost (ex: http://127.0.0.1:50000)
URI rootUri = this.host.getUri();
// ex: http://127.0.0.1:50000/
URI rootUriWithPath = UriUtils.buildUri(this.host.getUri(), UriUtils.URI_PATH_CHAR);
// Accessing localhost with URI will short-circuit the call to direct method invocation. (No netty layer)
// This should resolve the RootNamespaceService
this.host.getTestRequestSender().sendAndWait(Operation.createGet(rootUri));
// same for the URI with path-character
this.host.getTestRequestSender().sendAndWait(Operation.createGet(rootUriWithPath));
}
@Test
public void cors() throws Throwable {
// CORS config for http://example.com
CorsConfig corsConfig = CorsConfigBuilder.forOrigin("http://example.com")
.allowedRequestMethods(HttpMethod.PUT)
.allowedRequestHeaders("x-xenon")
.build();
this.host = new VerificationHost() {
@Override
protected void configureHttpListener(ServiceRequestListener httpListener) {
// enable CORS
((NettyHttpListener) httpListener).setCorsConfig(corsConfig);
}
};
VerificationHost.initialize(this.host, VerificationHost.buildDefaultServiceHostArguments(0));
this.host.start();
TestRequestSender sender = this.host.getTestRequestSender();
Operation get;
Operation preflight;
Operation response;
// Request from http://example.com
get = Operation.createGet(this.host, "/")
.addRequestHeader("origin", "http://example.com")
.forceRemote();
response = sender.sendAndWait(get);
assertEquals("http://example.com", response.getResponseHeader("access-control-allow-origin"));
// Request from http://not-example.com
get = Operation.createGet(this.host, "/")
.addRequestHeader("origin", "http://not-example.com")
.forceRemote();
response = sender.sendAndWait(get);
assertNull(response.getResponseHeader("access-control-allow-origin"));
// Preflight from http://example.com
preflight = Operation.createOptions(this.host, "/")
.addRequestHeader("origin", "http://example.com")
.addRequestHeader("Access-Control-Request-Method", "POST")
.forceRemote();
response = sender.sendAndWait(preflight);
assertEquals("http://example.com", response.getResponseHeader("access-control-allow-origin"));
assertEquals("PUT", response.getResponseHeader("access-control-allow-methods"));
assertEquals("x-xenon", response.getResponseHeader("access-control-allow-headers"));
// Preflight from http://not-example.com
preflight = Operation.createOptions(this.host, "/")
.addRequestHeader("origin", "http://not-example.com")
.addRequestHeader("Access-Control-Request-Method", "POST")
.addRequestHeader(Operation.CONNECTION_HEADER, "close")
.setKeepAlive(false)
.forceRemote();
response = sender.sendAndWait(preflight);
assertNull(response.getResponseHeader("access-control-allow-origin"));
assertNull(response.getResponseHeader("access-control-allow-methods"));
assertNull(response.getResponseHeader("access-control-allow-headers"));
}
@After
public void tearDown() {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
if (!this.host.isStopping()) {
AuthTestUtils.logout(this.host);
}
this.host.tearDown();
this.host = null;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_3 |
crossvul-java_data_good_3082_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_SYNCHRONIZATION;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.var.equals((1.0 * numBins) / 2.0));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factorySynchUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_SYNCHRONIZATION));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceSynchUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_SYNCHRONIZATION));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySynchUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSynchUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySynchUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSynchUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_5 |
crossvul-java_data_bad_3075_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.services.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.AuthorizationSetupHelper;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.FactoryService;
import com.vmware.xenon.common.NodeSelectorService.SelectAndForwardRequest;
import com.vmware.xenon.common.NodeSelectorService.SelectOwnerResponse;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationJoin;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceHost.HttpScheme;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.StatefulService;
import com.vmware.xenon.common.SynchronizationTaskService;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.RoundRobinIterator;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleTaskService.ExampleTaskServiceState;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupBroadcastResult.PeerNodeResult;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceErrorResponse;
import com.vmware.xenon.services.common.ReplicationTestService.ReplicationTestServiceState;
import com.vmware.xenon.services.common.ResourceGroupService.PatchQueryRequest;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestNodeGroupService {
public static class PeriodicExampleFactoryService extends FactoryService {
public static final String SELF_LINK = "test/examples-periodic";
public PeriodicExampleFactoryService() {
super(ExampleServiceState.class);
}
@Override
public Service createServiceInstance() throws Throwable {
ExampleService s = new ExampleService();
s.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
return s;
}
}
public static class ExampleServiceWithCustomSelector extends StatefulService {
public ExampleServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.REPLICATION, true);
super.toggleOption(ServiceOption.OWNER_SELECTION, true);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ExampleFactoryServiceWithCustomSelector extends FactoryService {
public ExampleFactoryServiceWithCustomSelector() {
super(ExampleServiceState.class);
super.setPeerNodeSelectorPath(CUSTOM_GROUP_NODE_SELECTOR);
}
@Override
public Service createServiceInstance() throws Throwable {
return new ExampleServiceWithCustomSelector();
}
}
private static final String CUSTOM_EXAMPLE_SERVICE_KIND = "xenon:examplestate";
private static final String CUSTOM_NODE_GROUP_NAME = "custom";
private static final String CUSTOM_NODE_GROUP = UriUtils.buildUriPath(
ServiceUriPaths.NODE_GROUP_FACTORY,
CUSTOM_NODE_GROUP_NAME);
private static final String CUSTOM_GROUP_NODE_SELECTOR = UriUtils.buildUriPath(
ServiceUriPaths.NODE_SELECTOR_PREFIX,
CUSTOM_NODE_GROUP_NAME);
public static final long DEFAULT_MAINT_INTERVAL_MICROS = TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
private VerificationHost host;
/**
* Command line argument specifying number of times to run the same test method.
*/
public int testIterationCount = 1;
/**
* Command line argument specifying default number of in process service hosts
*/
public int nodeCount = 3;
/**
* Command line argument specifying request count
*/
public int updateCount = 10;
/**
* Command line argument specifying service instance count
*/
public int serviceCount = 10;
/**
* Command line argument specifying test duration
*/
public long testDurationSeconds;
/**
* Command line argument specifying iterations per test method
*/
public long iterationCount = 1;
/**
* Command line argument used by replication long running tests
*/
public long totalOperationLimit = Long.MAX_VALUE;
private NodeGroupConfig nodeGroupConfig = new NodeGroupConfig();
private EnumSet<ServiceOption> postCreationServiceOptions = EnumSet.noneOf(ServiceOption.class);
private boolean expectFailure;
private long expectedFailureStartTimeMicros;
private List<URI> expectedFailedHosts = new ArrayList<>();
private String replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
private String replicationNodeSelector = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
private long replicationFactor;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
if (!this.host.isRemotePeerTest() &&
!CUSTOM_EXAMPLE_SERVICE_KIND.equals(current.documentKind)) {
return false;
}
return current.name.equals(initial.name);
};
private Function<ExampleServiceState, Void> exampleStateUpdateBodySetter = (
ExampleServiceState state) -> {
state.name = Utils.getNowMicrosUtc() + "";
return null;
};
private boolean isPeerSynchronizationEnabled = true;
private boolean isAuthorizationEnabled = false;
private HttpScheme replicationUriScheme;
private boolean skipAvailabilityChecks = false;
private boolean isMultiLocationTest = false;
private void setUp(int localHostCount) throws Throwable {
if (this.host != null) {
return;
}
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
this.host.setAuthorizationEnabled(this.isAuthorizationEnabled);
VerificationHost.createAndAttachSSLClient(this.host);
if (this.replicationUriScheme == HttpScheme.HTTPS_ONLY) {
// disable HTTP, forcing host.getPublicUri() to return a HTTPS schemed URI. This in
// turn forces the node group to use HTTPS for join, replication, etc
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// the default is disable (-1) so we must set port to 0, to enable SSL and make the
// runtime pick a random HTTPS port
this.host.setSecurePort(0);
}
if (this.testDurationSeconds > 0) {
// for long running tests use the default interval to match production code
this.host.maintenanceIntervalMillis = TimeUnit.MICROSECONDS.toMillis(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
}
this.host.start();
if (this.host.isAuthorizationEnabled()) {
this.host.setSystemAuthorizationContext();
}
CommandLineArgumentParser.parseFromProperties(this.host);
this.host.setStressTest(this.host.isStressTest);
this.host.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
this.host.setMultiLocationTest(this.isMultiLocationTest);
this.host.setUpPeerHosts(localHostCount);
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
setUpPeerHostWithAdditionalServices(h1);
}
// If the peer hosts are remote, then we undo CUSTOM_EXAMPLE_SERVICE_KIND
// from the KINDS cache and use the real documentKind of ExampleService.
if (this.host.isRemotePeerTest()) {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
}
}
private void setUpPeerHostWithAdditionalServices(VerificationHost h1) throws Throwable {
h1.setStressTest(this.host.isStressTest);
h1.waitForServiceAvailable(ExampleService.FACTORY_LINK);
Replication1xExampleFactoryService exampleFactory1x = new Replication1xExampleFactoryService();
h1.startServiceAndWait(exampleFactory1x,
Replication1xExampleFactoryService.SELF_LINK,
null);
Replication3xExampleFactoryService exampleFactory3x = new Replication3xExampleFactoryService();
h1.startServiceAndWait(exampleFactory3x,
Replication3xExampleFactoryService.SELF_LINK,
null);
// start the replication test factory service with OWNER_SELECTION
ReplicationFactoryTestService ownerSelRplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(ownerSelRplFactory,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK,
null);
// start the replication test factory service with STRICT update checking
ReplicationFactoryTestService strictReplFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(strictReplFactory,
ReplicationFactoryTestService.STRICT_SELF_LINK, null);
// start the replication test factory service with simple replication, no owner selection
ReplicationFactoryTestService replFactory = new ReplicationFactoryTestService();
h1.startServiceAndWait(replFactory,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK, null);
}
private Map<URI, URI> getFactoriesPerNodeGroup(String factoryLink) {
Map<URI, URI> map = this.host.getNodeGroupToFactoryMap(factoryLink);
for (URI h : this.expectedFailedHosts) {
URI e = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
// do not send messages through hosts that will be stopped: this allows all messages to
// end the node group and the succeed or fail based on the test goals. If we let messages
// route through a host that we will abruptly stop, the message might timeout, which is
// OK for the expected failure case when quorum is not met, but will prevent is from confirming
// in the non eager consistency case, that all updates were written to at least one host
map.remove(e);
}
return map;
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
Utils.registerKind(ExampleServiceState.class, CUSTOM_EXAMPLE_SERVICE_KIND);
}
private void setUpOnDemandLoad() throws Throwable {
setUp();
// we need at least 5 nodes, because we're going to stop 2
// nodes and we need majority quorum
this.nodeCount = Math.max(5, this.nodeCount);
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
// create node group, join nodes and set majority quorum
setUp(this.nodeCount);
toggleOnDemandLoad();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.host.getPeerCount() / 2 + 1);
}
private void toggleOnDemandLoad() {
for (URI nodeUri : this.host.getNodeGroupMap().keySet()) {
URI factoryUri = UriUtils.buildUri(nodeUri, ExampleService.FACTORY_LINK);
this.host.toggleServiceOptions(factoryUri, EnumSet.of(ServiceOption.ON_DEMAND_LOAD),
null);
}
}
@After
public void tearDown() throws InterruptedException {
Utils.registerKind(ExampleServiceState.class,
Utils.toDocumentKind(ExampleServiceState.class));
if (this.host == null) {
return;
}
if (this.host.isRemotePeerTest()) {
try {
this.host.logNodeProcessLogs(this.host.getNodeGroupMap().keySet(),
ServiceUriPaths.PROCESS_LOG);
} catch (Throwable e) {
this.host.log("Failure retrieving process logs: %s", Utils.toString(e));
}
try {
this.host.logNodeManagementState(this.host.getNodeGroupMap().keySet());
} catch (Throwable e) {
this.host.log("Failure retrieving management state: %s", Utils.toString(e));
}
}
this.host.tearDownInProcessPeers();
this.host.toggleNegativeTestMode(false);
this.host.tearDown();
this.host = null;
System.clearProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS);
}
@Test
public void synchronizationCollisionWithPosts() throws Throwable {
// POST requests go through the FactoryService
// and do not get queued with Synchronization
// requests, so if synchronization was running
// while POSTs were happening for the same factory
// service, we could run into collisions. This test
// verifies that xenon handles such collisions and
// POST requests are always successful.
// Join the nodes with full quorum and wait for nodes to
// converge and synchronization to complete.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// Find the owner node for /core/examples. We will
// use it to start on-demand synchronization for
// this factory
URI factoryUri = UriUtils.buildUri(this.host.getPeerHost(), ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(factoryUri, this.replicationNodeSelector);
String taskPath = UriUtils.buildUriPath(
SynchronizationTaskService.FACTORY_LINK,
UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
VerificationHost owner = null;
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
if (peer.isOwner(ExampleService.FACTORY_LINK, ServiceUriPaths.DEFAULT_NODE_SELECTOR)) {
owner = peer;
break;
}
}
this.host.log(Level.INFO, "Owner of synch-task is %s", owner.getId());
// Get the membershipUpdateTimeMicros so that we can
// kick-off the synch-task on-demand.
URI taskUri = UriUtils.buildUri(owner, taskPath);
SynchronizationTaskService.State taskState = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
long membershipUpdateTimeMicros = taskState.membershipUpdateTimeMicros;
// Start posting and in the middle also start
// synchronization. All POSTs should succeed!
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
TestContext ctx = this.host.testCreate((this.serviceCount * 10) + 1);
for (int i = 0; i < this.serviceCount * 10; i++) {
if (i == 5) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK);
task.factorySelfLink = ExampleService.FACTORY_LINK;
task.factoryStateKind = Utils.buildKind(ExampleService.ExampleServiceState.class);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros + 1;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
Operation post = Operation
.createPost(owner, SynchronizationTaskService.FACTORY_LINK)
.setBody(task)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
Operation post = Operation
.createPost(factoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void recognizeSelfInPeerNodesByPublicUri() throws Throwable {
String id = "node-" + VerificationHost.hostNumber.incrementAndGet();
String publicUri = "http://myhostname.local:";
// In order not to hardcode a port, 0 is used which will pick random port.
// The value of the random port is then used to set the initialPeerNodes and publicUri is if they
// used the assigned port to begin with.
ExampleServiceHost nodeA = new ExampleServiceHost() {
@Override
public List<URI> getInitialPeerHosts() {
try {
Field field = ServiceHost.class.getDeclaredField("state");
field.setAccessible(true);
ServiceHostState s = (ServiceHostState) field.get(this);
s.initialPeerNodes = new String[] { publicUri + getPort() };
s.publicUri = URI.create(publicUri + getPort());
} catch (Exception e) {
throw new RuntimeException(e);
}
return super.getInitialPeerHosts();
}
};
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
try {
String[] args = {
"--port=0",
"--id=" + id,
"--publicUri=" + publicUri,
"--bindAddress=127.0.0.1",
"--sandbox=" + tmpFolderA.getRoot().getAbsolutePath()
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP, null);
TestRequestSender sender = new TestRequestSender(nodeA);
Operation op = Operation.createGet(nodeGroupUri)
.setReferer(nodeA.getUri());
NodeGroupState nodeGroupState = sender.sendAndWait(op, NodeGroupState.class);
assertEquals(1, nodeGroupState.nodes.size());
assertEquals(1, nodeGroupState.nodes.values().iterator().next().membershipQuorum);
} finally {
tmpFolderA.delete();
nodeA.stop();
}
}
@Test
public void commandLineJoinRetries() throws Throwable {
this.host = VerificationHost.create(0);
this.host.start();
ExampleServiceHost nodeA = null;
TemporaryFolder tmpFolderA = new TemporaryFolder();
tmpFolderA.create();
this.setUp(1);
try {
// start a node, supplying a bogus peer. Verify we retry, up to expiration which is
// the operation timeout
nodeA = new ExampleServiceHost();
String id = "nodeA-" + VerificationHost.hostNumber.incrementAndGet();
int bogusPort = 1;
String[] args = {
"--port=0",
"--id=" + id,
"--bindAddress=127.0.0.1",
"--sandbox=" + tmpFolderA.getRoot().getAbsolutePath(),
"--peerNodes=" + "http://127.0.0.1:" + bogusPort
};
nodeA.initialize(args);
nodeA.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
nodeA.start();
// verify we see a specific retry stat
URI nodeGroupUri = UriUtils.buildUri(nodeA, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI statsUri = UriUtils.buildStatsUri(nodeGroupUri);
this.host.waitFor("expected stat did not converge", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsUri);
ServiceStat st = stats.entries.get(NodeGroupService.STAT_NAME_JOIN_RETRY_COUNT);
if (st == null || st.latestValue < 1) {
return false;
}
return true;
});
} finally {
if (nodeA != null) {
nodeA.stop();
tmpFolderA.delete();
}
}
}
@Test
public void synchronizationOnDemandLoad() throws Throwable {
// Setup peer nodes
setUp(this.nodeCount);
long intervalMicros = TimeUnit.MILLISECONDS.toMicros(200);
// Start the ODL Factory service on all the peers.
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
// Reduce cache clear delay to short duration
// to cause ODL service stops.
h.setServiceCacheClearDelayMicros(h.getMaintenanceIntervalMicros());
// create an on demand load factory and services
OnDemandLoadFactoryService.create(h);
}
// join the nodes and set full quorum.
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Create a few child-services.
VerificationHost h = this.host.getPeerHost();
Map<URI, ExampleServiceState> childServices = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = UUID.randomUUID().toString();
o.setBody(initialState);
},
UriUtils.buildFactoryUri(h, OnDemandLoadFactoryService.class));
// Verify that each peer host reports the correct value for ODL stop count.
for (VerificationHost vh : this.host.getInProcessHostMap().values()) {
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(vh, this.serviceCount));
}
// Add a new host to the cluster.
VerificationHost newHost = this.host.setUpLocalPeerHost(0, h.getMaintenanceIntervalMicros(),
null);
newHost.setServiceCacheClearDelayMicros(intervalMicros);
OnDemandLoadFactoryService.create(newHost);
this.host.joinNodesAndVerifyConvergence(this.nodeCount + 1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(OnDemandLoadFactoryService.SELF_LINK),
this.replicationNodeSelector);
// Do GETs on each previously created child services by calling the newly added host.
// This will trigger synchronization for the child services.
this.host.log(Level.INFO, "Verifying synchronization for ODL services");
for (Entry<URI, ExampleServiceState> childService : childServices.entrySet()) {
String childServicePath = childService.getKey().getPath();
ExampleServiceState state = this.host.getServiceState(null,
ExampleServiceState.class, UriUtils.buildUri(newHost, childServicePath));
assertNotNull(state);
}
// Verify that the new peer host reports the correct value for ODL stop count.
this.host.waitFor("ODL services did not stop as expected",
() -> checkOdlServiceStopCount(newHost, this.serviceCount));
}
private boolean checkOdlServiceStopCount(VerificationHost host, int serviceCount)
throws Throwable {
ServiceStat stopCount = host
.getServiceStats(host.getManagementServiceUri())
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
if (stopCount == null || stopCount.latestValue < serviceCount) {
this.host.log(Level.INFO,
"Current stopCount is %s",
(stopCount != null) ? String.valueOf(stopCount.latestValue) : "null");
return false;
}
return true;
}
@Test
public void customNodeGroupWithObservers() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
Logger.getAnonymousLogger().info("Iteration: " + i);
verifyCustomNodeGroupWithObservers();
tearDown();
}
}
private void verifyCustomNodeGroupWithObservers() throws Throwable {
setUp(this.nodeCount);
// on one of the hosts create the custom group but with self as an observer. That peer should
// never receive replicated or broadcast requests
URI observerHostUri = this.host.getPeerHostUri();
ServiceHostState observerHostState = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_MANAGEMENT));
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerHostState.id;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerHostUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
final String customFactoryLink = "custom-factory";
// start a node selector attached to the custom group
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
NodeSelectorState initialState = new NodeSelectorState();
initialState.nodeGroupLink = CUSTOM_NODE_GROUP;
h.startServiceAndWait(new ConsistentHashingNodeSelectorService(),
CUSTOM_GROUP_NODE_SELECTOR, initialState);
// start the factory that is attached to the custom group selector
h.startServiceAndWait(ExampleFactoryServiceWithCustomSelector.class, customFactoryLink);
}
URI customNodeGroupServiceOnObserver = UriUtils
.buildUri(observerHostUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
expectedOptionsPerNode.put(customNodeGroupServiceOnObserver,
observerSelfState.options);
this.host.joinNodesAndVerifyConvergence(CUSTOM_NODE_GROUP, this.nodeCount,
this.nodeCount, expectedOptionsPerNode);
// one of the nodes is observer, so we must set quorum to 2 explicitly
this.host.setNodeGroupQuorum(2, customNodeGroupServiceOnObserver);
this.host.waitForNodeSelectorQuorumConvergence(CUSTOM_GROUP_NODE_SELECTOR, 2);
this.host.waitForNodeGroupIsAvailableConvergence(CUSTOM_NODE_GROUP);
int restartCount = 0;
// verify that the observer node shows up as OBSERVER on all peers, including self
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI customNodeGroupUri = UriUtils.buildUri(hostUri, CUSTOM_NODE_GROUP);
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
customNodeGroupUri);
for (NodeState ns : ngs.nodes.values()) {
if (ns.id.equals(observerHostState.id)) {
assertTrue(ns.options.contains(NodeOption.OBSERVER));
} else {
assertTrue(ns.options.contains(NodeOption.PEER));
}
}
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(customNodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", restartCount, 0);
// join all the nodes through the default group, making sure another group still works
this.host.joinNodesAndVerifyConvergence(this.nodeCount, true);
URI observerFactoryUri = UriUtils.buildUri(observerHostUri, customFactoryLink);
waitForReplicatedFactoryServiceAvailable(observerFactoryUri, CUSTOM_GROUP_NODE_SELECTOR);
// create N services on the custom group, verify none of them got created on the observer.
// We actually post directly to the observer node, which should forward to the other nodes
Map<URI, ExampleServiceState> serviceStatesOnPost = this.host.doFactoryChildServiceStart(
null, this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = Utils.getNowMicrosUtc() + "";
o.setBody(body);
},
observerFactoryUri);
ServiceDocumentQueryResult r = this.host.getFactoryState(observerFactoryUri);
assertEquals(0, r.documentLinks.size());
// do a GET on each service and confirm the owner id is never that of the observer node
Map<URI, ExampleServiceState> serviceStatesFromGet = this.host.getServiceState(
null, ExampleServiceState.class, serviceStatesOnPost.keySet());
for (ExampleServiceState s : serviceStatesFromGet.values()) {
if (observerHostState.id.equals(s.documentOwner)) {
throw new IllegalStateException("Observer node reported state for service");
}
}
// create additional example services which are not associated with the custom node group
// and verify that they are always included in queries which target the custom node group
// (e.g. that the query is never executed on the OBSERVER node).
createExampleServices(observerHostUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI serviceUri = UriUtils.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
URI forwardQueryUri = UriUtils.buildForwardRequestUri(serviceUri, null,
CUSTOM_GROUP_NODE_SELECTOR);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(forwardQueryUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Forwarded query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
}
task.querySpec.options = EnumSet.of(QueryTask.QuerySpecification.QueryOption.BROADCAST);
task.nodeSelectorLink = CUSTOM_GROUP_NODE_SELECTOR;
URI queryPostUri = UriUtils.buildUri(observerHostUri, ServiceUriPaths.CORE_QUERY_TASKS);
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(queryPostUri)
.setBody(task)
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
int resultCount = rsp.results.documentLinks.size();
if (resultCount != 2 * this.serviceCount) {
ctx.fail(new IllegalStateException(
"Broadcast query returned unexpected document count " +
resultCount));
return;
}
ctx.complete();
});
this.host.send(post);
ctx.await();
URI existingNodeGroup = this.host.getPeerNodeGroupUri();
// start more nodes, insert them to existing group, but with no synchronization required
// start some additional nodes
Collection<VerificationHost> existingHosts = this.host.getInProcessHostMap().values();
int additionalHostCount = this.nodeCount;
this.host.setUpPeerHosts(additionalHostCount);
List<ServiceHost> newHosts = Collections.synchronizedList(new ArrayList<>());
newHosts.addAll(this.host.getInProcessHostMap().values());
newHosts.removeAll(existingHosts);
expectedOptionsPerNode.clear();
// join new nodes with existing node group.
TestContext testContext = this.host.testCreate(newHosts.size());
for (ServiceHost h : newHosts) {
URI newCustomNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
JoinPeerRequest joinBody = JoinPeerRequest.create(existingNodeGroup, null);
joinBody.localNodeOptions = EnumSet.of(NodeOption.PEER);
this.host.send(Operation.createPost(newCustomNodeGroupUri)
.setBody(joinBody)
.setCompletion(testContext.getCompletion()));
expectedOptionsPerNode.put(newCustomNodeGroupUri, joinBody.localNodeOptions);
}
testContext.await();
this.host.waitForNodeGroupConvergence(this.host.getNodeGroupMap().values(),
this.host.getNodeGroupMap().size(),
this.host.getNodeGroupMap().size(),
expectedOptionsPerNode, false);
restartCount = 0;
// do another restart check. None of the new nodes should have reported restarts
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
URI nodeGroupUri = UriUtils.buildUri(hostUri, ServiceUriPaths.DEFAULT_NODE_GROUP);
ServiceStats nodeGroupStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(nodeGroupUri));
ServiceStat restartStat = nodeGroupStats.entries
.get(NodeGroupService.STAT_NAME_RESTARTING_SERVICES_COUNT);
if (restartStat != null) {
restartCount += restartStat.latestValue;
}
}
assertEquals("expected different number of service restarts", 0,
restartCount);
}
@Test
public void verifyGossipForObservers() throws Throwable {
setUp(this.nodeCount);
Iterator<Entry<URI, URI>> nodeGroupIterator = this.host.getNodeGroupMap().entrySet()
.iterator();
URI observerUri = nodeGroupIterator.next().getKey();
String observerId = this.host.getServiceState(null,
ServiceHostState.class,
UriUtils.buildUri(observerUri, ServiceUriPaths.CORE_MANAGEMENT)).id;
// Create a custom node group. Mark one node as OBSERVER and rest as PEER
Map<URI, NodeState> selfStatePerNode = new HashMap<>();
NodeState observerSelfState = new NodeState();
observerSelfState.id = observerId;
observerSelfState.options = EnumSet.of(NodeOption.OBSERVER);
selfStatePerNode.put(observerUri, observerSelfState);
this.host.createCustomNodeGroupOnPeers(CUSTOM_NODE_GROUP_NAME, selfStatePerNode);
// Pick a PEER and join it to each node in the node-group
URI peerUri = nodeGroupIterator.next().getKey();
URI peerCustomUri = UriUtils.buildUri(peerUri, CUSTOM_NODE_GROUP);
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode = new HashMap<>();
Set<URI> customNodeUris = new HashSet<>();
for (Entry<URI, URI> node : this.host.getNodeGroupMap().entrySet()) {
URI nodeUri = node.getKey();
URI nodeCustomUri = UriUtils.buildUri(nodeUri, CUSTOM_NODE_GROUP);
JoinPeerRequest request = new JoinPeerRequest();
request.memberGroupReference = nodeCustomUri;
TestContext ctx = this.host.testCreate(1);
Operation post = Operation
.createPost(peerCustomUri)
.setBody(request)
.setReferer(this.host.getReferer())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(post);
ctx.await();
expectedOptionsPerNode.put(nodeCustomUri,
EnumSet.of((nodeUri == observerUri)
? NodeOption.OBSERVER : NodeOption.PEER));
customNodeUris.add(nodeCustomUri);
}
// Verify that gossip will propagate the single OBSERVER and the PEER nodes
// to every node in the custom node-group.
this.host.waitForNodeGroupConvergence(
customNodeUris, this.nodeCount, this.nodeCount, expectedOptionsPerNode, false);
}
@Test
public void synchronizationOneByOneWithAbruptNodeShutdown() throws Throwable {
setUp(this.nodeCount);
this.replicationTargetFactoryLink = PeriodicExampleFactoryService.SELF_LINK;
// start the periodic example service factory on each node
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.startServiceAndWait(PeriodicExampleFactoryService.class,
PeriodicExampleFactoryService.SELF_LINK);
}
// On one host, add some services. They exist only on this host and we expect them to synchronize
// across all hosts once this one joins with the group
VerificationHost initialHost = this.host.getPeerHost();
URI hostUriWithInitialState = initialHost.getUri();
Map<String, ExampleServiceState> exampleStatesPerSelfLink = createExampleServices(
hostUriWithInitialState);
URI hostWithStateNodeGroup = UriUtils.buildUri(hostUriWithInitialState,
ServiceUriPaths.DEFAULT_NODE_GROUP);
// before start joins, verify isolated factory synchronization is done
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
// join a node, with no state, one by one, to the host with state.
// The steps are:
// 1) set quorum to node group size + 1
// 2) Join new empty node with existing node group
// 3) verify convergence of factory state
// 4) repeat
List<URI> joinedHosts = new ArrayList<>();
Map<URI, URI> factories = new HashMap<>();
factories.put(hostWithStateNodeGroup, UriUtils.buildUri(hostWithStateNodeGroup,
this.replicationTargetFactoryLink));
joinedHosts.add(hostWithStateNodeGroup);
int fullQuorum = 1;
for (URI nodeGroupUri : this.host.getNodeGroupMap().values()) {
// skip host with state
if (hostWithStateNodeGroup.equals(nodeGroupUri)) {
continue;
}
this.host.log("Setting quorum to %d, already joined: %d",
fullQuorum + 1, joinedHosts.size());
// set quorum to expected full node group size, for the setup hosts
this.host.setNodeGroupQuorum(++fullQuorum);
this.host.testStart(1);
// join empty node, with node with state
this.host.joinNodeGroup(hostWithStateNodeGroup, nodeGroupUri, fullQuorum);
this.host.testWait();
joinedHosts.add(nodeGroupUri);
factories.put(nodeGroupUri, UriUtils.buildUri(nodeGroupUri,
this.replicationTargetFactoryLink));
this.host.waitForNodeGroupConvergence(joinedHosts, fullQuorum, fullQuorum, true);
this.host.waitForNodeGroupIsAvailableConvergence(nodeGroupUri.getPath(), joinedHosts);
this.waitForReplicatedFactoryChildServiceConvergence(
factories,
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker, exampleStatesPerSelfLink.size(),
0);
// Do updates, which will verify that the services are converged in terms of ownership.
// Since we also synchronize on demand, if there was any discrepancy, after updates, the
// services will converge
doExampleServicePatch(exampleStatesPerSelfLink,
joinedHosts.get(0));
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink, initialHost, joinedHosts, 0, 1,
ownerIds.size() - 1);
}
doNodeStopWithUpdates(exampleStatesPerSelfLink);
}
private void doExampleServicePatch(Map<String, ExampleServiceState> states,
URI nodeGroupOnSomeHost) throws Throwable {
this.host.log("Starting PATCH to %d example services", states.size());
TestContext ctx = this.host
.testCreate(this.updateCount * states.size());
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
for (int i = 0; i < this.updateCount; i++) {
for (Entry<String, ExampleServiceState> e : states.entrySet()) {
ExampleServiceState st = Utils.clone(e.getValue());
st.counter = (long) i;
Operation patch = Operation
.createPatch(UriUtils.buildUri(nodeGroupOnSomeHost, e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
this.host.log("Done with PATCH to %d example services", states.size());
}
public void doNodeStopWithUpdates(Map<String, ExampleServiceState> exampleStatesPerSelfLink)
throws Throwable {
this.host.log("Starting to stop nodes and send updates");
VerificationHost remainingHost = this.host.getPeerHost();
Collection<VerificationHost> hostsToStop = new ArrayList<>(this.host.getInProcessHostMap()
.values());
hostsToStop.remove(remainingHost);
List<URI> targetServices = new ArrayList<>();
for (String link : exampleStatesPerSelfLink.keySet()) {
// build the URIs using the host we plan to keep, so the maps we use below to lookup
// stats from URIs, work before and after node stop
targetServices.add(UriUtils.buildUri(remainingHost, link));
}
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(this.host.getTimeoutSeconds() / 3);
}
// capture current stats from each service
Map<URI, ServiceStats> prevStats = verifyMaintStatsAfterSynchronization(targetServices,
null);
stopHostsAndVerifyQueuing(hostsToStop, remainingHost, targetServices);
// its important to verify document ownership before we do any updates on the services.
// This is because we verify, that even without any on demand synchronization,
// the factory driven synchronization set the services in the proper state
Set<String> ownerIds = this.host.getNodeStateMap().keySet();
List<URI> remainingHosts = new ArrayList<>(this.host.getNodeGroupMap().keySet());
verifyDocumentOwnerAndEpoch(exampleStatesPerSelfLink,
this.host.getInProcessHostMap().values().iterator().next(),
remainingHosts, 0, 1,
ownerIds.size() - 1);
// confirm maintenance is back up and running on all services
verifyMaintStatsAfterSynchronization(targetServices, prevStats);
// nodes are stopped, do updates again, quorum is relaxed, they should work
doExampleServicePatch(exampleStatesPerSelfLink, remainingHost.getUri());
this.host.log("Done with stop nodes and send updates");
}
private void verifyDynamicMaintOptionToggle(Map<String, ExampleServiceState> childStates) {
List<URI> targetServices = new ArrayList<>();
childStates.keySet().forEach((l) -> targetServices.add(this.host.getPeerServiceUri(l)));
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
Map<URI, ServiceConfiguration> configPerService = this.host.getServiceState(
null, ServiceConfiguration.class, targetServiceConfig);
for (ServiceConfiguration cfg : configPerService.values()) {
assertTrue(!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE));
}
for (URI child : targetServices) {
this.host.toggleServiceOptions(child,
EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE),
null);
}
verifyMaintStatsAfterSynchronization(targetServices, null);
}
private Map<URI, ServiceStats> verifyMaintStatsAfterSynchronization(List<URI> targetServices,
Map<URI, ServiceStats> statsPerService) {
List<URI> targetServiceStats = new ArrayList<>();
List<URI> targetServiceConfig = new ArrayList<>();
for (URI child : targetServices) {
targetServiceStats.add(UriUtils.buildStatsUri(child));
targetServiceConfig.add(UriUtils.buildConfigUri(child));
}
if (statsPerService == null) {
statsPerService = new HashMap<>();
}
final Map<URI, ServiceStats> previousStatsPerService = statsPerService;
this.host.waitFor(
"maintenance not enabled",
() -> {
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, targetServiceStats);
for (Entry<URI, ServiceStats> currentEntry : stats.entrySet()) {
ServiceStats previousStats = previousStatsPerService.get(currentEntry
.getKey());
ServiceStats currentStats = currentEntry.getValue();
ServiceStat previousMaintStat = previousStats == null ? new ServiceStat()
: previousStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
double previousValue = previousMaintStat == null ? 0L
: previousMaintStat.latestValue;
ServiceStat maintStat = currentStats.entries
.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null || maintStat.latestValue <= previousValue) {
return false;
}
}
previousStatsPerService.putAll(stats);
return true;
});
return statsPerService;
}
private Map<String, ExampleServiceState> createExampleServices(URI hostUri) throws Throwable {
URI factoryUri = UriUtils.buildUri(hostUri, this.replicationTargetFactoryLink);
this.host.log("POSTing children to %s", hostUri);
// add some services on one of the peers, so we can verify the get synchronized after they all join
Map<URI, ExampleServiceState> exampleStates = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
}, factoryUri);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
for (ExampleServiceState s : exampleStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
return exampleStatesPerSelfLink;
}
@Test
public void synchronizationWithPeerNodeListAndDuplicates() throws Throwable {
ExampleServiceHost h = null;
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
setUp(this.nodeCount);
// the hosts are started, but not joined. We need to relax the quorum for any updates
// to go through
this.host.setNodeGroupQuorum(1);
Map<String, ExampleServiceState> exampleStatesPerSelfLink = new HashMap<>();
// add the *same* service instance, all *all* peers, so we force synchronization and epoch
// change on an instance that exists everywhere
int dupServiceCount = this.serviceCount;
AtomicInteger counter = new AtomicInteger();
Map<URI, ExampleServiceState> dupStates = new HashMap<>();
for (VerificationHost v : this.host.getInProcessHostMap().values()) {
counter.set(0);
URI factoryUri = UriUtils.buildFactoryUri(v,
ExampleService.class);
dupStates = this.host.doFactoryChildServiceStart(
null,
dupServiceCount,
ExampleServiceState.class,
(o) -> {
ExampleServiceState s = new ExampleServiceState();
s.documentSelfLink = "duplicateExampleInstance-"
+ counter.incrementAndGet();
s.name = s.documentSelfLink;
o.setBody(s);
}, factoryUri);
}
for (ExampleServiceState s : dupStates.values()) {
exampleStatesPerSelfLink.put(s.documentSelfLink, s);
}
// increment to account for link found on all nodes
this.serviceCount = exampleStatesPerSelfLink.size();
// create peer argument list, all the nodes join.
Collection<URI> peerNodeGroupUris = new ArrayList<>();
StringBuilder peerNodes = new StringBuilder();
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peerNodeGroupUris.add(UriUtils.buildUri(peer, ServiceUriPaths.DEFAULT_NODE_GROUP));
peerNodes.append(peer.getUri().toString()).append(",");
}
CountDownLatch notifications = new CountDownLatch(this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
this.host.subscribeForNodeGroupConvergence(nodeGroup, this.nodeCount + 1,
(o, e) -> {
if (e != null) {
this.host.log("Error in notificaiton: %s", Utils.toString(e));
return;
}
notifications.countDown();
});
}
// now start a new Host and supply the already created peer, then observe the automatic
// join
h = new ExampleServiceHost();
int quorum = this.host.getPeerCount() + 1;
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--port=0",
"--id=" + mainHostId,
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + peerNodes.toString()
};
h.initialize(args);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
h.start();
URI mainHostNodeGroupUri = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
int totalCount = this.nodeCount + 1;
peerNodeGroupUris.add(mainHostNodeGroupUri);
this.host.waitForNodeGroupIsAvailableConvergence();
this.host.waitForNodeGroupConvergence(peerNodeGroupUris, totalCount,
totalCount, true);
this.host.setNodeGroupQuorum(quorum, mainHostNodeGroupUri);
this.host.setNodeGroupQuorum(quorum);
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
int peerNodeCount = h.getInitialPeerHosts().size();
// include self in peers
assertTrue(totalCount >= peerNodeCount + 1);
// Before factory synch is complete, make sure POSTs to existing services fail,
// since they are not marked idempotent.
verifyReplicatedInConflictPost(dupStates);
// now verify all nodes synchronize and see the example service instances that existed on the single
// host
waitForReplicatedFactoryChildServiceConvergence(
exampleStatesPerSelfLink,
this.exampleStateConvergenceChecker,
this.serviceCount, 0);
// Send some updates after the full group has formed and verify the updates are seen by services on all nodes
doStateUpdateReplicationTest(Action.PATCH, this.serviceCount, this.updateCount, 0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
exampleStatesPerSelfLink);
URI exampleFactoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(exampleFactoryUri, ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
} finally {
this.host.log("test finished");
if (h != null) {
h.stop();
tmpFolder.delete();
}
}
}
private void verifyReplicatedInConflictPost(Map<URI, ExampleServiceState> dupStates)
throws Throwable {
// Its impossible to guarantee that this runs during factory synch. It might run before,
// it might run during, it might run after. Since we runs 1000s of tests per day, CI
// will let us know if the production code works. Here, we add a small sleep so we increase
// chance we overlap with factory synchronization.
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(
this.host.getPeerHost().getMaintenanceIntervalMicros()));
// Issue a POST for a service we know exists and expect failure, since the example service
// is not marked IDEMPOTENT. We expect CONFLICT error code, but if synchronization is active
// we want to confirm we dont get 500, but the 409 is preserved
TestContext ctx = this.host.testCreate(dupStates.size());
for (ExampleServiceState st : dupStates.values()) {
URI factoryUri = this.host.getPeerServiceUri(ExampleService.FACTORY_LINK);
Operation post = Operation.createPost(factoryUri).setBody(st)
.setCompletion((o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
ctx.failIteration(new IllegalStateException(
"Expected conflict status, got " + o.getStatusCode()));
return;
}
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"Expected failure on duplicate POST"));
});
this.host.send(post);
}
this.host.testWait(ctx);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopOnDemandLoad() throws Throwable {
tearDown();
for (int i = 0; i < this.testIterationCount; i++) {
setUpOnDemandLoad();
int hostStopCount = 2;
doReplicationWithQuorumAfterAbruptNodeStop(hostStopCount);
this.host.log("Done with iteration %d", i);
tearDown();
this.host = null;
}
}
private void doReplicationWithQuorumAfterAbruptNodeStop(int hostStopCount)
throws Throwable {
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop minority number of hosts - quorum is still intact
int i = 0;
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(e.getValue());
if (++i >= hostStopCount) {
break;
}
}
// do some updates with strong quorum enabled
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
@Test
public void replicationWithQuorumAfterAbruptNodeStopMultiLocation()
throws Throwable {
// we need 6 nodes, 3 in each location
this.nodeCount = 6;
this.isPeerSynchronizationEnabled = true;
this.skipAvailabilityChecks = true;
this.isMultiLocationTest = true;
if (this.host == null) {
// create node group, join nodes and set local majority quorum
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(2);
}
// create some documents
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
// stop hosts in location "L2"
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
VerificationHost h = e.getValue();
if (h.getLocation().equals(VerificationHost.LOCATION2)) {
this.expectedFailedHosts.add(e.getKey());
this.host.stopHost(h);
}
}
// do some updates
int expectedVersion = this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
/**
* This test validates that if a host, joined in a peer node group, stops/fails and another
* host, listening on the same address:port, rejoins, the existing peer members will mark the
* OLD host instance as FAILED, and mark the new instance, with the new ID as HEALTHY
*
* @throws Throwable
*/
@Test
public void nodeRestartWithSameAddressDifferentId() throws Throwable {
int failedNodeCount = 1;
int afterFailureQuorum = this.nodeCount - failedNodeCount;
setUp(this.nodeCount);
setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(5));
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.log("Stopping node");
// relax quorum for convergence check
this.host.setNodeGroupQuorum(afterFailureQuorum);
// we should now have N nodes, that see each other. Stop one of the
// nodes, and verify the other host's node group deletes the entry
List<ServiceHostState> hostStates = stopHostsToSimulateFailure(failedNodeCount);
URI remainingPeerNodeGroup = this.host.getPeerNodeGroupUri();
// wait for convergence of the remaining peers, before restarting. The failed host
// should be marked FAILED, otherwise we will not converge
this.host.waitForNodeGroupConvergence(this.nodeCount - failedNodeCount);
ServiceHostState stoppedHostState = hostStates.get(0);
// start a new HOST, with a new ID, but with the same address:port as the one we stopped
this.host.testStart(1);
VerificationHost newHost = this.host.setUpLocalPeerHost(stoppedHostState.httpPort,
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null);
this.host.testWait();
// re-join the remaining peers
URI newHostNodeGroupService = UriUtils
.buildUri(newHost.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.joinNodeGroup(newHostNodeGroupService, remainingPeerNodeGroup);
this.host.testWait();
// now wait for convergence. If the logic is correct, the old HOST, that listened on the
// same port as the new host, should stay in the FAILED state, but the new host should
// be marked as HEALTHY
this.host.waitForNodeGroupConvergence(this.nodeCount);
}
public void setMaintenanceIntervalMillis(long defaultMaintIntervalMillis) {
for (VerificationHost h1 : this.host.getInProcessHostMap().values()) {
// set short interval so failure detection and convergence happens quickly
h1.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(defaultMaintIntervalMillis));
}
}
@Test
public void synchronizationRequestQueuing() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(this.nodeCount);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
VerificationHost peerHost = this.host.getPeerHost();
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(peerHost, 1, exampleUris, null);
URI instanceUri = exampleUris.get(0);
ExampleServiceState synchState = new ExampleServiceState();
synchState.documentSelfLink = UriUtils.getLastPathSegment(instanceUri);
TestContext ctx = this.host.testCreate(this.updateCount);
for (int i = 0; i < this.updateCount; i++) {
Operation op = Operation.createPost(peerHost, ExampleService.FACTORY_LINK)
.setBody(synchState)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(op);
}
ctx.await();
}
@Test
public void enforceHighQuorumWithNodeConcurrentStop()
throws Throwable {
int hostRestartCount = 2;
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, null, null);
updateExampleServiceOptions(childStates);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setPeerSynchronizationTimeLimitSeconds(1);
}
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.host.setNodeGroupQuorum((this.nodeCount + 1) / 2);
// do some replication with strong quorum enabled
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
0,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
long now = Utils.getNowMicrosUtc();
validatePerOperationReplicationQuorum(childStates, now);
// expect failure, since we will stop some hosts, break quorum
this.expectFailure = true;
// when quorum is not met the runtime will just queue requests until expiration, so
// we set expiration to something quick. Some requests will make it past queuing
// and will fail because replication quorum is not met
long opTimeoutMicros = TimeUnit.MILLISECONDS.toMicros(500);
setOperationTimeoutMicros(opTimeoutMicros);
int i = 0;
for (URI h : this.host.getInProcessHostMap().keySet()) {
this.expectedFailedHosts.add(h);
if (++i >= hostRestartCount) {
break;
}
}
// stop one host right away
stopHostsToSimulateFailure(1);
// concurrently with the PATCH requests below, stop another host
Runnable r = () -> {
stopHostsToSimulateFailure(hostRestartCount - 1);
// add a small bit of time slop since its feasible a host completed a operation *after* we stopped it,
// the netty handlers are stopped in async (not forced) mode
this.expectedFailureStartTimeMicros = Utils.getNowMicrosUtc()
+ TimeUnit.MILLISECONDS.toMicros(250);
};
this.host.schedule(r, 1, TimeUnit.MILLISECONDS);
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
this.updateCount,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), this.updateCount,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
doStateUpdateReplicationTest(Action.PATCH, childStates.size(), 1,
this.updateCount * 2,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates);
}
private void validatePerOperationReplicationQuorum(Map<String, ExampleServiceState> childStates,
long now) throws Throwable {
Random r = new Random();
// issue a patch, with per operation quorum set, verify it applied
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.setCompletion(ctx.getCompletion())
.setBody(body);
// add an explicit replication count header, using either the "all" value, or an
// explicit node count
if (r.nextBoolean()) {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
} else {
patch.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
this.nodeCount + "");
}
this.host.send(patch);
this.host.testWait(ctx);
// Go to each peer, directly to their index, and verify update is present. This is not
// proof the per operation quorum was applied "synchronously", before the response
// was sent, but over many runs, if there is a race or its applied asynchronously,
// we will see failures
for (URI hostBaseUri : this.host.getNodeGroupMap().keySet()) {
URI indexUri = UriUtils.buildUri(hostBaseUri, ServiceUriPaths.CORE_DOCUMENT_INDEX);
indexUri = UriUtils.buildIndexQueryUri(indexUri,
e.getKey(), true, false, ServiceOption.PERSISTENCE);
ExampleServiceState afterState = this.host.getServiceState(null,
ExampleServiceState.class, indexUri);
assertEquals(body.counter, afterState.counter);
}
}
this.host.toggleNegativeTestMode(true);
// verify that if we try to set per operation quorum too high, request will fail
for (Entry<String, ExampleServiceState> e : childStates.entrySet()) {
TestContext ctx = this.host.testCreate(1);
ExampleServiceState body = e.getValue();
body.counter = now;
Operation patch = Operation.createPatch(this.host.getPeerServiceUri(e.getKey()))
.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
(this.nodeCount * 2) + "")
.setCompletion(ctx.getExpectedFailureCompletion())
.setBody(body);
this.host.send(patch);
this.host.testWait(ctx);
break;
}
this.host.toggleNegativeTestMode(false);
}
private void setOperationTimeoutMicros(long opTimeoutMicros) {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.setOperationTimeOutMicros(opTimeoutMicros);
}
this.host.setOperationTimeOutMicros(opTimeoutMicros);
}
/**
* This test creates N local service hosts, each with K instances of a replicated service. The
* service will create a query task, also replicated, and self patch itself. The test makes sure
* all K instances, on all N hosts see the self PATCHs AND that the query tasks exist on all
* hosts
*
* @throws Throwable
*/
@Test
public void replicationWithCrossServiceDependencies() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI hostUri = this.host.getPeerServiceUri(null);
URI factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri,
ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> ownerSelectedServices = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
factoryUri = UriUtils.buildUri(hostUri, ReplicationFactoryTestService.STRICT_SELF_LINK);
doReplicatedServiceFactoryPost(this.serviceCount, setBodyCallback, factoryUri);
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
Query kindClause = new Query();
kindClause.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ReplicationTestServiceState.class));
q.query.addBooleanClause(kindClause);
Query nameClause = new Query();
nameClause.setTermPropertyName("stringField")
.setTermMatchValue("*")
.setTermMatchType(MatchType.WILDCARD);
q.query.addBooleanClause(nameClause);
// expect results for strict and regular service instances
int expectedServiceCount = this.serviceCount * 3;
Date exp = this.host.getTestExpiration();
while (exp.after(new Date())) {
// create N direct query tasks. Direct tasks complete in the context of the POST to the
// query task factory
int count = 10;
URI queryFactoryUri = UriUtils.extendUri(hostUri,
ServiceUriPaths.CORE_QUERY_TASKS);
TestContext testContext = this.host.testCreate(count);
Map<String, QueryTask> taskResults = new ConcurrentSkipListMap<>();
for (int i = 0; i < count; i++) {
QueryTask qt = QueryTask.create(q);
qt.taskInfo.isDirect = true;
qt.documentSelfLink = UUID.randomUUID().toString();
Operation startPost = Operation
.createPost(queryFactoryUri)
.setBody(qt)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
QueryTask rsp = o.getBody(QueryTask.class);
qt.results = rsp.results;
qt.documentOwner = rsp.documentOwner;
taskResults.put(rsp.documentSelfLink, qt);
testContext.complete();
});
this.host.send(startPost);
}
testContext.await();
this.host.logThroughput();
boolean converged = true;
for (QueryTask qt : taskResults.values()) {
if (qt.results == null || qt.results.documentLinks == null) {
throw new IllegalStateException("Missing results");
}
if (qt.results.documentLinks.size() != expectedServiceCount) {
this.host.log("%s", Utils.toJsonHtml(qt));
converged = false;
break;
}
}
if (!converged) {
Thread.sleep(250);
continue;
}
break;
}
if (exp.before(new Date())) {
throw new TimeoutException();
}
// Negative tests: Make sure custom error response body is preserved
URI childUri = ownerSelectedServices.keySet().iterator().next();
TestContext testContext = this.host.testCreate(1);
ReplicationTestServiceState badRequestBody = new ReplicationTestServiceState();
this.host
.send(Operation
.createPatch(childUri)
.setBody(badRequestBody)
.setCompletion(
(o, e) -> {
if (e == null) {
testContext.fail(new IllegalStateException(
"Expected failure"));
return;
}
ReplicationTestServiceErrorResponse rsp = o
.getBody(ReplicationTestServiceErrorResponse.class);
if (!ReplicationTestServiceErrorResponse.KIND
.equals(rsp.documentKind)) {
testContext.fail(new IllegalStateException(
"Expected custom response body"));
return;
}
testContext.complete();
}));
testContext.await();
// verify that each owner selected service reports stats from the same node that reports state
Map<URI, ReplicationTestServiceState> latestState = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
Map<String, String> ownerIdPerLink = new HashMap<>();
List<URI> statsUris = new ArrayList<>();
for (ReplicationTestServiceState state : latestState.values()) {
URI statsUri = this.host.getPeerServiceUri(UriUtils.buildUriPath(
state.documentSelfLink, ServiceHost.SERVICE_URI_SUFFIX_STATS));
ownerIdPerLink.put(state.documentSelfLink, state.documentOwner);
statsUris.add(statsUri);
}
Map<URI, ServiceStats> latestStats = this.host.getServiceState(null, ServiceStats.class,
statsUris);
for (ServiceStats perServiceStats : latestStats.values()) {
String serviceLink = UriUtils.getParentPath(perServiceStats.documentSelfLink);
String expectedOwnerId = ownerIdPerLink.get(serviceLink);
if (expectedOwnerId.equals(perServiceStats.documentOwner)) {
continue;
}
throw new IllegalStateException("owner routing issue with stats: "
+ Utils.toJsonHtml(perServiceStats));
}
exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
// verify all factories report same number of children
for (VerificationHost peerHost : this.host.getInProcessHostMap().values()) {
factoryUri = UriUtils.buildUri(peerHost,
ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK);
ServiceDocumentQueryResult rsp = this.host.getFactoryState(factoryUri);
if (rsp.documentLinks.size() != latestState.size()) {
this.host.log("Factory %s reporting %d children, expected %d", factoryUri,
rsp.documentLinks.size(), latestState.size());
isConverged = false;
break;
}
}
if (!isConverged) {
Thread.sleep(250);
continue;
}
break;
}
if (new Date().after(exp)) {
throw new TimeoutException("factories did not converge");
}
this.host.log("Inducing synchronization");
// Induce synchronization on stable node group. No changes should be observed since
// all nodes should have identical state
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
// give synchronization a chance to run, its 100% asynchronous so we can't really tell when each
// child is done, but a small delay should be sufficient for 99.9% of test environments, even under
// load
Thread.sleep(2000);
// verify that example states did not change due to the induced synchronization
Map<URI, ReplicationTestServiceState> latestStateAfter = this.host.getServiceState(null,
ReplicationTestServiceState.class, ownerSelectedServices.keySet());
for (Entry<URI, ReplicationTestServiceState> afterEntry : latestStateAfter.entrySet()) {
ReplicationTestServiceState beforeState = latestState.get(afterEntry.getKey());
ReplicationTestServiceState afterState = afterEntry.getValue();
assertEquals(beforeState.documentVersion, afterState.documentVersion);
}
verifyOperationJoinAcrossPeers(latestStateAfter);
}
private Map<URI, ReplicationTestServiceState> doReplicatedServiceFactoryPost(int serviceCount,
Consumer<Operation> setBodyCallback, URI factoryUri) throws Throwable,
InterruptedException, TimeoutException {
ServiceDocumentDescription sdd = this.host
.buildDescription(ReplicationTestServiceState.class);
Map<URI, ReplicationTestServiceState> serviceMap = this.host.doFactoryChildServiceStart(
null, serviceCount, ReplicationTestServiceState.class, setBodyCallback, factoryUri);
Date expiration = this.host.getTestExpiration();
boolean isConverged = true;
Map<URI, String> uriToSignature = new HashMap<>();
while (new Date().before(expiration)) {
isConverged = true;
uriToSignature.clear();
for (Entry<URI, VerificationHost> e : this.host.getInProcessHostMap().entrySet()) {
URI baseUri = e.getKey();
VerificationHost h = e.getValue();
URI u = UriUtils.buildUri(baseUri, factoryUri.getPath());
u = UriUtils.buildExpandLinksQueryUri(u);
ServiceDocumentQueryResult r = this.host.getFactoryState(u);
if (r.documents.size() != serviceCount) {
this.host.log("instance count mismatch, expected %d, got %d, from %s",
serviceCount, r.documents.size(), u);
isConverged = false;
break;
}
for (URI instanceUri : serviceMap.keySet()) {
ReplicationTestServiceState initialState = serviceMap.get(instanceUri);
ReplicationTestServiceState newState = Utils.fromJson(
r.documents.get(instanceUri.getPath()),
ReplicationTestServiceState.class);
if (newState.documentVersion == 0) {
this.host.log("version mismatch, expected %d, got %d, from %s", 0,
newState.documentVersion, instanceUri);
isConverged = false;
break;
}
if (initialState.stringField.equals(newState.stringField)) {
this.host.log("field mismatch, expected %s, got %s, from %s",
initialState.stringField, newState.stringField, instanceUri);
isConverged = false;
break;
}
if (newState.queryTaskLink == null) {
this.host.log("missing query task link from %s", instanceUri);
isConverged = false;
break;
}
// Only instances with OWNER_SELECTION patch string field with self link so bypass this check
if (!newState.documentSelfLink
.contains(ReplicationFactoryTestService.STRICT_SELF_LINK)
&& !newState.documentSelfLink
.contains(ReplicationFactoryTestService.SIMPLE_REPL_SELF_LINK)
&& !newState.stringField.equals(newState.documentSelfLink)) {
this.host.log("State not in final state");
isConverged = false;
break;
}
String sig = uriToSignature.get(instanceUri);
if (sig == null) {
sig = Utils.computeSignature(newState, sdd);
uriToSignature.put(instanceUri, sig);
} else {
String newSig = Utils.computeSignature(newState, sdd);
if (!sig.equals(newSig)) {
isConverged = false;
this.host.log("signature mismatch, expected %s, got %s, from %s",
sig, newSig, instanceUri);
}
}
ProcessingStage ps = h.getServiceStage(newState.queryTaskLink);
if (ps == null || ps != ProcessingStage.AVAILABLE) {
this.host.log("missing query task service from %s", newState.queryTaskLink,
instanceUri);
isConverged = false;
break;
}
}
if (isConverged == false) {
break;
}
}
if (isConverged == true) {
break;
}
Thread.sleep(100);
}
if (!isConverged) {
throw new TimeoutException("States did not converge");
}
return serviceMap;
}
@Test
public void replicationWithOutOfOrderPostAndUpdates() throws Throwable {
// This test verifies that if a replica receives
// replication requests of POST and PATCH/PUT
// out-of-order, xenon can still handle it
// by doing retries for failed out-of-order
// updates. To verify this, we setup a node
// group and set quorum to just 1, so that the post
// returns as soon as the owner commits the post,
// so that we increase the chance of out-of-order
// update replication requests.
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
this.host.setNodeGroupQuorum(1);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicationFactoryConvergence();
ExampleServiceState state = new ExampleServiceState();
state.name = "testing";
state.counter = 1L;
VerificationHost peer = this.host.getPeerHost();
TestContext ctx = this.host.testCreate(this.serviceCount * this.updateCount);
for (int i = 0; i < this.serviceCount; i++) {
Operation post = Operation
.createPost(peer, ExampleService.FACTORY_LINK)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
for (int k = 0; k < this.updateCount; k++) {
ExampleServiceState update = new ExampleServiceState();
state.counter = (long) k;
Operation patch = Operation
.createPatch(peer, rsp.documentSelfLink)
.setBody(update)
.setReferer(this.host.getUri())
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
});
this.host.sendRequest(post);
}
ctx.await();
}
@Test
public void replication() throws Throwable {
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replicationSsl() throws Throwable {
this.replicationUriScheme = ServiceHost.HttpScheme.HTTPS_ONLY;
this.replicationTargetFactoryLink = ExampleService.FACTORY_LINK;
doReplication();
}
@Test
public void replication1x() throws Throwable {
this.replicationFactor = 1L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication1xExampleFactoryService.SELF_LINK;
doReplication();
}
@Test
public void replication3x() throws Throwable {
this.replicationFactor = 3L;
this.replicationNodeSelector = ServiceUriPaths.DEFAULT_3X_NODE_SELECTOR;
this.replicationTargetFactoryLink = Replication3xExampleFactoryService.SELF_LINK;
this.nodeCount = Math.max(5, this.nodeCount);
doReplication();
}
private void doReplication() throws Throwable {
this.isPeerSynchronizationEnabled = false;
CommandLineArgumentParser.parseFromProperties(this);
Date expiration = new Date();
if (this.testDurationSeconds > 0) {
expiration = new Date(expiration.getTime()
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
}
Map<Action, Long> elapsedTimePerAction = new HashMap<>();
Map<Action, Long> countPerAction = new HashMap<>();
long totalOperations = 0;
int iterationCount = 0;
do {
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// for limited replication factor, we will still set the quorum high, and expect
// the limited replication selector to use the minimum between majority of replication
// factor, versus node group membership quorum
this.host.setNodeGroupQuorum(this.nodeCount);
// since we have disabled peer synch, trigger it explicitly so factories become available
this.host.scheduleSynchronizationIfAutoSyncDisabled(this.replicationNodeSelector);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
waitForReplicationFactoryConvergence();
if (this.replicationUriScheme == ServiceHost.HttpScheme.HTTPS_ONLY) {
// confirm nodes are joined using HTTPS group references
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
assertTrue(UriUtils.HTTPS_SCHEME.equals(nodeGroup.getScheme()));
}
}
}
Map<String, ExampleServiceState> childStates = doExampleFactoryPostReplicationTest(
this.serviceCount, countPerAction, elapsedTimePerAction);
totalOperations += this.serviceCount;
if (this.testDurationSeconds == 0) {
// various validation tests, executed just once, ignored in long running test
this.host.doExampleServiceUpdateAndQueryByVersion(this.host.getPeerHostUri(),
this.serviceCount);
verifyReplicatedForcedPostAfterDelete(childStates);
verifyInstantNotFoundFailureOnBadLinks();
verifyReplicatedIdempotentPost(childStates);
verifyDynamicMaintOptionToggle(childStates);
}
totalOperations += this.serviceCount;
if (expiration == null) {
expiration = this.host.getTestExpiration();
}
int expectedVersion = this.updateCount;
if (!this.host.isStressTest()
&& (this.host.getPeerCount() > 16
|| this.serviceCount * this.updateCount > 100)) {
this.host.setStressTest(true);
}
long opCount = this.serviceCount * this.updateCount;
childStates = doStateUpdateReplicationTest(Action.PATCH, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
expectedVersion += this.updateCount;
totalOperations += opCount;
childStates = doStateUpdateReplicationTest(Action.PUT, this.serviceCount,
this.updateCount,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += opCount;
Date queryExp = this.host.getTestExpiration();
if (expiration.after(queryExp)) {
queryExp = expiration;
}
while (new Date().before(queryExp)) {
Set<String> links = verifyReplicatedServiceCountWithBroadcastQueries();
if (links.size() < this.serviceCount) {
this.host.log("Found only %d links across nodes, retrying", links.size());
Thread.sleep(500);
continue;
}
break;
}
totalOperations += this.serviceCount;
if (queryExp.before(new Date())) {
throw new TimeoutException();
}
expectedVersion += 1;
doStateUpdateReplicationTest(Action.DELETE, this.serviceCount, 1,
expectedVersion,
this.exampleStateUpdateBodySetter,
this.exampleStateConvergenceChecker,
childStates,
countPerAction,
elapsedTimePerAction);
totalOperations += this.serviceCount;
// compute the binary serialized payload, and the JSON payload size
ExampleServiceState st = childStates.values().iterator().next();
String json = Utils.toJson(st);
int byteCount = KryoSerializers.serializeDocument(st, 4096).position();
int jsonByteCount = json.getBytes(Utils.CHARSET).length;
// estimate total bytes transferred between nodes. The owner receives JSON from the client
// but then uses binary serialization to the N-1 replicas
long totalBytes = jsonByteCount * totalOperations
+ (this.nodeCount - 1) * byteCount * totalOperations;
this.host.log(
"Bytes per json:%d, per binary: %d, Total operations: %d, Total bytes:%d",
jsonByteCount,
byteCount,
totalOperations,
totalBytes);
if (iterationCount++ < 2 && this.testDurationSeconds > 0) {
// ignore data during JVM warm-up, first two iterations
countPerAction.clear();
elapsedTimePerAction.clear();
}
} while (new Date().before(expiration) && this.totalOperationLimit > totalOperations);
logHostStats();
logPerActionThroughput(elapsedTimePerAction, countPerAction);
this.host.doNodeGroupStatsVerification(this.host.getNodeGroupMap());
}
private void logHostStats() {
for (URI u : this.host.getNodeGroupMap().keySet()) {
URI mgmtUri = UriUtils.buildUri(u, ServiceHostManagementService.SELF_LINK);
mgmtUri = UriUtils.buildStatsUri(mgmtUri);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, mgmtUri);
this.host.log("%s: %s", u, Utils.toJsonHtml(stats));
}
}
private void logPerActionThroughput(Map<Action, Long> elapsedTimePerAction,
Map<Action, Long> countPerAction) {
for (Action a : EnumSet.allOf(Action.class)) {
Long count = countPerAction.get(a);
if (count == null) {
continue;
}
Long elapsedMicros = elapsedTimePerAction.get(a);
double thpt = (count * 1.0) / (1.0 * elapsedMicros);
thpt *= 1000000;
this.host.log("Total ops for %s: %d, Throughput (ops/sec): %f", a, count, thpt);
}
}
private void updatePerfDataPerAction(Action a, Long startTime, Long opCount,
Map<Action, Long> countPerAction, Map<Action, Long> elapsedTime) {
if (opCount == null || countPerAction != null) {
countPerAction.merge(a, opCount, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
if (startTime == null || elapsedTime == null) {
return;
}
long delta = Utils.getNowMicrosUtc() - startTime;
elapsedTime.merge(a, delta, (e, n) -> {
if (e == null) {
return n;
}
return e + n;
});
}
private void verifyReplicatedIdempotentPost(Map<String, ExampleServiceState> childStates)
throws Throwable {
// verify IDEMPOTENT POST conversion to PUT, with replication
// Since the factory is not idempotent by default, enable the option dynamically
Map<URI, URI> exampleFactoryUris = this.host
.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK);
for (URI factoryUri : exampleFactoryUris.values()) {
this.host.toggleServiceOptions(factoryUri,
EnumSet.of(ServiceOption.IDEMPOTENT_POST), null);
}
TestContext ctx = this.host.testCreate(childStates.size());
for (Entry<String, ExampleServiceState> entry : childStates.entrySet()) {
Operation post = Operation
.createPost(this.host.getPeerServiceUri(ExampleService.FACTORY_LINK))
.setBody(entry.getValue())
.setCompletion(ctx.getCompletion());
this.host.send(post);
}
ctx.await();
}
/**
* Verifies that DELETE actions propagate and commit, and, that forced POST actions succeed
*/
private void verifyReplicatedForcedPostAfterDelete(Map<String, ExampleServiceState> childStates)
throws Throwable {
// delete one of the children, then re-create but with a zero version, using a special
// directive that forces creation
Entry<String, ExampleServiceState> childEntry = childStates.entrySet().iterator().next();
TestContext ctx = this.host.testCreate(1);
Operation delete = Operation
.createDelete(this.host.getPeerServiceUri(childEntry.getKey()))
.setCompletion(ctx.getCompletion());
this.host.send(delete);
ctx.await();
if (!this.host.isRemotePeerTest()) {
this.host.waitFor("services not deleted", () -> {
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(childEntry.getKey());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
childEntry.getKey(), h.toString(), stg);
return false;
}
}
return true;
});
}
TestContext postCtx = this.host.testCreate(1);
Operation opPost = Operation
.createPost(this.host.getPeerServiceUri(this.replicationTargetFactoryLink))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE)
.setBody(childEntry.getValue())
.setCompletion((o, e) -> {
if (e != null) {
postCtx.failIteration(e);
} else {
postCtx.completeIteration();
}
});
this.host.send(opPost);
this.host.testWait(postCtx);
}
private void waitForReplicationFactoryConvergence() throws Throwable {
// for code coverage, verify the convenience method on the host also reports available
WaitHandler wh = () -> {
TestContext ctx = this.host.testCreate(1);
boolean[] isReady = new boolean[1];
CompletionHandler ch = (o, e) -> {
if (e != null) {
isReady[0] = false;
} else {
isReady[0] = true;
}
ctx.completeIteration();
};
VerificationHost peerHost = this.host.getPeerHost();
if (peerHost == null) {
NodeGroupUtils.checkServiceAvailability(ch, this.host,
this.host.getPeerServiceUri(this.replicationTargetFactoryLink),
this.replicationNodeSelector);
} else {
peerHost.checkReplicatedServiceAvailable(ch, this.replicationTargetFactoryLink);
}
ctx.await();
return isReady[0];
};
this.host.waitFor("available check timeout for " + this.replicationTargetFactoryLink, wh);
}
private Set<String> verifyReplicatedServiceCountWithBroadcastQueries()
throws Throwable {
// create a query task, which will execute on a randomly selected node. Since there is no guarantee the node
// selected to execute the query task is the one with all the replicated services, broadcast to all nodes, then
// join the results
URI nodeUri = this.host.getPeerHostUri();
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND).setTermMatchValue(
Utils.buildKind(ExampleServiceState.class));
QueryTask task = QueryTask.create(q).setDirect(true);
URI queryTaskFactoryUri = UriUtils
.buildUri(nodeUri, ServiceUriPaths.CORE_LOCAL_QUERY_TASKS);
// send the POST to the forwarding service on one of the nodes, with the broadcast query parameter set
URI forwardingService = UriUtils.buildBroadcastRequestUri(queryTaskFactoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
Set<String> links = new HashSet<>();
TestContext testContext = this.host.testCreate(1);
Operation postQuery = Operation
.createPost(forwardingService)
.setBody(task)
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
NodeGroupBroadcastResponse rsp = o
.getBody(NodeGroupBroadcastResponse.class);
NodeGroupBroadcastResult broadcastResponse = NodeGroupUtils.toBroadcastResult(rsp);
if (broadcastResponse.hasFailure()) {
testContext.fail(new IllegalStateException(
"Failure from query tasks: " + Utils.toJsonHtml(rsp)));
return;
}
// verify broadcast requests should come from all discrete nodes
Set<String> ownerIds = new HashSet<>();
for (PeerNodeResult successResponse : broadcastResponse.successResponses) {
QueryTask qt = successResponse.castBodyTo(QueryTask.class);
this.host.log("Broadcast response from %s %s", qt.documentSelfLink,
qt.documentOwner);
ownerIds.add(qt.documentOwner);
if (qt.results == null) {
this.host.log("Node %s had no results", successResponse.requestUri);
continue;
}
for (String l : qt.results.documentLinks) {
links.add(l);
}
}
testContext.completeIteration();
});
this.host.send(postQuery);
testContext.await();
return links;
}
private void verifyInstantNotFoundFailureOnBadLinks() throws Throwable {
this.host.toggleNegativeTestMode(true);
TestContext testContext = this.host.testCreate(this.serviceCount);
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.complete();
return;
}
// strange, service exists, lets verify
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
ProcessingStage stg = h.getServiceStage(o.getUri().getPath());
if (stg != null) {
this.host.log("Service exists %s on host %s, stage %s",
o.getUri().getPath(), h.toString(), stg);
}
}
testContext.fail(new Throwable("Expected service to not exist:"
+ o.toString()));
};
// do a negative test: send request to a example child we know does not exist, but disable queuing
// so we get 404 right away
for (int i = 0; i < this.serviceCount; i++) {
URI factoryURI = this.host.getNodeGroupToFactoryMap(ExampleService.FACTORY_LINK)
.values().iterator().next();
URI bogusChild = UriUtils.extendUri(factoryURI,
Utils.getNowMicrosUtc() + UUID.randomUUID().toString());
Operation patch = Operation.createPatch(bogusChild)
.setCompletion(c)
.setBody(new ExampleServiceState());
this.host.send(patch);
}
testContext.await();
this.host.toggleNegativeTestMode(false);
}
@Test
public void factorySynchronization() throws Throwable {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
factorySynchronizationNoChildren();
factoryDuplicatePost();
}
@Test
public void replicationWithAuthzCacheClear() throws Throwable {
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.setNodeGroupQuorum(this.nodeCount);
VerificationHost groupHost = this.host.getPeerHost();
// wait for auth related services to be stabilized
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, UserGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, ResourceGroupService.FACTORY_LINK));
groupHost.waitForReplicatedFactoryServiceAvailable(
UriUtils.buildUri(groupHost, RoleService.FACTORY_LINK));
String fooUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"foo@vmware.com");
String barUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"bar@vmware.com");
String bazUserLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS,
"baz@vmware.com");
groupHost.setSystemAuthorizationContext();
// create user, user-group, resource-group, role for foo@vmware.com
// user: /core/authz/users/foo@vmware.com
// user-group: /core/authz/user-groups/foo-user-group
// resource-group: /core/authz/resource-groups/foo-resource-group
// role: /core/authz/roles/foo-role-1
TestContext testContext = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("foo@vmware.com")
.setUserEmail("foo@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setUserGroupName("foo-user-group")
.setResourceGroupName("foo-resource-group")
.setRoleName("foo-role-1")
.setCompletion(testContext.getCompletion())
.start();
testContext.await();
// create another user-group, resource-group, and role for foo@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: /core/authz/role/foo-role-2
TestContext ctxToCreateAnotherRole = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(fooUserLink)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setRoleName("foo-role-2")
.setCompletion(ctxToCreateAnotherRole.getCompletion())
.setupRole();
ctxToCreateAnotherRole.await();
// create user, user-group, resource-group, role for bar@vmware.com
// user: /core/authz/users/bar@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("bar@vmware.com")
.setUserEmail("bar@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBar.getCompletion())
.start();
ctxToCreateBar.await();
// create user, user-group, resource-group, role for baz@vmware.com
// user: /core/authz/users/baz@vmware.com
// user-group: (not important)
// resource-group: (not important)
// role: (not important)
TestContext ctxToCreateBaz = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink("baz@vmware.com")
.setUserEmail("baz@vmware.com")
.setUserPassword("password")
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(ctxToCreateBaz.getCompletion())
.start();
ctxToCreateBaz.await();
AuthorizationContext fooAuthContext = groupHost.assumeIdentity(fooUserLink);
AuthorizationContext barAuthContext = groupHost.assumeIdentity(barUserLink);
AuthorizationContext bazAuthContext = groupHost.assumeIdentity(bazUserLink);
String fooToken = fooAuthContext.getToken();
String barToken = barAuthContext.getToken();
String bazToken = bazAuthContext.getToken();
groupHost.resetSystemAuthorizationContext();
// verify GET will NOT clear cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/users/foo@vmware.com")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/resource-groups/foo-resource-group")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createGet(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
checkCacheInAllPeers(fooToken, true);
// verify deleting role should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/roles/foo-role-1")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user-group should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
// delete the user group associated with the user
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(
UriUtils.buildUri(groupHost, "/core/authz/user-groups/foo-user-group")));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify creating new role should clear the auth cache (using bar@vmware.com)
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
Query q = Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.build();
TestContext ctxToCreateAnotherRoleForBar = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(groupHost)
.setUserSelfLink(barUserLink)
.setResourceGroupName("/core/authz/resource-groups/new-rg")
.setResourceQuery(q)
.setRoleName("bar-role-2")
.setCompletion(ctxToCreateAnotherRoleForBar.getCompletion())
.setupRole();
ctxToCreateAnotherRoleForBar.await();
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
//
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
// Updating the resource group should be able to handle the fact that the user group does not exist
String newResourceGroupLink = "/core/authz/resource-groups/new-rg";
Query updateResourceGroupQuery = Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.query = updateResourceGroupQuery;
this.host.sendAndWaitExpectSuccess(
Operation.createPut(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(resourceGroupState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
// verify patching user should clear the auth cache
populateAuthCacheInAllPeers(fooAuthContext);
groupHost.setSystemAuthorizationContext();
UserState userState = new UserState();
userState.userGroupLinks = new HashSet<>();
userState.userGroupLinks.add("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, fooUserLink))
.setBody(userState));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(fooToken);
// verify deleting user should clear the auth cache
populateAuthCacheInAllPeers(bazAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(groupHost, bazUserLink)));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(bazToken);
// verify patching ResourceGroup should clear the auth cache
// uses "new-rg" resource group that has associated to user bar
TestRequestSender sender = new TestRequestSender(this.host.getPeerHost());
groupHost.setSystemAuthorizationContext();
Operation newResourceGroupGetOp = Operation.createGet(groupHost, newResourceGroupLink);
ResourceGroupState newResourceGroupState = sender.sendAndWait(newResourceGroupGetOp, ResourceGroupState.class);
groupHost.resetSystemAuthorizationContext();
PatchQueryRequest patchBody = PatchQueryRequest.create(newResourceGroupState.query, false);
populateAuthCacheInAllPeers(barAuthContext);
groupHost.setSystemAuthorizationContext();
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(groupHost, newResourceGroupLink))
.setBody(patchBody));
groupHost.resetSystemAuthorizationContext();
verifyAuthCacheHasClearedInAllPeers(barToken);
}
private void populateAuthCacheInAllPeers(AuthorizationContext authContext) throws Throwable {
// send a GET request to the ExampleService factory to populate auth cache on each peer.
// since factory is not OWNER_SELECTION service, request goes to the specified node.
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setAuthorizationContext(authContext);
// based on the role created in test, all users have access to ExampleService
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildStatsUri(peer, ExampleService.FACTORY_LINK)));
}
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(authContext.getToken(), true));
}
private void verifyAuthCacheHasClearedInAllPeers(String userToken) {
this.host.waitFor("Timeout waiting for correct auth cache state",
() -> checkCacheInAllPeers(userToken, false));
}
private boolean checkCacheInAllPeers(String token, boolean expectEntries) throws Throwable {
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
peer.setSystemAuthorizationContext();
MinimalTestService s = new MinimalTestService();
peer.addPrivilegedService(MinimalTestService.class);
peer.startServiceAndWait(s, UUID.randomUUID().toString(), null);
peer.resetSystemAuthorizationContext();
boolean contextFound = peer.getAuthorizationContext(s, token) != null;
if ((expectEntries && !contextFound) || (!expectEntries && contextFound)) {
return false;
}
}
return true;
}
private void factoryDuplicatePost() throws Throwable, InterruptedException, TimeoutException {
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
Consumer<Operation> setBodyCallback = (o) -> {
ReplicationTestServiceState s = new ReplicationTestServiceState();
s.stringField = UUID.randomUUID().toString();
o.setBody(s);
};
URI factoryUri = this.host
.getPeerServiceUri(ReplicationFactoryTestService.OWNER_SELECTION_SELF_LINK);
Map<URI, ReplicationTestServiceState> states = doReplicatedServiceFactoryPost(
this.serviceCount, setBodyCallback, factoryUri);
TestContext testContext = serviceHost.testCreate(states.size());
ReplicationTestServiceState initialState = new ReplicationTestServiceState();
for (URI uri : states.keySet()) {
initialState.documentSelfLink = uri.toString().substring(uri.toString()
.lastIndexOf(UriUtils.URI_PATH_CHAR) + 1);
Operation createPost = Operation
.createPost(factoryUri)
.setBody(initialState)
.setCompletion(
(o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_CONFLICT) {
testContext.fail(
new IllegalStateException(
"Incorrect response code received"));
return;
}
testContext.complete();
});
serviceHost.send(createPost);
}
testContext.await();
}
private void factorySynchronizationNoChildren() throws Throwable {
int factoryCount = Math.max(this.serviceCount, 25);
setUp(this.nodeCount);
// start many factories, in each host, so when the nodes join there will be a storm
// of synchronization requests between the nodes + factory instances
TestContext testContext = this.host.testCreate(this.nodeCount * factoryCount);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
for (int i = 0; i < factoryCount; i++) {
Operation startPost = Operation.createPost(
UriUtils.buildUri(h,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, UUID
.randomUUID().toString())))
.setCompletion(testContext.getCompletion());
h.startService(startPost, ExampleService.createFactory());
}
}
testContext.await();
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
@Test
public void forwardingAndSelection() throws Throwable {
this.isPeerSynchronizationEnabled = false;
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
for (int i = 0; i < this.iterationCount; i++) {
directOwnerSelection();
forwardingToPeerId();
forwardingToKeyHashNode();
broadcast();
}
}
public void broadcast() throws Throwable {
// Do a broadcast on a local, non replicated service. Replicated services can not
// be used with broadcast since they will duplicate the update and potentially route
// to a single node
URI nodeGroup = this.host.getPeerNodeGroupUri();
long c = this.updateCount * this.nodeCount;
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
// we broadcast one update, per service, through one peer. We expect to see
// the same update across all peers, just like with replicated services
nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildBroadcastRequestUri(serviceUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
for (URI baseHostUri : this.host.getNodeGroupMap().keySet()) {
List<URI> uris = new ArrayList<>();
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(baseHostUri, s.documentSelfLink);
uris.add(serviceUri);
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service broadcast failure");
}
}
}
}
public void forwardingToKeyHashNode() throws Throwable {
long c = this.updateCount * this.nodeCount;
Map<String, List<String>> ownersPerServiceLink = new HashMap<>();
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to owner, per service link
// 2) verify the request ended up on the owner the partitioning service predicted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
URI nodeGroup = this.host.getPeerNodeGroupUri();
testContext = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
URI serviceUri = UriUtils.buildUri(nodeGroup, s.documentSelfLink);
URI u = UriUtils.buildForwardRequestUri(serviceUri,
null,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = serviceUri.getPath();
this.host.send(Operation.createPut(u)
.setCompletion(testContext.getCompletion())
.setBody(body));
}
testContext.await();
this.host.logThroughput();
AtomicInteger assignedLinks = new AtomicInteger();
TestContext testContextForPost = this.host.testCreate(initialStates.size());
for (ServiceDocument s : initialStates) {
// make sure the key is the path to the service. The initial state self link is not a
// path ...
String key = UriUtils.normalizeUriPath(s.documentSelfLink);
s.documentSelfLink = key;
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion((o, e) -> {
if (e != null) {
testContextForPost.fail(e);
return;
}
synchronized (ownersPerServiceLink) {
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
List<String> links = ownersPerServiceLink.get(rsp.ownerNodeId);
if (links == null) {
links = new ArrayList<>();
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
links.add(key);
ownersPerServiceLink.put(rsp.ownerNodeId, links);
}
assignedLinks.incrementAndGet();
testContextForPost.complete();
});
this.host.send(post);
}
testContextForPost.await();
assertTrue(assignedLinks.get() == initialStates.size());
// verify the services on the node that should be owner, has modified state
for (Entry<String, List<String>> e : ownersPerServiceLink.entrySet()) {
String nodeId = e.getKey();
List<String> links = e.getValue();
NodeState ns = this.host.getNodeStateMap().get(nodeId);
List<URI> uris = new ArrayList<>();
// make a list of URIs to the services assigned to this peer node
for (String l : links) {
uris.add(UriUtils.buildUri(ns.groupReference, l));
}
Map<URI, MinimalTestServiceState> states = this.host.getServiceState(null,
MinimalTestServiceState.class, uris);
for (MinimalTestServiceState s : states.values()) {
// the PUT we issued, should have been forwarded to this service and modified its
// initial ID to be the same as the self link
if (!s.id.equals(s.documentSelfLink)) {
throw new IllegalStateException("Service forwarding failure");
} else {
}
}
}
}
public void forwardingToPeerId() throws Throwable {
long c = this.updateCount * this.nodeCount;
// 0) Create N service instances, in each peer host. Services are NOT replicated
// 1) issue a forward request to a specific peer id, per service link
// 2) verify the request ended up on the peer we targeted
List<ServiceDocument> initialStates = new ArrayList<>();
for (int i = 0; i < c; i++) {
ServiceDocument s = this.host.buildMinimalTestState();
s.documentSelfLink = UUID.randomUUID().toString();
initialStates.add(s);
}
TestContext testContext = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
s = Utils.clone(s);
// set the owner to be the target node. we will use this to verify it matches
// the id in the state, which is set through a forwarded PATCH
s.documentOwner = peer.getId();
Operation post = Operation.createPost(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(testContext.getCompletion())
.setBody(s);
peer.startService(post, new MinimalTestService());
}
}
testContext.await();
VerificationHost peerEntryPoint = this.host.getPeerHost();
// add a custom header and make sure the service sees it in its handler, in the request
// headers, and we see a service response header in our response
String headerName = MinimalTestService.TEST_HEADER_NAME.toLowerCase();
UUID id = UUID.randomUUID();
String headerRequestValue = "request-" + id;
String headerResponseValue = "response-" + id;
TestContext testContextForPut = this.host.testCreate(initialStates.size() * this.nodeCount);
for (ServiceDocument s : initialStates) {
// send a PATCH the id for each document, to each peer. If it routes to the proper peer
// the initial state.documentOwner, will match the state.id
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
// For testing coverage, force the use of the same forwarding service instance.
// We make all request flow from one peer to others, testing both loopback p2p
// and true forwarding. Otherwise, the forwarding happens by directly contacting
// peer we want to land on!
URI localForwardingUri = UriUtils.buildUri(peerEntryPoint.getUri(),
s.documentSelfLink);
// add a query to make sure it does not affect forwarding
localForwardingUri = UriUtils.extendUriWithQuery(localForwardingUri, "k", "v",
"k1", "v1", "k2", "v2");
URI u = UriUtils.buildForwardToPeerUri(localForwardingUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR, EnumSet.noneOf(ServiceOption.class));
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
body.id = peer.getId();
this.host.send(Operation.createPut(u)
.addRequestHeader(headerName, headerRequestValue)
.setCompletion(
(o, e) -> {
if (e != null) {
testContextForPut.fail(e);
return;
}
String value = o.getResponseHeader(headerName);
if (value == null || !value.equals(headerResponseValue)) {
testContextForPut.fail(new IllegalArgumentException(
"response header not found"));
return;
}
testContextForPut.complete();
})
.setBody(body));
}
}
testContextForPut.await();
this.host.logThroughput();
TestContext ctx = this.host.testCreate(c * this.host.getPeerCount());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
for (ServiceDocument s : initialStates) {
Operation get = Operation.createGet(UriUtils.buildUri(peer, s.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
MinimalTestServiceState rsp = o
.getBody(MinimalTestServiceState.class);
if (!rsp.id.equals(rsp.documentOwner)) {
ctx.fail(
new IllegalStateException("Expected: "
+ rsp.documentOwner + " was: " + rsp.id));
} else {
ctx.complete();
}
});
this.host.send(get);
}
}
ctx.await();
// Do a negative test: Send a request that will induce failure in the service handler and
// make sure we receive back failure, with a ServiceErrorResponse body
this.host.toggleDebuggingMode(true);
TestContext testCxtForPut = this.host.testCreate(this.host.getInProcessHostMap().size());
for (VerificationHost peer : this.host.getInProcessHostMap().values()) {
ServiceDocument s = initialStates.get(0);
URI serviceUri = UriUtils.buildUri(peerEntryPoint.getUri(), s.documentSelfLink);
URI u = UriUtils.buildForwardToPeerUri(serviceUri, peer.getId(),
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
null);
MinimalTestServiceState body = (MinimalTestServiceState) this.host
.buildMinimalTestState();
// setting id to null will cause validation failure.
body.id = null;
this.host.send(Operation.createPut(u)
.setCompletion(
(o, e) -> {
if (e == null) {
testCxtForPut.fail(new IllegalStateException(
"expected failure"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (rsp.message == null || rsp.message.isEmpty()) {
testCxtForPut.fail(new IllegalStateException(
"expected error response message"));
return;
}
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)
|| 0 != Double.compare(Math.PI, rsp.customErrorField)) {
testCxtForPut.fail(new IllegalStateException(
"expected custom error fields"));
return;
}
testCxtForPut.complete();
})
.setBody(body));
}
testCxtForPut.await();
this.host.toggleDebuggingMode(false);
}
private void directOwnerSelection() throws Throwable {
Map<URI, Map<String, Long>> keyToNodeAssignmentsPerNode = new HashMap<>();
List<String> keys = new ArrayList<>();
long c = this.updateCount * this.nodeCount;
// generate N keys once, then ask each node to assign to its peers. Each node should come up
// with the same distribution
for (int i = 0; i < c; i++) {
keys.add(Utils.getNowMicrosUtc() + "");
}
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
keyToNodeAssignmentsPerNode.put(nodeGroup, new HashMap<>());
}
this.host.waitForNodeGroupConvergence(this.nodeCount);
TestContext testContext = this.host.testCreate(c * this.nodeCount);
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
for (String key : keys) {
SelectAndForwardRequest body = new SelectAndForwardRequest();
body.key = key;
Operation post = Operation
.createPost(UriUtils.buildUri(nodeGroup,
ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.setBody(body)
.setCompletion(
(o, e) -> {
try {
synchronized (keyToNodeAssignmentsPerNode) {
SelectOwnerResponse rsp = o
.getBody(SelectOwnerResponse.class);
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode
.get(nodeGroup);
Long l = assignmentsPerNode.get(rsp.ownerNodeId);
if (l == null) {
l = 0L;
}
assignmentsPerNode.put(rsp.ownerNodeId, l + 1);
testContext.complete();
}
} catch (Throwable ex) {
testContext.fail(ex);
}
});
this.host.send(post);
}
}
testContext.await();
this.host.logThroughput();
Map<String, Long> countPerNode = null;
for (URI nodeGroup : this.host.getNodeGroupMap().values()) {
Map<String, Long> assignmentsPerNode = keyToNodeAssignmentsPerNode.get(nodeGroup);
if (countPerNode == null) {
countPerNode = assignmentsPerNode;
}
this.host.log("Node group %s assignments: %s", nodeGroup, assignmentsPerNode);
for (Entry<String, Long> e : assignmentsPerNode.entrySet()) {
// we assume that with random keys, and random node ids, each node will get at least
// one key.
assertTrue(e.getValue() > 0);
Long count = countPerNode.get(e.getKey());
if (count == null) {
continue;
}
if (!count.equals(e.getValue())) {
this.host.logNodeGroupState();
throw new IllegalStateException(
"Node id got assigned the same key different number of times, on one of the nodes");
}
}
}
}
@Test
public void replicationFullQuorumMissingServiceOnPeer() throws Throwable {
// This test verifies the following scenario:
// A new node joins an existing node-group with
// services already created. Synchronization is
// still in-progress and a write request arrives.
// If the quorum is configured to FULL, the write
// request will fail on the new node with not-found
// error, since synchronization hasn't completed.
// The test verifies that when this happens, the
// owner node will try to synchronize on-demand
// and retry the original update reqeust.
// Artificially setting the replica not found timeout to
// a lower-value, to reduce the wait time before owner
// retries
System.setProperty(
NodeSelectorReplicationService.PROPERTY_NAME_REPLICA_NOT_FOUND_TIMEOUT_MICROS,
Long.toString(TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS)));
this.host = VerificationHost.create(0);
this.host.setPeerSynchronizationEnabled(false);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.start();
// Setup one host and create some example
// services on it.
List<URI> exampleUris = new ArrayList<>();
this.host.createExampleServices(this.host, this.serviceCount, exampleUris, null);
// Add a second host with synchronization disabled,
// Join it to the existing host.
VerificationHost host2 = new VerificationHost();
try {
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
String mainHostId = "main-" + VerificationHost.hostNumber.incrementAndGet();
String[] args = {
"--id=" + mainHostId,
"--port=0",
"--bindAddress=127.0.0.1",
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--peerNodes=" + this.host.getUri()
};
host2.initialize(args);
host2.setPeerSynchronizationEnabled(false);
host2.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
host2.start();
this.host.addPeerNode(host2);
// Wait for node-group to converge
List<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.buildUri(this.host, ServiceUriPaths.DEFAULT_NODE_GROUP));
nodeGroupUris.add(UriUtils.buildUri(host2, ServiceUriPaths.DEFAULT_NODE_GROUP));
this.host.waitForNodeGroupConvergence(nodeGroupUris, 2, 2, true);
// Set the quorum to full.
this.host.setNodeGroupQuorum(2, nodeGroupUris.get(0));
host2.setNodeGroupQuorum(2);
// Filter the created examples to only those
// that are owned by host-1.
List<URI> host1Examples = exampleUris.stream()
.filter(e -> this.host.isOwner(e.getPath(), ServiceUriPaths.DEFAULT_NODE_SELECTOR))
.collect(Collectors.toList());
// Start patching all filtered examples. Because
// synchronization is disabled each of these
// example services will not exist on the new
// node that we added resulting in a non_found
// error. However, the owner will retry this
// after on-demand synchronization and hence
// patches should succeed.
ExampleServiceState state = new ExampleServiceState();
state.counter = 1L;
if (host1Examples.size() > 0) {
this.host.log(Level.INFO, "Starting patches");
TestContext ctx = this.host.testCreate(host1Examples.size());
for (URI exampleUri : host1Examples) {
Operation patch = Operation
.createPatch(exampleUri)
.setBody(state)
.setReferer("localhost")
.setCompletion(ctx.getCompletion());
this.host.sendRequest(patch);
}
ctx.await();
}
} finally {
host2.tearDown();
}
}
@Test
public void replicationWithAuthAndNodeRestart() throws Throwable {
AuthorizationHelper authHelper;
this.isAuthorizationEnabled = true;
setUp(this.nodeCount);
authHelper = new AuthorizationHelper(this.host);
// relax quorum to allow for divergent writes, on independent nodes (not yet joined)
this.host.setSystemAuthorizationContext();
// Create the same users and roles on every peer independently
Map<ServiceHost, Collection<String>> roleLinksByHost = new HashMap<>();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
String email = "jane@doe.com";
authHelper.createUserService(h, email);
authHelper.createRoles(h, email);
}
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = getRolesByHost(roleLinksByHost);
// Join nodes to force synchronization and convergence
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
// Get roles from all nodes
Map<ServiceHost, Map<URI, RoleState>> newRoleStateByHost = getRolesByHost(roleLinksByHost);
// Verify that every host independently advances their version & epoch
for (ServiceHost h : roleStateByHost.keySet()) {
Map<URI, RoleState> roleState = roleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState oldRole = roleState.get(u);
RoleState newRole = newRoleStateByHost.get(h).get(u);
assertTrue("version should have advanced",
newRole.documentVersion > oldRole.documentVersion);
assertTrue("epoch should have advanced",
newRole.documentEpoch > oldRole.documentEpoch);
}
}
// Verify that every host converged to the same version, epoch, and owner
Map<String, Long> versions = new HashMap<>();
Map<String, Long> epochs = new HashMap<>();
Map<String, String> owners = new HashMap<>();
for (ServiceHost h : newRoleStateByHost.keySet()) {
Map<URI, RoleState> roleState = newRoleStateByHost.get(h);
for (URI u : roleState.keySet()) {
RoleState newRole = roleState.get(u);
if (versions.containsKey(newRole.documentSelfLink)) {
assertTrue(versions.get(newRole.documentSelfLink) == newRole.documentVersion);
} else {
versions.put(newRole.documentSelfLink, newRole.documentVersion);
}
if (epochs.containsKey(newRole.documentSelfLink)) {
assertTrue(Objects.equals(epochs.get(newRole.documentSelfLink),
newRole.documentEpoch));
} else {
epochs.put(newRole.documentSelfLink, newRole.documentEpoch);
}
if (owners.containsKey(newRole.documentSelfLink)) {
assertEquals(owners.get(newRole.documentSelfLink), newRole.documentOwner);
} else {
owners.put(newRole.documentSelfLink, newRole.documentOwner);
}
}
}
// create some example tasks, which delete example services. We dont have any
// examples services created, which is good, since we just want these tasks to
// go to finished state, then verify, after node restart, they all start
Set<String> exampleTaskLinks = new ConcurrentSkipListSet<>();
createReplicatedExampleTasks(exampleTaskLinks, null);
Set<String> exampleLinks = new ConcurrentSkipListSet<>();
verifyReplicatedAuthorizedPost(exampleLinks);
// verify restart, with authorization.
// stop one host
VerificationHost hostToStop = this.host.getInProcessHostMap().values().iterator().next();
stopAndRestartHost(exampleLinks, exampleTaskLinks, hostToStop);
}
private void createReplicatedExampleTasks(Set<String> exampleTaskLinks, String name)
throws Throwable {
URI factoryUri = UriUtils.buildFactoryUri(this.host.getPeerHost(),
ExampleTaskService.class);
this.host.setSystemAuthorizationContext();
// Sample body that this user is authorized to create
ExampleTaskServiceState exampleServiceState = new ExampleTaskServiceState();
if (name != null) {
exampleServiceState.customQueryClause = Query.Builder.create()
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, name).build();
}
this.host.log("creating example *task* instances");
TestContext testContext = this.host.testCreate(this.serviceCount);
for (int i = 0; i < this.serviceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
ExampleTaskServiceState rsp = o.getBody(ExampleTaskServiceState.class);
synchronized (exampleTaskLinks) {
exampleTaskLinks.add(rsp.documentSelfLink);
}
testContext.complete();
};
this.host.send(Operation
.createPost(factoryUri)
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
// ensure all tasks are in finished state
this.host.waitFor("Example tasks did not finish", () -> {
ServiceDocumentQueryResult rsp = this.host.getExpandedFactoryState(factoryUri);
for (Object o : rsp.documents.values()) {
ExampleTaskServiceState doc = Utils.fromJson(o, ExampleTaskServiceState.class);
if (TaskState.isFailed(doc.taskInfo)) {
this.host.log("task %s failed: %s", doc.documentSelfLink, doc.failureMessage);
throw new IllegalStateException("task failed");
}
if (!TaskState.isFinished(doc.taskInfo)) {
return false;
}
}
return true;
});
}
private void verifyReplicatedAuthorizedPost(Set<String> exampleLinks)
throws Throwable {
Collection<VerificationHost> hosts = this.host.getInProcessHostMap().values();
RoundRobinIterator<VerificationHost> it = new RoundRobinIterator<>(hosts);
int exampleServiceCount = this.serviceCount;
String userLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "jane@doe.com");
// Verify we can assert identity and make a request to every host
this.host.assumeIdentity(userLink);
// Sample body that this user is authorized to create
ExampleServiceState exampleServiceState = new ExampleServiceState();
exampleServiceState.name = "jane";
this.host.log("creating example instances");
TestContext testContext = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
try {
// Verify the user is set as principal
ExampleServiceState state = o.getBody(ExampleServiceState.class);
assertEquals(state.documentAuthPrincipalLink,
userLink);
exampleLinks.add(state.documentSelfLink);
testContext.complete();
} catch (Throwable e2) {
testContext.fail(e2);
}
};
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(exampleServiceState)
.setCompletion(c));
}
testContext.await();
this.host.toggleNegativeTestMode(true);
// Sample body that this user is NOT authorized to create
ExampleServiceState invalidExampleServiceState = new ExampleServiceState();
invalidExampleServiceState.name = "somebody other than jane";
this.host.log("issuing non authorized request");
TestContext testCtx = this.host.testCreate(exampleServiceCount);
for (int i = 0; i < exampleServiceCount; i++) {
this.host.send(Operation
.createPost(UriUtils.buildFactoryUri(it.next(), ExampleService.class))
.setBody(invalidExampleServiceState)
.setCompletion((o, e) -> {
if (e != null) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, o.getStatusCode());
testCtx.complete();
return;
}
testCtx.fail(new IllegalStateException("expected failure"));
}));
}
testCtx.await();
this.host.toggleNegativeTestMode(false);
}
private void stopAndRestartHost(Set<String> exampleLinks, Set<String> exampleTaskLinks,
VerificationHost hostToStop)
throws Throwable, InterruptedException {
// relax quorum
this.host.setNodeGroupQuorum(this.nodeCount - 1);
// expire node that went away quickly to avoid alot of log spam from gossip failures
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(1);
this.host.setNodeGroupConfig(cfg);
this.host.stopHostAndPreserveState(hostToStop);
this.host.waitForNodeGroupConvergence(2, 2);
VerificationHost existingHost = this.host.getInProcessHostMap().values().iterator().next();
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleTaskService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// create some additional tasks on the remaining two hosts, but make sure they don't delete
// any example service instances, by specifying a name value we know will not match anything
createReplicatedExampleTasks(exampleTaskLinks, UUID.randomUUID().toString());
// delete some of the task links, to test synchronization of deleted entries on the restarted
// host
Set<String> deletedExampleLinks = deleteSomeServices(exampleLinks);
// increase quorum on existing nodes, so they wait for new node
this.host.setNodeGroupQuorum(this.nodeCount);
hostToStop.setPort(0);
hostToStop.setSecurePort(0);
if (!VerificationHost.restartStatefulHost(hostToStop)) {
this.host.log("Failed restart of host, aborting");
return;
}
// restart host, rejoin it
URI nodeGroupU = UriUtils.buildUri(hostToStop, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI eNodeGroupU = UriUtils.buildUri(existingHost, ServiceUriPaths.DEFAULT_NODE_GROUP);
this.host.testStart(1);
this.host.setSystemAuthorizationContext();
this.host.joinNodeGroup(nodeGroupU, eNodeGroupU, this.nodeCount);
this.host.testWait();
this.host.addPeerNode(hostToStop);
this.host.waitForNodeGroupConvergence(this.nodeCount);
// set quorum on new node as well
this.host.setNodeGroupQuorum(this.nodeCount);
this.host.resetAuthorizationContext();
this.host.waitFor("Task services not started in restarted host:" + exampleTaskLinks, () -> {
return checkChildServicesIfStarted(exampleTaskLinks, hostToStop) == 0;
});
// verify all services, not previously deleted, are restarted
this.host.waitFor("Services not started in restarted host:" + exampleLinks, () -> {
return checkChildServicesIfStarted(exampleLinks, hostToStop) == 0;
});
int deletedCount = deletedExampleLinks.size();
this.host.waitFor("Deleted services still present in restarted host", () -> {
return checkChildServicesIfStarted(deletedExampleLinks, hostToStop) == deletedCount;
});
}
private Set<String> deleteSomeServices(Set<String> exampleLinks)
throws Throwable {
int deleteCount = exampleLinks.size() / 3;
Iterator<String> itLinks = exampleLinks.iterator();
Set<String> deletedExampleLinks = new HashSet<>();
TestContext testContext = this.host.testCreate(deleteCount);
for (int i = 0; i < deleteCount; i++) {
String link = itLinks.next();
deletedExampleLinks.add(link);
exampleLinks.remove(link);
Operation delete = Operation.createDelete(this.host.getPeerServiceUri(link))
.setCompletion(testContext.getCompletion());
this.host.send(delete);
}
testContext.await();
this.host.log("Deleted links: %s", deletedExampleLinks);
return deletedExampleLinks;
}
private int checkChildServicesIfStarted(Set<String> exampleTaskLinks,
VerificationHost host) {
this.host.setSystemAuthorizationContext();
int notStartedCount = 0;
for (String s : exampleTaskLinks) {
ProcessingStage st = host.getServiceStage(s);
if (st == null) {
notStartedCount++;
}
}
this.host.resetAuthorizationContext();
if (notStartedCount > 0) {
this.host.log("%d services not started on %s (%s)", notStartedCount,
host.getPublicUri(), host.getId());
}
return notStartedCount;
}
private Map<ServiceHost, Map<URI, RoleState>> getRolesByHost(
Map<ServiceHost, Collection<String>> roleLinksByHost) throws Throwable {
Map<ServiceHost, Map<URI, RoleState>> roleStateByHost = new HashMap<>();
for (ServiceHost h : roleLinksByHost.keySet()) {
Collection<String> roleLinks = roleLinksByHost.get(h);
Collection<URI> roleURIs = new ArrayList<>();
for (String link : roleLinks) {
roleURIs.add(UriUtils.buildUri(h, link));
}
Map<URI, RoleState> serviceState = this.host.getServiceState(null, RoleState.class,
roleURIs);
roleStateByHost.put(h, serviceState);
}
return roleStateByHost;
}
private void verifyOperationJoinAcrossPeers(Map<URI, ReplicationTestServiceState> childStates)
throws Throwable {
// do a OperationJoin across N nodes, making sure join works when forwarding is involved
List<Operation> joinedOps = new ArrayList<>();
for (ReplicationTestServiceState st : childStates.values()) {
Operation get = Operation.createGet(
this.host.getPeerServiceUri(st.documentSelfLink)).setReferer(
this.host.getReferer());
joinedOps.add(get);
}
TestContext testContext = this.host.testCreate(1);
OperationJoin
.create(joinedOps)
.setCompletion(
(ops, exc) -> {
if (exc != null) {
testContext.fail(exc.values().iterator().next());
return;
}
for (Operation o : ops.values()) {
ReplicationTestServiceState state = o.getBody(
ReplicationTestServiceState.class);
if (state.stringField == null) {
testContext.fail(new IllegalStateException());
return;
}
}
testContext.complete();
})
.sendWith(this.host.getPeerHost());
testContext.await();
}
public Map<String, Set<String>> computeOwnerIdsPerLink(VerificationHost joinedHost,
Collection<String> links)
throws Throwable {
TestContext testContext = this.host.testCreate(links.size());
Map<String, Set<String>> expectedOwnersPerLink = new ConcurrentSkipListMap<>();
CompletionHandler c = (o, e) -> {
if (e != null) {
testContext.fail(e);
return;
}
SelectOwnerResponse rsp = o.getBody(SelectOwnerResponse.class);
Set<String> eligibleNodeIds = new HashSet<>();
for (NodeState ns : rsp.selectedNodes) {
eligibleNodeIds.add(ns.id);
}
expectedOwnersPerLink.put(rsp.key, eligibleNodeIds);
testContext.complete();
};
for (String link : links) {
Operation selectOp = Operation.createGet(null)
.setCompletion(c)
.setExpiration(this.host.getOperationTimeoutMicros() + Utils.getNowMicrosUtc());
joinedHost.selectOwner(this.replicationNodeSelector, link, selectOp);
}
testContext.await();
return expectedOwnersPerLink;
}
public <T extends ServiceDocument> void verifyDocumentOwnerAndEpoch(Map<String, T> childStates,
VerificationHost joinedHost,
List<URI> joinedHostUris,
int minExpectedEpochRetries,
int maxExpectedEpochRetries, int expectedOwnerChanges)
throws Throwable, InterruptedException, TimeoutException {
Map<URI, NodeGroupState> joinedHostNodeGroupStates = this.host.getServiceState(null,
NodeGroupState.class, joinedHostUris);
Set<String> joinedHostOwnerIds = new HashSet<>();
for (NodeGroupState st : joinedHostNodeGroupStates.values()) {
joinedHostOwnerIds.add(st.documentOwner);
}
this.host.waitFor("ownership did not converge", () -> {
Map<String, Set<String>> ownerIdsPerLink = computeOwnerIdsPerLink(joinedHost,
childStates.keySet());
boolean isConverged = true;
Map<String, Set<Long>> epochsPerLink = new HashMap<>();
List<URI> nodeSelectorStatsUris = new ArrayList<>();
for (URI baseNodeUri : joinedHostUris) {
nodeSelectorStatsUris.add(UriUtils.buildUri(baseNodeUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
URI factoryUri = UriUtils.buildUri(
baseNodeUri, this.replicationTargetFactoryLink);
ServiceDocumentQueryResult factoryRsp = this.host
.getFactoryState(factoryUri);
if (factoryRsp.documentLinks == null
|| factoryRsp.documentLinks.size() != childStates.size()) {
isConverged = false;
// services not all started in new nodes yet;
this.host.log("Node %s does not have all services: %s", baseNodeUri,
Utils.toJsonHtml(factoryRsp));
break;
}
List<URI> childUris = new ArrayList<>();
for (String link : childStates.keySet()) {
childUris.add(UriUtils.buildUri(baseNodeUri, link));
}
// retrieve the document state directly from each service
Map<URI, ServiceDocument> childDocs = this.host.getServiceState(null,
ServiceDocument.class, childUris);
List<URI> childStatUris = new ArrayList<>();
for (ServiceDocument state : childDocs.values()) {
if (state.documentOwner == null) {
this.host.log("Owner not set in service on new node: %s",
Utils.toJsonHtml(state));
isConverged = false;
break;
}
URI statUri = UriUtils.buildUri(baseNodeUri, state.documentSelfLink,
ServiceHost.SERVICE_URI_SUFFIX_STATS);
childStatUris.add(statUri);
Set<Long> epochs = epochsPerLink.get(state.documentEpoch);
if (epochs == null) {
epochs = new HashSet<>();
epochsPerLink.put(state.documentSelfLink, epochs);
}
epochs.add(state.documentEpoch);
Set<String> eligibleNodeIds = ownerIdsPerLink.get(state.documentSelfLink);
if (!joinedHostOwnerIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not expected: %s, valid ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
if (eligibleNodeIds != null && !eligibleNodeIds.contains(state.documentOwner)) {
this.host.log("Owner id for %s not eligible: %s, eligible ids: %s",
state.documentSelfLink, state.documentOwner, joinedHostOwnerIds);
isConverged = false;
break;
}
}
int nodeGroupMaintCount = 0;
int docOwnerToggleOffCount = 0;
int docOwnerToggleCount = 0;
// verify stats were reported by owner node, not a random peer
Map<URI, ServiceStats> allChildStats = this.host.getServiceState(null,
ServiceStats.class, childStatUris);
for (ServiceStats childStats : allChildStats.values()) {
String parentLink = UriUtils.getParentPath(childStats.documentSelfLink);
Set<String> eligibleNodes = ownerIdsPerLink.get(parentLink);
if (!eligibleNodes.contains(childStats.documentOwner)) {
this.host.log("Stats for %s owner not expected. Is %s, should be %s",
parentLink, childStats.documentOwner,
ownerIdsPerLink.get(parentLink));
isConverged = false;
break;
}
ServiceStat maintStat = childStats.entries
.get(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (maintStat != null) {
nodeGroupMaintCount++;
}
ServiceStat docOwnerToggleOffStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
if (docOwnerToggleOffStat != null) {
docOwnerToggleOffCount++;
}
ServiceStat docOwnerToggleStat = childStats.entries
.get(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
if (docOwnerToggleStat != null) {
docOwnerToggleCount++;
}
}
this.host.log("Node group change maintenance observed: %d", nodeGroupMaintCount);
if (nodeGroupMaintCount < expectedOwnerChanges) {
isConverged = false;
}
this.host.log("Toggled off doc owner count: %d, toggle on count: %d",
docOwnerToggleOffCount, docOwnerToggleCount);
if (docOwnerToggleCount < childStates.size()) {
isConverged = false;
}
// verify epochs
for (Set<Long> epochs : epochsPerLink.values()) {
if (epochs.size() > 1) {
this.host.log("Documents have different epochs:%s", epochs.toString());
isConverged = false;
}
}
if (!isConverged) {
break;
}
}
return isConverged;
});
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild) throws Throwable {
return doStateUpdateReplicationTest(action, childCount, updateCount, expectedVersion,
updateBodySetter, convergenceChecker, initialStatesPerChild, null, null);
}
private <T extends ServiceDocument> Map<String, T> doStateUpdateReplicationTest(Action action,
int childCount, int updateCount,
long expectedVersion,
Function<T, Void> updateBodySetter,
BiPredicate<T, T> convergenceChecker,
Map<String, T> initialStatesPerChild,
Map<Action, Long> countsPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
int testCount = childCount * updateCount;
String testName = "Replication with " + action;
TestContext testContext = this.host.testCreate(testCount);
testContext.setTestName(testName).logBefore();
if (!this.expectFailure) {
// Before we do the replication test, wait for factory availability.
for (URI fu : this.host.getNodeGroupToFactoryMap(this.replicationTargetFactoryLink)
.values()) {
// confirm that /factory/available returns 200 across all nodes
waitForReplicatedFactoryServiceAvailable(fu, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
}
long before = Utils.getNowMicrosUtc();
AtomicInteger failedCount = new AtomicInteger();
// issue an update to each child service and verify it was reflected
// among
// peers
for (T initState : initialStatesPerChild.values()) {
// change a field in the initial state of each service but keep it
// the same across all updates so potential re ordering of the
// updates does not cause spurious test breaks
updateBodySetter.apply(initState);
for (int i = 0; i < updateCount; i++) {
long sentTime = 0;
if (this.expectFailure) {
sentTime = Utils.getNowMicrosUtc();
}
URI factoryOnRandomPeerUri = this.host
.getPeerServiceUri(this.replicationTargetFactoryLink);
long finalSentTime = sentTime;
this.host
.send(Operation
.createPatch(UriUtils.buildUri(factoryOnRandomPeerUri,
initState.documentSelfLink))
.setAction(action)
.forceRemote()
.setBodyNoCloning(initState)
.setCompletion(
(o, e) -> {
if (e != null) {
if (this.expectFailure) {
failedCount.incrementAndGet();
testContext.complete();
return;
}
testContext.fail(e);
return;
}
if (this.expectFailure
&& this.expectedFailureStartTimeMicros > 0
&& finalSentTime > this.expectedFailureStartTimeMicros) {
testContext.fail(new IllegalStateException(
"Request should have failed: %s"
+ o.toString()
+ " sent at " + finalSentTime));
return;
}
testContext.complete();
}));
}
}
testContext.await();
testContext.logAfter();
updatePerfDataPerAction(action, before, (long) (childCount * updateCount), countsPerAction,
elapsedTimePerAction);
if (this.expectFailure) {
this.host.log("Failed count: %d", failedCount.get());
if (failedCount.get() == 0) {
throw new IllegalStateException(
"Possible false negative but expected at least one failure");
}
return initialStatesPerChild;
}
// All updates sent to all children within one host, now wait for
// convergence
if (action != Action.DELETE) {
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
childCount,
expectedVersion);
}
// for DELETE replication, we expect the child services to be stopped
// across hosts and their state marked "deleted". So confirm no children
// are available
return waitForReplicatedFactoryChildServiceConvergence(initialStatesPerChild,
convergenceChecker,
0,
expectedVersion);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction)
throws Throwable {
return doExampleFactoryPostReplicationTest(childCount, null,
countPerAction, elapsedTimePerAction);
}
private Map<String, ExampleServiceState> doExampleFactoryPostReplicationTest(int childCount,
EnumSet<TestProperty> props,
Map<Action, Long> countPerAction,
Map<Action, Long> elapsedTimePerAction) throws Throwable {
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (this.host == null) {
setUp(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.host.getPeerCount());
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
this.host.toggleNegativeTestMode(true);
}
String factoryPath = this.replicationTargetFactoryLink;
Map<String, ExampleServiceState> serviceStates = new HashMap<>();
long before = Utils.getNowMicrosUtc();
TestContext testContext = this.host.testCreate(childCount);
testContext.setTestName("POST replication");
testContext.logBefore();
for (int i = 0; i < childCount; i++) {
URI factoryOnRandomPeerUri = this.host.getPeerServiceUri(factoryPath);
Operation post = Operation
.createPost(factoryOnRandomPeerUri)
.setCompletion(testContext.getCompletion());
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = "" + post.getId();
initialState.counter = Long.MIN_VALUE;
// set the self link as a hint so the child service URI is
// predefined instead of random
initialState.documentSelfLink = "" + post.getId();
// factory service is started on all hosts. Now issue a POST to one,
// to create a child service with some initial state.
post.setReferer(this.host.getReferer());
this.host.sendRequest(post.setBody(initialState));
// initial state is cloned and sent, now we can change self link per
// child to reflect its runtime URI, which will
// contain the factory service path
initialState.documentSelfLink = UriUtils.buildUriPath(factoryPath,
initialState.documentSelfLink);
serviceStates.put(initialState.documentSelfLink, initialState);
}
if (props.contains(TestProperty.FORCE_FAILURE)) {
// do not wait for convergence of the child services. Instead
// proceed to the next test which is probably stopping hosts
// abruptly
return serviceStates;
}
testContext.await();
updatePerfDataPerAction(Action.POST, before, (long) this.serviceCount, countPerAction,
elapsedTimePerAction);
testContext.logAfter();
return waitForReplicatedFactoryChildServiceConvergence(serviceStates,
this.exampleStateConvergenceChecker,
childCount,
0L);
}
private void updateExampleServiceOptions(
Map<String, ExampleServiceState> statesPerSelfLink) throws Throwable {
if (this.postCreationServiceOptions == null || this.postCreationServiceOptions.isEmpty()) {
return;
}
TestContext testContext = this.host.testCreate(statesPerSelfLink.size());
URI nodeGroup = this.host.getNodeGroupMap().values().iterator().next();
for (String link : statesPerSelfLink.keySet()) {
URI bUri = UriUtils.buildBroadcastRequestUri(
UriUtils.buildUri(nodeGroup, link, ServiceHost.SERVICE_URI_SUFFIX_CONFIG),
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
ServiceConfigUpdateRequest cfgBody = ServiceConfigUpdateRequest.create();
cfgBody.addOptions = this.postCreationServiceOptions;
this.host.send(Operation.createPatch(bUri)
.setBody(cfgBody)
.setCompletion(testContext.getCompletion()));
}
testContext.await();
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
return waitForReplicatedFactoryChildServiceConvergence(
getFactoriesPerNodeGroup(this.replicationTargetFactoryLink),
serviceStates,
stateChecker,
expectedChildCount,
expectedVersion);
}
private <T extends ServiceDocument> Map<String, T> waitForReplicatedFactoryChildServiceConvergence(
Map<URI, URI> factories,
Map<String, T> serviceStates,
BiPredicate<T, T> stateChecker,
int expectedChildCount, long expectedVersion)
throws Throwable, TimeoutException {
// now poll all hosts until they converge: They all have a child service
// with the expected URI and it has the same state
Map<String, T> updatedStatesPerSelfLink = new HashMap<>();
Date expiration = new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(this.host.getTimeoutSeconds()));
do {
URI node = factories.keySet().iterator().next();
AtomicInteger getFailureCount = new AtomicInteger();
if (expectedChildCount != 0) {
// issue direct GETs to the services, we do not trust the factory
for (String link : serviceStates.keySet()) {
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(node, link))
.setReferer(this.host.getReferer())
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(5))
.setCompletion(
(o, e) -> {
if (e != null) {
getFailureCount.incrementAndGet();
}
ctx.completeIteration();
});
this.host.sendRequest(get);
this.host.testWait(ctx);
}
}
if (getFailureCount.get() > 0) {
this.host.log("Child services not propagated yet. Failure count: %d",
getFailureCount.get());
Thread.sleep(500);
continue;
}
TestContext testContext = this.host.testCreate(factories.size());
Map<URI, ServiceDocumentQueryResult> childServicesPerNode = new HashMap<>();
for (URI remoteFactory : factories.values()) {
URI factoryUriWithExpand = UriUtils.buildExpandLinksQueryUri(remoteFactory);
Operation get = Operation.createGet(factoryUriWithExpand)
.setCompletion(
(o, e) -> {
if (e != null) {
testContext.complete();
return;
}
if (!o.hasBody()) {
testContext.complete();
return;
}
ServiceDocumentQueryResult r = o
.getBody(ServiceDocumentQueryResult.class);
synchronized (childServicesPerNode) {
childServicesPerNode.put(o.getUri(), r);
}
testContext.complete();
});
this.host.send(get);
}
testContext.await();
long expectedNodeCountPerLinkMax = factories.size();
long expectedNodeCountPerLinkMin = expectedNodeCountPerLinkMax;
if (this.replicationFactor != 0) {
// We expect services to end up either on K nodes, or K + 1 nodes,
// if limited replication is enabled. The reason we might end up with services on
// an additional node, is because we elect an owner to synchronize an entire factory,
// using the factory's link, and that might end up on a node not used for any child.
// This will produce children on that node, giving us K+1 replication, which is acceptable
// given K (replication factor) << N (total nodes in group)
expectedNodeCountPerLinkMax = this.replicationFactor + 1;
expectedNodeCountPerLinkMin = this.replicationFactor;
}
if (expectedChildCount == 0) {
expectedNodeCountPerLinkMax = 0;
expectedNodeCountPerLinkMin = 0;
}
// build a service link to node map so we can tell on which node each service instance landed
Map<String, Set<URI>> linkToNodeMap = new HashMap<>();
boolean isConverged = true;
for (Entry<URI, ServiceDocumentQueryResult> entry : childServicesPerNode.entrySet()) {
for (String link : entry.getValue().documentLinks) {
if (!serviceStates.containsKey(link)) {
this.host.log("service %s not expected, node: %s", link, entry.getKey());
isConverged = false;
continue;
}
Set<URI> hostsPerLink = linkToNodeMap.get(link);
if (hostsPerLink == null) {
hostsPerLink = new HashSet<>();
}
hostsPerLink.add(entry.getKey());
linkToNodeMap.put(link, hostsPerLink);
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
// each link must exist on N hosts, where N is either the replication factor, or, if not used, all nodes
for (Entry<String, Set<URI>> e : linkToNodeMap.entrySet()) {
if (e.getValue() == null && this.replicationFactor == 0) {
this.host.log("Service %s not found on any nodes", e.getKey());
isConverged = false;
continue;
}
if (e.getValue().size() < expectedNodeCountPerLinkMin
|| e.getValue().size() > expectedNodeCountPerLinkMax) {
this.host.log("Service %s found on %d nodes, expected %d -> %d", e.getKey(), e
.getValue().size(), expectedNodeCountPerLinkMin,
expectedNodeCountPerLinkMax);
isConverged = false;
}
}
if (!isConverged) {
Thread.sleep(500);
continue;
}
if (expectedChildCount == 0) {
// DELETE test, all children removed from all hosts, we are done
return updatedStatesPerSelfLink;
}
// verify /available reports correct results on the factory.
URI factoryUri = factories.values().iterator().next();
Class<?> stateType = serviceStates.values().iterator().next().getClass();
waitForReplicatedFactoryServiceAvailable(factoryUri,
ServiceUriPaths.DEFAULT_NODE_SELECTOR);
// we have the correct number of services on all hosts. Now verify
// the state of each service matches what we expect
isConverged = true;
for (Entry<String, Set<URI>> entry : linkToNodeMap.entrySet()) {
String selfLink = entry.getKey();
int convergedNodeCount = 0;
for (URI nodeUri : entry.getValue()) {
ServiceDocumentQueryResult childLinksAndDocsPerHost = childServicesPerNode
.get(nodeUri);
Object jsonState = childLinksAndDocsPerHost.documents.get(selfLink);
if (jsonState == null && this.replicationFactor == 0) {
this.host
.log("Service %s not present on host %s", selfLink, entry.getKey());
continue;
}
if (jsonState == null) {
continue;
}
T initialState = serviceStates.get(selfLink);
if (initialState == null) {
continue;
}
@SuppressWarnings("unchecked")
T stateOnNode = (T) Utils.fromJson(jsonState, stateType);
if (!stateChecker.test(initialState, stateOnNode)) {
this.host
.log("State for %s not converged on node %s. Current state: %s, Initial: %s",
selfLink, nodeUri, Utils.toJsonHtml(stateOnNode),
Utils.toJsonHtml(initialState));
break;
}
if (stateOnNode.documentVersion < expectedVersion) {
this.host
.log("Version (%d, expected %d) not converged, state: %s",
stateOnNode.documentVersion,
expectedVersion,
Utils.toJsonHtml(stateOnNode));
break;
}
if (stateOnNode.documentEpoch == null) {
this.host.log("Epoch is missing, state: %s",
Utils.toJsonHtml(stateOnNode));
break;
}
// Do not check exampleState.counter, in this validation loop.
// We can not compare the counter since the replication test sends the updates
// in parallel, meaning some of them will get re-ordered and ignored due to
// version being out of date.
updatedStatesPerSelfLink.put(selfLink, stateOnNode);
convergedNodeCount++;
}
if (convergedNodeCount < expectedNodeCountPerLinkMin
|| convergedNodeCount > expectedNodeCountPerLinkMax) {
isConverged = false;
break;
}
}
if (isConverged) {
return updatedStatesPerSelfLink;
}
Thread.sleep(500);
} while (new Date().before(expiration));
throw new TimeoutException();
}
private List<ServiceHostState> stopHostsToSimulateFailure(int failedNodeCount) {
int k = 0;
List<ServiceHostState> stoppedHosts = new ArrayList<>();
for (VerificationHost hostToStop : this.host.getInProcessHostMap().values()) {
this.host.log("Stopping host %s", hostToStop);
stoppedHosts.add(hostToStop.getState());
this.host.stopHost(hostToStop);
k++;
if (k >= failedNodeCount) {
break;
}
}
return stoppedHosts;
}
public static class StopVerificationTestService extends StatefulService {
public Collection<URI> serviceTargets;
public AtomicInteger outboundRequestCompletion = new AtomicInteger();
public AtomicInteger outboundRequestFailureCompletion = new AtomicInteger();
public StopVerificationTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation deleteForStop) {
// send requests to replicated services, during stop to verify that the
// runtime prevents any outbound requests from making it out
for (URI uri : this.serviceTargets) {
ReplicationTestServiceState body = new ReplicationTestServiceState();
body.stringField = ReplicationTestServiceState.CLIENT_PATCH_HINT;
for (int i = 0; i < 10; i++) {
// send patch to self, so the select owner logic gets invoked and in theory
// queues or cancels the request
Operation op = Operation.createPatch(this, uri.getPath()).setBody(body)
.setTargetReplicated(true)
.setCompletion((o, e) -> {
if (e != null) {
this.outboundRequestFailureCompletion.incrementAndGet();
} else {
this.outboundRequestCompletion.incrementAndGet();
}
});
sendRequest(op);
}
}
}
}
private void stopHostsAndVerifyQueuing(Collection<VerificationHost> hostsToStop,
VerificationHost remainingHost,
Collection<URI> serviceTargets) throws Throwable {
this.host.log("Starting to stop hosts and verify queuing");
// reduce node expiration for unavailable hosts so gossip warning
// messages do not flood the logs
this.nodeGroupConfig.nodeRemovalDelayMicros = remainingHost.getMaintenanceIntervalMicros();
this.host.setNodeGroupConfig(this.nodeGroupConfig);
this.setOperationTimeoutMicros(TimeUnit.SECONDS.toMicros(10));
// relax quorum to single remaining host
this.host.setNodeGroupQuorum(1);
// start a special test service that will attempt to send messages when it sees
// handleStop(). This is not expected of production code, since service authors
// should never have to worry about handleStop(). We rely on the fact that handleStop
// will be called due to node shutdown, and issue requests to replicated targets,
// then check if anyone of them actually made it out (they should not have)
List<StopVerificationTestService> verificationServices = new ArrayList<>();
// Do the inverse test. Remove all of the original hosts and this time, expect all the
// documents have owners assigned to the new hosts
for (VerificationHost h : hostsToStop) {
StopVerificationTestService s = new StopVerificationTestService();
verificationServices.add(s);
s.serviceTargets = serviceTargets;
h.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.stopHost(h);
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
for (StopVerificationTestService s : verificationServices) {
if (s.outboundRequestCompletion.get() > 0) {
throw new IllegalStateException("Replicated request succeeded");
}
if (s.outboundRequestFailureCompletion.get() < serviceTargets.size()) {
// We expect at least one failure per service target, if we have less
// keep polling.
this.host.log(
"Not converged yet: service %s on host %s has %d outbound request failures, which is lower than %d",
s.getSelfLink(), s.getHost().getId(),
s.outboundRequestFailureCompletion.get(), serviceTargets.size());
isConverged = false;
break;
}
}
if (isConverged) {
this.host.log("Done with stop hosts and verify queuing");
return;
}
Thread.sleep(250);
}
throw new TimeoutException();
}
private void waitForReplicatedFactoryServiceAvailable(URI uri, String nodeSelectorPath)
throws Throwable {
if (this.skipAvailabilityChecks) {
return;
}
if (UriUtils.isHostEqual(this.host, uri)) {
VerificationHost host = this.host;
// if uri is for in-process peers, then use the one
URI peerUri = UriUtils.buildUri(uri.toString().replace(uri.getPath(), ""));
VerificationHost peer = this.host.getInProcessHostMap().get(peerUri);
if (peer != null) {
host = peer;
}
TestContext ctx = host.testCreate(1);
CompletionHandler ch = (o, e) -> {
if (e != null) {
String msg = "Failed to check replicated factory service availability";
ctx.failIteration(new RuntimeException(msg, e));
return;
}
ctx.completeIteration();
};
host.registerForServiceAvailability(ch, nodeSelectorPath, true, uri.getPath());
ctx.await();
} else {
// for remote host
this.host.waitForReplicatedFactoryServiceAvailable(uri, nodeSelectorPath);
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_7 |
crossvul-java_data_good_3076_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
OperationContext.setAuthorizationContext(null);
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
OperationContext.setAuthorizationContext(null);
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_1 |
crossvul-java_data_bad_3079_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_2 |
crossvul-java_data_bad_3078_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_0 |
crossvul-java_data_good_3081_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_2 |
crossvul-java_data_good_3081_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_6 |
crossvul-java_data_good_3080_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_5 |
crossvul-java_data_good_3079_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.OperationContext;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
@Override
protected void configureLoggerFormatter(Logger logger) {
super.configureLoggerFormatter(logger);
// override with formatters for VerificationHost
// if custom formatter has already set, do NOT replace it.
for (Handler h : logger.getParent().getHandlers()) {
if (Objects.equals(h.getFormatter(), LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.NORMAL_FORMAT);
} else if (Objects.equals(h.getFormatter(), COLOR_LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.COLORED_FORMAT);
}
}
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getBody(ServiceErrorResponse.class);
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = Utils.getNowMicrosUtc() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getOperationTimeoutMicros();
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
log("Starting query with options:%s, resultLimit: %d",
create.querySpec.options,
create.querySpec.resultLimit);
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(10))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QueryTask.QuerySpecification spec, long documentCount, long expectedResultCount) {
long start = Utils.getNowMicrosUtc();
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = Utils.getNowMicrosUtc();
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.getNowMicrosUtc() + getOperationTimeoutMicros());
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
AuthorizationContext ctx = null;
if (this.isAuthorizationEnabled()) {
ctx = OperationContext.getAuthorizationContext();
this.setSystemAuthorizationContext();
}
ServiceStats stats = this.getServiceState(
null, ServiceStats.class, UriUtils.buildStatsUri(serviceUri));
if (this.isAuthorizationEnabled()) {
this.setAuthorizationContext(ctx);
}
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
private void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> void doPutPerService(List<Service> services)
throws Throwable {
doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> void doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> void doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> void doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PUT, count, properties, services);
}
public void doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getMaintenanceIntervalMicros();
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri).setReferer(getReferer());
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
send(putClone);
});
} else if (properties.contains(TestProperty.CALLBACK_SEND)) {
updateOp.toggleOption(OperationOption.SEND_WITH_CALLBACK, true);
send(updateOp.setBody(b));
} else {
send(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
} else {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum)
throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
setNodeGroupQuorum(quorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
Date exp = getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (quorum != ns.membershipQuorum) {
isConverged = false;
}
}
}
resetAuthorizationContext();
if (isConverged) {
log("converged");
return;
}
Thread.sleep(500);
}
waitForNodeSelectorQuorumConvergence(ServiceUriPaths.DEFAULT_NODE_SELECTOR, quorum);
resetAuthorizationContext();
throw new TimeoutException();
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri) {
ServiceStats stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\tAvg\t\tTotal\t\t\tName%n"));
for (ServiceStat st : stats.entries.values()) {
logStat(uri, st, sb);
}
log(sb.toString());
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.getNowMicrosUtc() + host.getOperationTimeoutMicros();
do {
Thread.sleep(2000);
try {
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_6 |
crossvul-java_data_bad_3083_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_6 |
crossvul-java_data_good_3080_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_1 |
crossvul-java_data_good_3080_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.setSystemAuthorizationContext();
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
this.host.resetAuthorizationContext();
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_2 |
crossvul-java_data_bad_3078_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_6 |
crossvul-java_data_good_3077_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3077_2 |
crossvul-java_data_good_3078_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
OperationContext.setAuthorizationContext(null);
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
OperationContext.setAuthorizationContext(null);
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_1 |
crossvul-java_data_good_3081_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = name.intern();
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_0 |
crossvul-java_data_good_3078_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_6 |
crossvul-java_data_bad_3076_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_1 |
crossvul-java_data_good_3081_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_4 |
crossvul-java_data_bad_3076_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleNonPersistedService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
ServiceStat http1AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountDaily));
return false;
}
ServiceStat http1AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountHourly));
return false;
}
ServiceStat http2AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountDaily));
return false;
}
ServiceStat http2AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
@Test
public void serviceStopDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service stop
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
String factoryLink = OnDemandLoadFactoryService.create(this.host);
URI factoryURI = UriUtils.buildUri(this.host, factoryLink);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will stop all the services
// we just created since the memory limit was set so low.
long expectedStopTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedStopTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify stopped services get started.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting stop to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be started
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely stopped) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
}
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
@Test
public void queryServiceUrisWithAuth() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new ExampleNonPersistedService());
this.host.waitForServiceAvailable(ExampleNonPersistedService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
// create user foo@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserFoo = this.host.testCreate(1);
String userFoo = "foo@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userFoo)
.setUserSelfLink(userFoo)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "foo")
.build())
.setCompletion(createUserFoo.getCompletion())
.start();
createUserFoo.await();
// create user bar@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserBar = this.host.testCreate(1);
String userBar = "bar@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userBar)
.setUserSelfLink(userBar)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build())
.setCompletion(createUserBar.getCompletion())
.start();
createUserBar.await();
// create foo & bar documents
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
ExampleServiceState exampleBar = new ExampleServiceState();
exampleBar.name = "bar";
exampleBar.documentSelfLink = "bar";
List<Operation> posts = new ArrayList<>();
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleFoo));
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleBar));
sender.sendAndWait(posts);
AuthTestUtils.resetAuthorizationContext(this.host);
// login as foo
AuthTestUtils.loginAndSetToken(this.host, "foo@example.com", "password");
Operation factoryGetFoo = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultFoo = sender.sendAndWait(factoryGetFoo, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultFoo.documentLinks.size());
assertEquals("/core/nonpersist-examples/foo", factoryGetResultFoo.documentLinks.get(0));
// login as bar
AuthTestUtils.loginAndSetToken(this.host, "bar@example.com", "password");
Operation factoryGetBar = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultBar = sender.sendAndWait(factoryGetBar, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultBar.documentLinks.size());
assertEquals("/core/nonpersist-examples/bar", factoryGetResultBar.documentLinks.get(0));
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
if (!this.host.isStopping()) {
AuthTestUtils.logout(this.host);
}
this.host.tearDown();
this.host = null;
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_3 |
crossvul-java_data_good_3083_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
hostWithAuth.setSystemAuthorizationContext();
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.resetAuthorizationContext();
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_4 |
crossvul-java_data_good_3078_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_3 |
crossvul-java_data_good_3075_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void testUtilityStats() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals(accumulatedValue));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN, AggregationType.MAX));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink));
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version > 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
double maxAvg = 0;
double countPerMaxAvgBin = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.avg != null && bin.avg > maxAvg) {
maxAvg = bin.avg;
countPerMaxAvgBin = bin.count;
}
}
assertTrue(maxAvg > 0);
assertTrue(countPerMaxAvgBin >= 1);
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_4 |
crossvul-java_data_good_3079_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
if (op.hasBody()) {
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (op.getAction()) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceDocument rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_0 |
crossvul-java_data_bad_3078_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_4 |
crossvul-java_data_bad_3081_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
// Create user group
String userGroupLink = createUserGroup(target, getUserGroupName(email),
Builder.create().addFieldClause("email", email).build());
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = UserGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = ResourceGroupState.Builder.create()
.withSelfLink(selfLink)
.withQuery(q)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = RoleState.Builder.create()
.withSelfLink(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink))
.withUserGroupLink(userGroupLink)
.withResourceGroupLink(resourceGroupLink)
.withVerbs(verbs)
.withPolicy(Policy.ALLOW)
.build();
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_6 |
crossvul-java_data_good_3083_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_3 |
crossvul-java_data_bad_3080_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.TestResults;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyChannelContext;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* When {@link #peerNodes} is configured this flag will trigger join of the remote nodes.
*/
public boolean joinNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
if (NettyChannelContext.isALPNEnabled()) {
SslContext http2ClientContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
}
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getErrorResponseBody();
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getSystemNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getSystemNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = new Operation().getId() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.getOperationTimeoutMicros());
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
log("Selecting owner for %s on %s", documentSelfLink, nodeSelector);
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(10)))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
log("Is owner: %s for %s", rsp.isLocalHostOwner, rsp.key);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(fieldName, fieldValue, documentCount,
expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(hostUri, fieldName, fieldValue,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(spec,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QuerySpecification spec,
long documentCount, long expectedResultCount, TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QuerySpecification spec, long documentCount, long expectedResultCount, TestResults testResults) {
long start = System.nanoTime() / 1000;
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = System.nanoTime() / 1000;
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
if (testResults != null) {
String key = spec.query.term.propertyName + " docs/s";
testResults.getReport().all(key, thpt);
}
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.fromNowMicrosUtc(getOperationTimeoutMicros()));
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
ServiceStats stats = this.sender.sendStatsGetAndWait(serviceUri);
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
public void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> double doPutPerService(List<Service> services)
throws Throwable {
return doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> double doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> double doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> double doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PUT, count, properties, services);
}
public double doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
+this.getMaintenanceIntervalMicros());
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri);
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
s.sendRequest(putClone);
});
} else {
s.sendRequest(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
double throughput = ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return throughput;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return throughput;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
return throughput;
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
}
if (!isRemotePeerTest() || (isRemotePeerTest() && this.joinNodes)) {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
setNodeGroupQuorum(quorum, null, nodeGroup);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
if (locationQuorum != null) {
body.setLocationQuorum(locationQuorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public void setNodeGroupQuorum(Integer quorum) throws Throwable {
setNodeGroupQuorum(quorum, (Integer) null);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum) throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
if (quorum != null) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
}
if (locationQuorum != null) {
log("Changing location quorum to %d on group %s", locationQuorum, nodeGroup);
}
setNodeGroupQuorum(quorum, locationQuorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
resetAuthorizationContext();
waitFor("quorum did not converge", () -> {
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (!NodeStatus.AVAILABLE.equals(ns.status)) {
continue;
}
if (quorum != ns.membershipQuorum) {
return false;
}
if (locationQuorum != null && !locationQuorum.equals(ns.locationQuorum)) {
return false;
}
}
}
resetAuthorizationContext();
return true;
});
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h,
long serviceCount, List<URI> exampleURIs, Long expiration) {
createExampleServices(h, serviceCount, exampleURIs, expiration, false);
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration, boolean skipAvailabilityCheck) {
if (!skipAvailabilityCheck) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
}
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri, TestResults testResults) {
ServiceStats serviceStats = logServiceStats(uri);
if (testResults != null) {
testResults.getReport().stats(uri, serviceStats);
}
}
public ServiceStats logServiceStats(URI uri) {
ServiceStats stats = null;
try {
stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\t\tAvg\t\tTotal\t\t\tName%n"));
stats.entries.values().stream()
.sorted((s1, s2) -> s1.name.compareTo(s2.name))
.forEach((s) -> logStat(uri, s, sb));
log(sb.toString());
} catch (Throwable e) {
log("Failure getting stats: %s", e.getMessage());
}
return stats;
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.fromNowMicrosUtc(host.getOperationTimeoutMicros());
do {
Thread.sleep(2000);
try {
if (host.isAuthorizationEnabled()) {
host.setAuthenticationService(new AuthorizationContextService());
}
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getSystemNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3080_7 |
crossvul-java_data_bad_3081_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.TestResults;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyChannelContext;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* When {@link #peerNodes} is configured this flag will trigger join of the remote nodes.
*/
public boolean joinNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
if (NettyChannelContext.isALPNEnabled()) {
SslContext http2ClientContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
}
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getErrorResponseBody();
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
for (VerificationHost peer : this.localPeerHosts.values()) {
peer.setTimeoutSeconds(seconds);
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getSystemNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getSystemNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = new Operation().getId() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.getOperationTimeoutMicros());
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
log("Selecting owner for %s on %s", documentSelfLink, nodeSelector);
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(10)))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
log("Is owner: %s for %s", rsp.isLocalHostOwner, rsp.key);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(fieldName, fieldValue, documentCount,
expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(hostUri, fieldName, fieldValue,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(spec,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QuerySpecification spec,
long documentCount, long expectedResultCount, TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QuerySpecification spec, long documentCount, long expectedResultCount, TestResults testResults) {
long start = System.nanoTime() / 1000;
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (spec.resultLimit != null) {
task = getServiceState(null,
QueryTask.class,
UriUtils.buildUri(hostUri, task.results.nextPageLink));
}
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = System.nanoTime() / 1000;
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
if (testResults != null) {
String key = spec.query.term.propertyName + " docs/s";
testResults.getReport().all(key, thpt);
}
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.fromNowMicrosUtc(getOperationTimeoutMicros()));
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
ServiceStats stats = this.sender.sendStatsGetAndWait(serviceUri);
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
public void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> double doPutPerService(List<Service> services)
throws Throwable {
return doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> double doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> double doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> double doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PUT, count, properties, services);
}
public double doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
+this.getMaintenanceIntervalMicros());
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri);
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
s.sendRequest(putClone);
});
} else {
s.sendRequest(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
double throughput = ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return throughput;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return throughput;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
return throughput;
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
}
if (!isRemotePeerTest() || (isRemotePeerTest() && this.joinNodes)) {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence() {
ArrayList<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.extendUri(this.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
waitForNodeGroupConvergence(nodeGroupUris, 0, null, new HashMap<>(), false);
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
waitFor("peer gossip stats not found", () -> {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
int peerCount = defaultNodeGroupsPerHost.size();
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
if (stats.entries.isEmpty()) {
return false;
}
int gossipPatchStatCount = 0;
for (ServiceStat st : stats.entries.values()) {
if (!st.name
.contains(NodeGroupService.STAT_NAME_PREFIX_GOSSIP_PATCH_DURATION)) {
continue;
}
gossipPatchStatCount++;
if (st.logHistogram == null) {
return false;
}
if (st.timeSeriesStats == null) {
return false;
}
if (st.version < 1) {
return false;
}
}
if (gossipPatchStatCount != peerCount - 1) {
return false;
}
}
return true;
});
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
setNodeGroupQuorum(quorum, null, nodeGroup);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
if (locationQuorum != null) {
body.setLocationQuorum(locationQuorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public void setNodeGroupQuorum(Integer quorum) throws Throwable {
setNodeGroupQuorum(quorum, (Integer) null);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum) throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
if (quorum != null) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
}
if (locationQuorum != null) {
log("Changing location quorum to %d on group %s", locationQuorum, nodeGroup);
}
setNodeGroupQuorum(quorum, locationQuorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
resetAuthorizationContext();
waitFor("quorum did not converge", () -> {
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (!NodeStatus.AVAILABLE.equals(ns.status)) {
continue;
}
if (quorum != ns.membershipQuorum) {
return false;
}
if (locationQuorum != null && !locationQuorum.equals(ns.locationQuorum)) {
return false;
}
}
}
resetAuthorizationContext();
return true;
});
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
/**
* @return list of full urls of the created example services
*/
public List<URI> createExampleServices(ServiceHost h, long serviceCount, Long expiration) {
return createExampleServices(h, serviceCount, expiration, false);
}
/**
* @return list of full urls of the created example services
*/
public List<URI> createExampleServices(ServiceHost h, long serviceCount, Long expiration, boolean skipAvailabilityCheck) {
if (!skipAvailabilityCheck) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
}
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
ExampleServiceState initState = new ExampleServiceState();
initState.counter = 123L;
if (expiration != null) {
initState.documentExpirationTimeMicros = expiration;
}
initState.name = initState.documentSelfLink = UUID.randomUUID().toString();
Operation post = Operation.createPost(UriUtils.buildFactoryUri(h, ExampleService.class)).setBody(initState);
ops.add(post);
}
List<ExampleServiceState> result = this.sender.sendAndWait(ops, ExampleServiceState.class);
// returns list of full url
return result.stream()
.map(state -> UriUtils.extendUri(h.getUri(), state.documentSelfLink))
.collect(toList());
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri, TestResults testResults) {
ServiceStats serviceStats = logServiceStats(uri);
if (testResults != null) {
testResults.getReport().stats(uri, serviceStats);
}
}
public ServiceStats logServiceStats(URI uri) {
ServiceStats stats = null;
try {
stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\t\tAvg\t\tTotal\t\t\tName%n"));
stats.entries.values().stream()
.sorted((s1, s2) -> s1.name.compareTo(s2.name))
.forEach((s) -> logStat(uri, s, sb));
log(sb.toString());
} catch (Throwable e) {
log("Failure getting stats: %s", e.getMessage());
}
return stats;
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles operation tracing on the service host using the management service
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
toggleOperationTracing(baseHostURI, null, enable);
}
/**
* Toggles operation tracing on the service host using the management service
*/
public void toggleOperationTracing(URI baseHostURI, Level level, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
if (level != null) {
r.level = level.toString();
}
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
// we convert body to JSON to verify client requests using HTTP client
// with JSON, will work
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(Utils.toJson(r)));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false, true);
}
public void deleteOrStopAllChildServices(
URI factoryURI, boolean stopOnly, boolean useFullQuorum) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
if (useFullQuorum) {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true if host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host, boolean failOnIndexDeletion)
throws Throwable {
long exp = Utils.fromNowMicrosUtc(host.getOperationTimeoutMicros());
do {
Thread.sleep(2000);
try {
if (host.isAuthorizationEnabled()) {
host.setAuthenticationService(new AuthorizationContextService());
}
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException && !failOnIndexDeletion) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getSystemNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_7 |
crossvul-java_data_bad_2469_0 | package cz.metacentrum.perun.core.impl;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.GroupsManager;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceUnsupportedOperationException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.SubjectNotExistsException;
import cz.metacentrum.perun.core.blImpl.PerunBlImpl;
import cz.metacentrum.perun.core.implApi.ExtSourceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Ext source implementation for LDAP.
*
* @author Michal Prochazka michalp@ics.muni.cz
* @author Pavel Zlámal <zlamal@cesnet.cz>
*/
public class ExtSourceLdap extends ExtSource implements ExtSourceApi {
protected Map<String, String> mapping;
protected final static Logger log = LoggerFactory.getLogger(ExtSourceLdap.class);
protected DirContext dirContext = null;
protected String filteredQuery = null;
protected DirContext getContext() throws InternalErrorException {
if (dirContext == null) {
initContext();
}
return dirContext;
}
private static PerunBlImpl perunBl;
// filled by spring (perun-core.xml)
public static PerunBlImpl setPerunBlImpl(PerunBlImpl perun) {
perunBl = perun;
return perun;
}
@Override
public List<Map<String,String>> findSubjectsLogins(String searchString) throws InternalErrorException {
return findSubjectsLogins(searchString, 0);
}
@Override
public List<Map<String,String>> findSubjectsLogins(String searchString, int maxResults) throws InternalErrorException {
// Prepare searchQuery
// attributes.get("query") contains query template, e.g. (uid=?), ? will be replaced by the searchString
String query = getAttributes().get("query");
if (query == null) {
throw new InternalErrorException("query attributes is required");
}
query = query.replaceAll("\\?", searchString);
String base = getAttributes().get("base");
if (base == null) {
throw new InternalErrorException("base attributes is required");
}
return this.querySource(query, base, maxResults);
}
@Override
public Map<String, String> getSubjectByLogin(String login) throws InternalErrorException, SubjectNotExistsException {
// Prepare searchQuery
// attributes.get("loginQuery") contains query template, e.g. (uid=?), ? will be replaced by the login
String query = getAttributes().get("loginQuery");
if (query == null) {
throw new InternalErrorException("loginQuery attributes is required");
}
query = query.replaceAll("\\?", login);
String base = getAttributes().get("base");
if (base == null) {
throw new InternalErrorException("base attributes is required");
}
List<Map<String, String>> subjects = this.querySource(query, base, 0);
if (subjects.size() > 1) {
throw new SubjectNotExistsException("There are more than one results for the login: " + login);
}
if (subjects.size() == 0) {
throw new SubjectNotExistsException(login);
}
return subjects.get(0);
}
@Override
public List<Map<String, String>> getGroupSubjects(Map<String, String> attributes) throws InternalErrorException {
List<String> ldapGroupSubjects = new ArrayList<>();
// Get the LDAP group name
String ldapGroupName = attributes.get(GroupsManager.GROUPMEMBERSQUERY_ATTRNAME);
// Get optional filter for members filtering
String filter = attributes.get(GroupsManager.GROUPMEMBERSFILTER_ATTRNAME);
try {
log.trace("LDAP External Source: searching for group subjects [{}]", ldapGroupName);
String attrName;
// Default value
attrName = getAttributes().getOrDefault("memberAttribute", "uniqueMember");
List<String> retAttrs = new ArrayList<>();
retAttrs.add(attrName);
String[] retAttrsArray = retAttrs.toArray(new String[0]);
Attributes attrs = getContext().getAttributes(ldapGroupName, retAttrsArray);
Attribute ldapAttribute = null;
// Get the list of returned groups, should be only one
if (attrs.get(attrName) != null) {
// Get the attribute which holds group subjects
ldapAttribute = attrs.get(attrName);
}
if (ldapAttribute != null) {
// Get the DNs of the subjects
for (int i=0; i < ldapAttribute.size(); i++) {
String ldapSubjectDN = (String) ldapAttribute.get(i);
ldapGroupSubjects.add(ldapSubjectDN);
log.trace("LDAP External Source: found group subject [{}].", ldapSubjectDN);
}
}
List<Map<String, String>> subjects = new ArrayList<>();
// If attribute filter not exists, use optional default filter from extSource definition
if(filter == null) filter = filteredQuery;
// Now query LDAP again and search for each subject
for (String ldapSubjectName : ldapGroupSubjects) {
subjects.addAll(this.querySource(filter, ldapSubjectName, 0));
}
return subjects;
} catch (NamingException e) {
log.error("LDAP exception during running query '{}'", ldapGroupName);
throw new InternalErrorException("Entry '"+ldapGroupName+"' was not found in LDAP." , e);
}
}
@Override
public List<Map<String, String>> getUsersSubjects() throws ExtSourceUnsupportedOperationException {
throw new ExtSourceUnsupportedOperationException();
}
protected void initContext() throws InternalErrorException {
// Load mapping between LDAP attributes and Perun attributes
Hashtable<String,String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
if (getAttributes().containsKey("referral")) {
env.put(Context.REFERRAL, getAttributes().get("referral"));
}
if (getAttributes().containsKey("url")) {
env.put(Context.PROVIDER_URL, getAttributes().get("url"));
} else {
throw new InternalErrorException("url attributes is required");
}
if (getAttributes().containsKey("user")) {
env.put(Context.SECURITY_PRINCIPAL, getAttributes().get("user"));
}
if (getAttributes().containsKey("password")) {
env.put(Context.SECURITY_CREDENTIALS, getAttributes().get("password"));
}
if (getAttributes().containsKey("filteredQuery")) {
filteredQuery = getAttributes().get("filteredQuery");
}
try {
// ldapMapping contains entries like: firstName={givenName},lastName={sn},email={mail}
if (getAttributes().get("ldapMapping") == null) {
throw new InternalErrorException("ldapMapping attributes is required");
}
String[] ldapMapping = getAttributes().get("ldapMapping").trim().split(",\n");
mapping = new HashMap<>();
for (String entry: ldapMapping) {
String[] values = entry.trim().split("=", 2);
mapping.put(values[0].trim(), values[1].trim());
}
this.dirContext = new InitialDirContext(env);
} catch (NamingException e) {
log.error("LDAP exception during creating the context.");
throw new InternalErrorException(e);
}
}
protected Map<String,String> getSubjectAttributes(Attributes attributes) throws InternalErrorException {
Pattern pattern = Pattern.compile("\\{([^}])*}");
Map<String, String> map = new HashMap<>();
for (String key: mapping.keySet()) {
// Get attribute value and substitute all {} in the string
Matcher matcher = pattern.matcher(mapping.get(key));
String value = mapping.get(key);
// Find all matches
while (matcher.find()) {
// Get the matching string
String ldapAttributeNameRaw = matcher.group();
String ldapAttributeName = ldapAttributeNameRaw.replaceAll("\\{([^}]*)}", "$1"); // ldapAttributeNameRaw is encapsulate with {}, so remove it
// Replace {ldapAttrName} with the value
value = value.replace(ldapAttributeNameRaw, getLdapAttributeValue(attributes, ldapAttributeName));
log.trace("ExtSourceLDAP: Retrieved value {} of attribute {} for {} and storing into the key {}.", value, ldapAttributeName, ldapAttributeNameRaw, key);
}
map.put(key, value);
}
return map;
}
protected String getLdapAttributeValue(Attributes attributes, String ldapAttrNameRaw) throws InternalErrorException {
String ldapAttrName;
String rule = null;
Matcher matcher;
String attrValue = "";
// Check if the ldapAttrName contains regex
if (ldapAttrNameRaw.contains("|")) {
int splitter = ldapAttrNameRaw.indexOf('|');
ldapAttrName = ldapAttrNameRaw.substring(0,splitter);
rule = ldapAttrNameRaw.substring(splitter+1);
} else {
ldapAttrName = ldapAttrNameRaw;
}
// Check if the ldapAttrName contains specification of the value index
int attributeValueIndex = -1;
if (ldapAttrNameRaw.contains("[")) {
Pattern indexPattern = Pattern.compile("^(.*)\\[([0-9]+)]$");
Matcher indexMatcher = indexPattern.matcher(ldapAttrNameRaw);
if (indexMatcher.find()) {
ldapAttrName = indexMatcher.group(1);
attributeValueIndex = Integer.parseInt(indexMatcher.group(2));
} else {
throw new InternalErrorException("Wrong attribute name format for attribute: " + ldapAttrNameRaw + ", it should be name[0-9+]");
}
}
// Mapping to the LDAP attribute
Attribute attr = attributes.get(ldapAttrName);
if (attr != null) {
// There could be more than one value in the attribute. Separator is defined in the AttributesManagerImpl
for (int i = 0; i < attr.size(); i++) {
if (attributeValueIndex != -1 && attributeValueIndex != i) {
// We want only value on concrete index, so skip the other ones
continue;
}
String tmpAttrValue;
try {
if(attr.get() instanceof byte[]) {
// It can be byte array with cert or binary file
char[] encodedValue = Base64Coder.encode((byte[]) attr.get());
tmpAttrValue = new String(encodedValue);
} else {
tmpAttrValue = (String) attr.get(i);
}
} catch (NamingException e) {
throw new InternalErrorException(e);
}
if (rule != null) {
if(rule.contains("#")) {
// Rules are in place, so apply them
String regex = rule.substring(0, rule.indexOf('#'));
String replacement = rule.substring(rule.indexOf('#')+1);
tmpAttrValue = tmpAttrValue.replaceAll(regex, replacement);
//DEPRECATED way
} else {
// Rules are in place, so apply them
Pattern pattern = Pattern.compile(rule);
matcher = pattern.matcher(tmpAttrValue);
// Get the first group which matched
if (matcher.matches()) {
tmpAttrValue = matcher.group(1);
}
}
}
if (i == 0 || attributeValueIndex != -1) {
// Do not add delimiter before first entry or if the particular index has been requested
attrValue += tmpAttrValue;
} else {
attrValue += AttributesManagerImpl.LIST_DELIMITER + tmpAttrValue;
}
}
if (attrValue.isEmpty()) {
return "";
} else {
return attrValue;
}
} else {
return "";
}
}
/**
* Query LDAP using query in defined base. Results can be limited to the maxResults.
*
* @param query
* @param base
* @param maxResults
* @return List of Map of the LDAP attribute names and theirs values
* @throws InternalErrorException
*/
protected List<Map<String,String>> querySource(String query, String base, int maxResults) throws InternalErrorException {
NamingEnumeration<SearchResult> results = null;
List<Map<String, String>> subjects = new ArrayList<>();
try {
// If query is null, then we are finding object by the base
if (query == null) {
log.trace("search base [{}]", base);
// TODO jmena atributu spise prijimiat pres vstupni parametr metody
Attributes ldapAttributes = getContext().getAttributes(base);
if (ldapAttributes.size() > 0) {
Map<String, String> attributes = this.getSubjectAttributes(ldapAttributes);
if (!attributes.isEmpty()) {
subjects.add(attributes);
}
}
} else {
log.trace("search string [{}]", query);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Set timeout to 5s
controls.setTimeLimit(5000);
if (maxResults > 0) {
controls.setCountLimit(maxResults);
}
if (base == null) base = "";
results = getContext().search(base, query, controls);
while (results.hasMore()) {
SearchResult searchResult = results.next();
Attributes attributes = searchResult.getAttributes();
Map<String,String> subjectAttributes = this.getSubjectAttributes(attributes);
if (!subjectAttributes.isEmpty()) {
subjects.add(subjectAttributes);
}
}
}
log.trace("Returning [{}] subjects", subjects.size());
return subjects;
} catch (NamingException e) {
log.error("LDAP exception during running query '{}'", query);
throw new InternalErrorException("LDAP exception during running query: "+query+".", e);
} finally {
try {
if (results != null) { results.close(); }
} catch (Exception e) {
log.error("LDAP exception during closing result, while running query '{}'", query);
throw new InternalErrorException(e);
}
}
}
@Override
public void close() throws InternalErrorException {
if (this.dirContext != null) {
try {
this.dirContext.close();
this.dirContext = null;
} catch (NamingException e) {
throw new InternalErrorException(e);
}
}
}
@Override
public List<Map<String, String>> getSubjectGroups(Map<String, String> attributes) throws ExtSourceUnsupportedOperationException {
throw new ExtSourceUnsupportedOperationException();
}
@Override
public List<Map<String, String>> findSubjects(String searchString) throws InternalErrorException {
return findSubjects(searchString, 0);
}
@Override
public List<Map<String, String>> findSubjects(String searchString, int maxResults) throws InternalErrorException {
// We can call original implementation, since LDAP always return whole entry and not just login
return findSubjectsLogins(searchString, maxResults);
}
protected Map<String,String> getAttributes() throws InternalErrorException {
return perunBl.getExtSourcesManagerBl().getAttributes(this);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_2469_0 |
crossvul-java_data_good_3078_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3078_2 |
crossvul-java_data_good_3081_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationContext;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.TestResults;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyChannelContext;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* When {@link #peerNodes} is configured this flag will trigger join of the remote nodes.
*/
public boolean joinNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
if (NettyChannelContext.isALPNEnabled()) {
SslContext http2ClientContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
}
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getErrorResponseBody();
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
for (VerificationHost peer : this.localPeerHosts.values()) {
peer.setTimeoutSeconds(seconds);
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getSystemNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getSystemNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = new Operation().getId() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.getOperationTimeoutMicros());
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
log("Selecting owner for %s on %s", documentSelfLink, nodeSelector);
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(10)))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
log("Is owner: %s for %s", rsp.isLocalHostOwner, rsp.key);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(fieldName, fieldValue, documentCount,
expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(hostUri, fieldName, fieldValue,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(spec,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QuerySpecification spec,
long documentCount, long expectedResultCount, TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QuerySpecification spec, long documentCount, long expectedResultCount, TestResults testResults) {
long start = System.nanoTime() / 1000;
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (spec.resultLimit != null) {
task = getServiceState(null,
QueryTask.class,
UriUtils.buildUri(hostUri, task.results.nextPageLink));
}
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = System.nanoTime() / 1000;
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
if (testResults != null) {
String key = spec.query.term.propertyName + " docs/s";
testResults.getReport().all(key, thpt);
}
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.fromNowMicrosUtc(getOperationTimeoutMicros()));
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
AuthorizationContext ctx = null;
if (this.isAuthorizationEnabled()) {
ctx = OperationContext.getAuthorizationContext();
this.setSystemAuthorizationContext();
}
ServiceStats stats = this.sender.sendStatsGetAndWait(serviceUri);
if (this.isAuthorizationEnabled()) {
this.setAuthorizationContext(ctx);
}
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
public void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> double doPutPerService(List<Service> services)
throws Throwable {
return doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> double doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> double doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> double doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PUT, count, properties, services);
}
public double doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
+this.getMaintenanceIntervalMicros());
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri);
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
s.sendRequest(putClone);
});
} else {
s.sendRequest(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
double throughput = ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return throughput;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return throughput;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
return throughput;
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
}
if (!isRemotePeerTest() || (isRemotePeerTest() && this.joinNodes)) {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence() {
ArrayList<URI> nodeGroupUris = new ArrayList<>();
nodeGroupUris.add(UriUtils.extendUri(this.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
waitForNodeGroupConvergence(nodeGroupUris, 0, null, new HashMap<>(), false);
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
waitFor("peer gossip stats not found", () -> {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
int peerCount = defaultNodeGroupsPerHost.size();
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
if (stats.entries.isEmpty()) {
return false;
}
int gossipPatchStatCount = 0;
for (ServiceStat st : stats.entries.values()) {
if (!st.name
.contains(NodeGroupService.STAT_NAME_PREFIX_GOSSIP_PATCH_DURATION)) {
continue;
}
gossipPatchStatCount++;
if (st.logHistogram == null) {
return false;
}
if (st.timeSeriesStats == null) {
return false;
}
if (st.version < 1) {
return false;
}
}
if (gossipPatchStatCount != peerCount - 1) {
return false;
}
}
return true;
});
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
setNodeGroupQuorum(quorum, null, nodeGroup);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
if (locationQuorum != null) {
body.setLocationQuorum(locationQuorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public void setNodeGroupQuorum(Integer quorum) throws Throwable {
setNodeGroupQuorum(quorum, (Integer) null);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum) throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
if (quorum != null) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
}
if (locationQuorum != null) {
log("Changing location quorum to %d on group %s", locationQuorum, nodeGroup);
}
setNodeGroupQuorum(quorum, locationQuorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
resetAuthorizationContext();
waitFor("quorum did not converge", () -> {
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (!NodeStatus.AVAILABLE.equals(ns.status)) {
continue;
}
if (quorum != ns.membershipQuorum) {
return false;
}
if (locationQuorum != null && !locationQuorum.equals(ns.locationQuorum)) {
return false;
}
}
}
resetAuthorizationContext();
return true;
});
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
/**
* @return list of full urls of the created example services
*/
public List<URI> createExampleServices(ServiceHost h, long serviceCount, Long expiration) {
return createExampleServices(h, serviceCount, expiration, false);
}
/**
* @return list of full urls of the created example services
*/
public List<URI> createExampleServices(ServiceHost h, long serviceCount, Long expiration, boolean skipAvailabilityCheck) {
if (!skipAvailabilityCheck) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
}
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
ExampleServiceState initState = new ExampleServiceState();
initState.counter = 123L;
if (expiration != null) {
initState.documentExpirationTimeMicros = expiration;
}
initState.name = initState.documentSelfLink = UUID.randomUUID().toString();
Operation post = Operation.createPost(UriUtils.buildFactoryUri(h, ExampleService.class)).setBody(initState);
ops.add(post);
}
List<ExampleServiceState> result = this.sender.sendAndWait(ops, ExampleServiceState.class);
// returns list of full url
return result.stream()
.map(state -> UriUtils.extendUri(h.getUri(), state.documentSelfLink))
.collect(toList());
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri, TestResults testResults) {
ServiceStats serviceStats = logServiceStats(uri);
if (testResults != null) {
testResults.getReport().stats(uri, serviceStats);
}
}
public ServiceStats logServiceStats(URI uri) {
ServiceStats stats = null;
try {
stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\t\tAvg\t\tTotal\t\t\tName%n"));
stats.entries.values().stream()
.sorted((s1, s2) -> s1.name.compareTo(s2.name))
.forEach((s) -> logStat(uri, s, sb));
log(sb.toString());
} catch (Throwable e) {
log("Failure getting stats: %s", e.getMessage());
}
return stats;
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles operation tracing on the service host using the management service
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
toggleOperationTracing(baseHostURI, null, enable);
}
/**
* Toggles operation tracing on the service host using the management service
*/
public void toggleOperationTracing(URI baseHostURI, Level level, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
if (level != null) {
r.level = level.toString();
}
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
// we convert body to JSON to verify client requests using HTTP client
// with JSON, will work
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(Utils.toJson(r)));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false, true);
}
public void deleteOrStopAllChildServices(
URI factoryURI, boolean stopOnly, boolean useFullQuorum) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
if (useFullQuorum) {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true if host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host, boolean failOnIndexDeletion)
throws Throwable {
long exp = Utils.fromNowMicrosUtc(host.getOperationTimeoutMicros());
do {
Thread.sleep(2000);
try {
if (host.isAuthorizationEnabled()) {
host.setAuthenticationService(new AuthorizationContextService());
}
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException && !failOnIndexDeletion) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getSystemNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_7 |
crossvul-java_data_good_3076_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_2 |
crossvul-java_data_good_3075_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.OperationContext;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
@Override
protected void configureLoggerFormatter(Logger logger) {
super.configureLoggerFormatter(logger);
// override with formatters for VerificationHost
// if custom formatter has already set, do NOT replace it.
for (Handler h : logger.getParent().getHandlers()) {
if (Objects.equals(h.getFormatter(), LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.NORMAL_FORMAT);
} else if (Objects.equals(h.getFormatter(), COLOR_LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.COLORED_FORMAT);
}
}
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getBody(ServiceErrorResponse.class);
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = Utils.getNowMicrosUtc() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getOperationTimeoutMicros();
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
log("Starting query with options:%s, resultLimit: %d",
create.querySpec.options,
create.querySpec.resultLimit);
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(10))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QueryTask.QuerySpecification spec, long documentCount, long expectedResultCount) {
long start = Utils.getNowMicrosUtc();
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = Utils.getNowMicrosUtc();
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.getNowMicrosUtc() + getOperationTimeoutMicros());
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
AuthorizationContext ctx = null;
if (this.isAuthorizationEnabled()) {
ctx = OperationContext.getAuthorizationContext();
this.setSystemAuthorizationContext();
}
ServiceStats stats = this.getServiceState(
null, ServiceStats.class, UriUtils.buildStatsUri(serviceUri));
if (this.isAuthorizationEnabled()) {
this.setAuthorizationContext(ctx);
}
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
private void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> void doPutPerService(List<Service> services)
throws Throwable {
doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> void doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> void doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> void doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PUT, count, properties, services);
}
public void doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getMaintenanceIntervalMicros();
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri).setReferer(getReferer());
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
send(putClone);
});
} else if (properties.contains(TestProperty.CALLBACK_SEND)) {
updateOp.toggleOption(OperationOption.SEND_WITH_CALLBACK, true);
send(updateOp.setBody(b));
} else {
send(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
} else {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum)
throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
setNodeGroupQuorum(quorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
Date exp = getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (quorum != ns.membershipQuorum) {
isConverged = false;
}
}
}
resetAuthorizationContext();
if (isConverged) {
log("converged");
return;
}
Thread.sleep(500);
}
waitForNodeSelectorQuorumConvergence(ServiceUriPaths.DEFAULT_NODE_SELECTOR, quorum);
resetAuthorizationContext();
throw new TimeoutException();
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri) {
ServiceStats stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\tAvg\t\tTotal\t\t\tName%n"));
for (ServiceStat st : stats.entries.values()) {
logStat(uri, st, sb);
}
log(sb.toString());
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.getNowMicrosUtc() + host.getOperationTimeoutMicros();
do {
Thread.sleep(2000);
try {
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_6 |
crossvul-java_data_good_2469_0 | package cz.metacentrum.perun.core.impl;
import cz.metacentrum.perun.core.api.ExtSource;
import cz.metacentrum.perun.core.api.GroupsManager;
import cz.metacentrum.perun.core.api.exceptions.ExtSourceUnsupportedOperationException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.SubjectNotExistsException;
import cz.metacentrum.perun.core.blImpl.PerunBlImpl;
import cz.metacentrum.perun.core.implApi.ExtSourceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Ext source implementation for LDAP.
*
* @author Michal Prochazka michalp@ics.muni.cz
* @author Pavel Zlámal <zlamal@cesnet.cz>
*/
public class ExtSourceLdap extends ExtSource implements ExtSourceApi {
protected Map<String, String> mapping;
protected final static Logger log = LoggerFactory.getLogger(ExtSourceLdap.class);
protected DirContext dirContext = null;
protected String filteredQuery = null;
protected DirContext getContext() throws InternalErrorException {
if (dirContext == null) {
initContext();
}
return dirContext;
}
private static PerunBlImpl perunBl;
// filled by spring (perun-core.xml)
public static PerunBlImpl setPerunBlImpl(PerunBlImpl perun) {
perunBl = perun;
return perun;
}
@Override
public List<Map<String,String>> findSubjectsLogins(String searchString) throws InternalErrorException {
return findSubjectsLogins(searchString, 0);
}
@Override
public List<Map<String,String>> findSubjectsLogins(String searchString, int maxResults) throws InternalErrorException {
// Prepare searchQuery
// attributes.get("query") contains query template, e.g. (uid=?), ? will be replaced by the searchString
String query = getAttributes().get("query");
if (query == null) {
throw new InternalErrorException("query attributes is required");
}
query = query.replace("?", Utils.escapeStringForLDAP(searchString));
String base = getAttributes().get("base");
if (base == null) {
throw new InternalErrorException("base attributes is required");
}
return this.querySource(query, base, maxResults);
}
@Override
public Map<String, String> getSubjectByLogin(String login) throws InternalErrorException, SubjectNotExistsException {
// Prepare searchQuery
// attributes.get("loginQuery") contains query template, e.g. (uid=?), ? will be replaced by the login
String query = getAttributes().get("loginQuery");
if (query == null) {
throw new InternalErrorException("loginQuery attributes is required");
}
query = query.replace("?", Utils.escapeStringForLDAP(login));
String base = getAttributes().get("base");
if (base == null) {
throw new InternalErrorException("base attributes is required");
}
List<Map<String, String>> subjects = this.querySource(query, base, 0);
if (subjects.size() > 1) {
throw new SubjectNotExistsException("There are more than one results for the login: " + login);
}
if (subjects.size() == 0) {
throw new SubjectNotExistsException(login);
}
return subjects.get(0);
}
@Override
public List<Map<String, String>> getGroupSubjects(Map<String, String> attributes) throws InternalErrorException {
List<String> ldapGroupSubjects = new ArrayList<>();
// Get the LDAP group name
String ldapGroupName = attributes.get(GroupsManager.GROUPMEMBERSQUERY_ATTRNAME);
// Get optional filter for members filtering
String filter = attributes.get(GroupsManager.GROUPMEMBERSFILTER_ATTRNAME);
try {
log.trace("LDAP External Source: searching for group subjects [{}]", ldapGroupName);
String attrName;
// Default value
attrName = getAttributes().getOrDefault("memberAttribute", "uniqueMember");
List<String> retAttrs = new ArrayList<>();
retAttrs.add(attrName);
String[] retAttrsArray = retAttrs.toArray(new String[0]);
Attributes attrs = getContext().getAttributes(ldapGroupName, retAttrsArray);
Attribute ldapAttribute = null;
// Get the list of returned groups, should be only one
if (attrs.get(attrName) != null) {
// Get the attribute which holds group subjects
ldapAttribute = attrs.get(attrName);
}
if (ldapAttribute != null) {
// Get the DNs of the subjects
for (int i=0; i < ldapAttribute.size(); i++) {
String ldapSubjectDN = (String) ldapAttribute.get(i);
ldapGroupSubjects.add(ldapSubjectDN);
log.trace("LDAP External Source: found group subject [{}].", ldapSubjectDN);
}
}
List<Map<String, String>> subjects = new ArrayList<>();
// If attribute filter not exists, use optional default filter from extSource definition
if(filter == null) filter = filteredQuery;
// Now query LDAP again and search for each subject
for (String ldapSubjectName : ldapGroupSubjects) {
subjects.addAll(this.querySource(filter, ldapSubjectName, 0));
}
return subjects;
} catch (NamingException e) {
log.error("LDAP exception during running query '{}'", ldapGroupName);
throw new InternalErrorException("Entry '"+ldapGroupName+"' was not found in LDAP." , e);
}
}
@Override
public List<Map<String, String>> getUsersSubjects() throws ExtSourceUnsupportedOperationException {
throw new ExtSourceUnsupportedOperationException();
}
protected void initContext() throws InternalErrorException {
// Load mapping between LDAP attributes and Perun attributes
Hashtable<String,String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
if (getAttributes().containsKey("referral")) {
env.put(Context.REFERRAL, getAttributes().get("referral"));
}
if (getAttributes().containsKey("url")) {
env.put(Context.PROVIDER_URL, getAttributes().get("url"));
} else {
throw new InternalErrorException("url attributes is required");
}
if (getAttributes().containsKey("user")) {
env.put(Context.SECURITY_PRINCIPAL, getAttributes().get("user"));
}
if (getAttributes().containsKey("password")) {
env.put(Context.SECURITY_CREDENTIALS, getAttributes().get("password"));
}
if (getAttributes().containsKey("filteredQuery")) {
filteredQuery = getAttributes().get("filteredQuery");
}
try {
// ldapMapping contains entries like: firstName={givenName},lastName={sn},email={mail}
if (getAttributes().get("ldapMapping") == null) {
throw new InternalErrorException("ldapMapping attributes is required");
}
String[] ldapMapping = getAttributes().get("ldapMapping").trim().split(",\n");
mapping = new HashMap<>();
for (String entry: ldapMapping) {
String[] values = entry.trim().split("=", 2);
mapping.put(values[0].trim(), values[1].trim());
}
this.dirContext = new InitialDirContext(env);
} catch (NamingException e) {
log.error("LDAP exception during creating the context.");
throw new InternalErrorException(e);
}
}
protected Map<String,String> getSubjectAttributes(Attributes attributes) throws InternalErrorException {
Pattern pattern = Pattern.compile("\\{([^}])*}");
Map<String, String> map = new HashMap<>();
for (String key: mapping.keySet()) {
// Get attribute value and substitute all {} in the string
Matcher matcher = pattern.matcher(mapping.get(key));
String value = mapping.get(key);
// Find all matches
while (matcher.find()) {
// Get the matching string
String ldapAttributeNameRaw = matcher.group();
String ldapAttributeName = ldapAttributeNameRaw.replaceAll("\\{([^}]*)}", "$1"); // ldapAttributeNameRaw is encapsulate with {}, so remove it
// Replace {ldapAttrName} with the value
value = value.replace(ldapAttributeNameRaw, getLdapAttributeValue(attributes, ldapAttributeName));
log.trace("ExtSourceLDAP: Retrieved value {} of attribute {} for {} and storing into the key {}.", value, ldapAttributeName, ldapAttributeNameRaw, key);
}
map.put(key, value);
}
return map;
}
protected String getLdapAttributeValue(Attributes attributes, String ldapAttrNameRaw) throws InternalErrorException {
String ldapAttrName;
String rule = null;
Matcher matcher;
String attrValue = "";
// Check if the ldapAttrName contains regex
if (ldapAttrNameRaw.contains("|")) {
int splitter = ldapAttrNameRaw.indexOf('|');
ldapAttrName = ldapAttrNameRaw.substring(0,splitter);
rule = ldapAttrNameRaw.substring(splitter+1);
} else {
ldapAttrName = ldapAttrNameRaw;
}
// Check if the ldapAttrName contains specification of the value index
int attributeValueIndex = -1;
if (ldapAttrNameRaw.contains("[")) {
Pattern indexPattern = Pattern.compile("^(.*)\\[([0-9]+)]$");
Matcher indexMatcher = indexPattern.matcher(ldapAttrNameRaw);
if (indexMatcher.find()) {
ldapAttrName = indexMatcher.group(1);
attributeValueIndex = Integer.parseInt(indexMatcher.group(2));
} else {
throw new InternalErrorException("Wrong attribute name format for attribute: " + ldapAttrNameRaw + ", it should be name[0-9+]");
}
}
// Mapping to the LDAP attribute
Attribute attr = attributes.get(ldapAttrName);
if (attr != null) {
// There could be more than one value in the attribute. Separator is defined in the AttributesManagerImpl
for (int i = 0; i < attr.size(); i++) {
if (attributeValueIndex != -1 && attributeValueIndex != i) {
// We want only value on concrete index, so skip the other ones
continue;
}
String tmpAttrValue;
try {
if(attr.get() instanceof byte[]) {
// It can be byte array with cert or binary file
char[] encodedValue = Base64Coder.encode((byte[]) attr.get());
tmpAttrValue = new String(encodedValue);
} else {
tmpAttrValue = (String) attr.get(i);
}
} catch (NamingException e) {
throw new InternalErrorException(e);
}
if (rule != null) {
if(rule.contains("#")) {
// Rules are in place, so apply them
String regex = rule.substring(0, rule.indexOf('#'));
String replacement = rule.substring(rule.indexOf('#')+1);
tmpAttrValue = tmpAttrValue.replaceAll(regex, replacement);
//DEPRECATED way
} else {
// Rules are in place, so apply them
Pattern pattern = Pattern.compile(rule);
matcher = pattern.matcher(tmpAttrValue);
// Get the first group which matched
if (matcher.matches()) {
tmpAttrValue = matcher.group(1);
}
}
}
if (i == 0 || attributeValueIndex != -1) {
// Do not add delimiter before first entry or if the particular index has been requested
attrValue += tmpAttrValue;
} else {
attrValue += AttributesManagerImpl.LIST_DELIMITER + tmpAttrValue;
}
}
if (attrValue.isEmpty()) {
return "";
} else {
return attrValue;
}
} else {
return "";
}
}
/**
* Query LDAP using query in defined base. Results can be limited to the maxResults.
*
* @param query
* @param base
* @param maxResults
* @return List of Map of the LDAP attribute names and theirs values
* @throws InternalErrorException
*/
protected List<Map<String,String>> querySource(String query, String base, int maxResults) throws InternalErrorException {
NamingEnumeration<SearchResult> results = null;
List<Map<String, String>> subjects = new ArrayList<>();
try {
// If query is null, then we are finding object by the base
if (query == null) {
log.trace("search base [{}]", base);
// TODO jmena atributu spise prijimiat pres vstupni parametr metody
Attributes ldapAttributes = getContext().getAttributes(base);
if (ldapAttributes.size() > 0) {
Map<String, String> attributes = this.getSubjectAttributes(ldapAttributes);
if (!attributes.isEmpty()) {
subjects.add(attributes);
}
}
} else {
log.trace("search string [{}]", query);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Set timeout to 5s
controls.setTimeLimit(5000);
if (maxResults > 0) {
controls.setCountLimit(maxResults);
}
if (base == null) base = "";
results = getContext().search(base, query, controls);
while (results.hasMore()) {
SearchResult searchResult = results.next();
Attributes attributes = searchResult.getAttributes();
Map<String,String> subjectAttributes = this.getSubjectAttributes(attributes);
if (!subjectAttributes.isEmpty()) {
subjects.add(subjectAttributes);
}
}
}
log.trace("Returning [{}] subjects", subjects.size());
return subjects;
} catch (NamingException e) {
log.error("LDAP exception during running query '{}'", query);
throw new InternalErrorException("LDAP exception during running query: "+query+".", e);
} finally {
try {
if (results != null) { results.close(); }
} catch (Exception e) {
log.error("LDAP exception during closing result, while running query '{}'", query);
throw new InternalErrorException(e);
}
}
}
@Override
public void close() throws InternalErrorException {
if (this.dirContext != null) {
try {
this.dirContext.close();
this.dirContext = null;
} catch (NamingException e) {
throw new InternalErrorException(e);
}
}
}
@Override
public List<Map<String, String>> getSubjectGroups(Map<String, String> attributes) throws ExtSourceUnsupportedOperationException {
throw new ExtSourceUnsupportedOperationException();
}
@Override
public List<Map<String, String>> findSubjects(String searchString) throws InternalErrorException {
return findSubjects(searchString, 0);
}
@Override
public List<Map<String, String>> findSubjects(String searchString, int maxResults) throws InternalErrorException {
// We can call original implementation, since LDAP always return whole entry and not just login
return findSubjectsLogins(searchString, maxResults);
}
protected Map<String,String> getAttributes() throws InternalErrorException {
return perunBl.getExtSourcesManagerBl().getAttributes(this);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_2469_0 |
crossvul-java_data_bad_3075_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
@Override
protected void configureLoggerFormatter(Logger logger) {
super.configureLoggerFormatter(logger);
// override with formatters for VerificationHost
// if custom formatter has already set, do NOT replace it.
for (Handler h : logger.getParent().getHandlers()) {
if (Objects.equals(h.getFormatter(), LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.NORMAL_FORMAT);
} else if (Objects.equals(h.getFormatter(), COLOR_LOG_FORMATTER)) {
h.setFormatter(VerificationHostLogFormatter.COLORED_FORMAT);
}
}
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getBody(ServiceErrorResponse.class);
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = Utils.getNowMicrosUtc() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getOperationTimeoutMicros();
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
log("Starting query with options:%s, resultLimit: %d",
create.querySpec.options,
create.querySpec.resultLimit);
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.getNowMicrosUtc() + TimeUnit.SECONDS.toMicros(10))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QueryTask.QuerySpecification spec, long documentCount, long expectedResultCount) {
long start = Utils.getNowMicrosUtc();
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = Utils.getNowMicrosUtc();
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.getNowMicrosUtc() + getOperationTimeoutMicros());
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
ServiceStats stats = this.getServiceState(
null, ServiceStats.class, UriUtils.buildStatsUri(serviceUri));
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
private void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> void doPutPerService(List<Service> services)
throws Throwable {
doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> void doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> void doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> void doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
doServiceUpdates(Action.PUT, count, properties, services);
}
public void doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.getMaintenanceIntervalMicros();
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri).setReferer(getReferer());
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
send(putClone);
});
} else if (properties.contains(TestProperty.CALLBACK_SEND)) {
updateOp.toggleOption(OperationOption.SEND_WITH_CALLBACK, true);
send(updateOp.setBody(b));
} else {
send(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
} else {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum)
throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
setNodeGroupQuorum(quorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
Date exp = getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (quorum != ns.membershipQuorum) {
isConverged = false;
}
}
}
resetAuthorizationContext();
if (isConverged) {
log("converged");
return;
}
Thread.sleep(500);
}
waitForNodeSelectorQuorumConvergence(ServiceUriPaths.DEFAULT_NODE_SELECTOR, quorum);
resetAuthorizationContext();
throw new TimeoutException();
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri) {
ServiceStats stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\tAvg\t\tTotal\t\t\tName%n"));
for (ServiceStat st : stats.entries.values()) {
logStat(uri, st, sb);
}
log(sb.toString());
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.getNowMicrosUtc() + host.getOperationTimeoutMicros();
do {
Thread.sleep(2000);
try {
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_6 |
crossvul-java_data_good_3083_5 | /*
* Copyright (c) 2014-2016 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleODLService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.InMemoryLuceneDocumentIndexService;
import com.vmware.xenon.services.common.NodeGroupService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TestLuceneDocumentIndexService.InMemoryExampleService;
public class TestSynchronizationTaskService extends BasicTestCase {
public static class SynchRetryExampleService extends StatefulService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/test-retry-examples";
public static final FactoryService createFactory() {
return FactoryService.create(SynchRetryExampleService.class);
}
public SynchRetryExampleService() {
super(ServiceDocument.class);
toggleOption(ServiceOption.PERSISTENCE, true);
toggleOption(ServiceOption.OWNER_SELECTION, true);
toggleOption(ServiceOption.REPLICATION, true);
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void handleRequest(Operation op) {
if (getSelfLink().endsWith("fail")) {
if (op.hasPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)) {
op.fail(500);
return;
}
}
super.handleRequest(op);
}
}
public static final String STAT_NAME_PATCH_REQUEST_COUNT = "PATCHrequestCount";
public int updateCount = 10;
public int serviceCount = 10;
public int nodeCount = 3;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
return current.name.equals(initial.name);
};
@BeforeClass
public static void setUpClass() throws Exception {
System.setProperty(
SynchronizationTaskService.PROPERTY_NAME_SYNCHRONIZATION_LOGGING, "true");
}
@AfterClass
public static void tearDownClass() throws Exception {
System.setProperty(
SynchronizationTaskService.PROPERTY_NAME_SYNCHRONIZATION_LOGGING, "false");
}
@Override
public void beforeHostStart(VerificationHost host) throws Throwable {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
this.host.startServiceAndWait(InMemoryLuceneDocumentIndexService.class,
InMemoryLuceneDocumentIndexService.SELF_LINK);
this.host.startFactory(InMemoryExampleService.class, InMemoryExampleService::createFactory);
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
URI exampleFactoryUri = UriUtils.buildUri(
this.host.getUri(), ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(
exampleFactoryUri);
}
private void setUpMultiNode() throws Throwable {
this.host.setUpPeerHosts(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
URI exampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(exampleFactoryUri);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
h.startCoreServicesSynchronously(new InMemoryLuceneDocumentIndexService());
h.startFactory(new InMemoryExampleService());
h.startFactory(new ExampleODLService());
}
URI inMemoryExampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(InMemoryExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(inMemoryExampleFactoryUri);
URI ODLExampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(InMemoryExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(ODLExampleFactoryUri);
}
@After
public void tearDown() {
this.host.tearDownInProcessPeers();
this.host.tearDown();
}
@Test
public void ownershipValidation() throws Throwable {
// This test verifies that only the owner node
// executes the synchronization task. If the task
// is started on a non-owner node, the task should
// self-cancel.
setUpMultiNode();
ownershipValidationDo(ExampleService.FACTORY_LINK);
ownershipValidationDo(InMemoryExampleService.FACTORY_LINK);
}
public void ownershipValidationDo(String factoryLink) throws Throwable {
this.host.createExampleServices(this.host.getPeerHost(), this.serviceCount, null, false, factoryLink);
long membershipUpdateTimeMicros = getLatestMembershipUpdateTime(this.host.getPeerHostUri());
SynchronizationTaskService.State task = createSynchronizationTaskState(membershipUpdateTimeMicros, factoryLink);
List<Operation> ops = this.host.getInProcessHostMap().keySet().stream()
.map(uri -> Operation
.createPost(UriUtils.buildUri(uri, SynchronizationTaskService.FACTORY_LINK))
.setBody(task)
.setReferer(this.host.getUri())
).collect(toList());
TestRequestSender sender = new TestRequestSender(this.host);
List<SynchronizationTaskService.State> results = sender
.sendAndWait(ops, SynchronizationTaskService.State.class);
int finishedCount = 0;
for (SynchronizationTaskService.State r : results) {
assertTrue(r.taskInfo.stage == TaskState.TaskStage.FINISHED ||
r.taskInfo.stage == TaskState.TaskStage.CANCELLED);
if (r.taskInfo.stage == TaskState.TaskStage.FINISHED) {
finishedCount++;
}
}
assertTrue(finishedCount == 1);
}
@Test
public void serviceResynchOnFailure() throws Throwable {
TestRequestSender sender = new TestRequestSender(this.host);
// Test with all failed to synch services, after all retries the task will be in failed state.
this.host.startFactory(SynchRetryExampleService.class, SynchRetryExampleService::createFactory);
URI factoryUri = UriUtils.buildUri(
this.host, SynchRetryExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
createExampleServices(sender, this.host, this.serviceCount, "fail", SynchRetryExampleService.FACTORY_LINK);
SynchronizationTaskService.State task = createSynchronizationTaskState(
null, SynchRetryExampleService.FACTORY_LINK, ServiceDocument.class);
task.membershipUpdateTimeMicros = Utils.getNowMicrosUtc();
// Add pagination in query results.
task.queryResultLimit = this.serviceCount / 2;
// Speed up the retries.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(1));
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
SynchronizationTaskService.State result = sender
.sendAndWait(op, SynchronizationTaskService.State.class);
assertEquals(TaskState.TaskStage.FAILED, result.taskInfo.stage);
assertEquals(0, result.synchCompletionCount);
// Verify that half of the child services were failed.
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue == task.queryResultLimit);
// Test after all retries the task will be in failed state with at-least half
// successful synched services in each page.
createExampleServices(sender, this.host, this.serviceCount * 3, "pass", SynchRetryExampleService.FACTORY_LINK);
task.queryResultLimit = this.serviceCount * 4;
op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
assertEquals(TaskState.TaskStage.FAILED, result.taskInfo.stage);
assertEquals(this.serviceCount * 3, result.synchCompletionCount);
// Verify that this.serviceCount of the child services were failed.
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue == this.serviceCount);
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_SYNCH_RETRY_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue > 0);
}
private void waitForSynchRetries(SynchronizationTaskService.State state, String statName,
Function<ServiceStats.ServiceStat, Boolean> check) {
this.host.waitFor("Expected retries not completed", () -> {
URI statsURI = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsURI);
ServiceStats.ServiceStat synchRetryCount = stats.entries
.get(statName);
return synchRetryCount != null && check.apply(synchRetryCount);
});
}
private void createExampleServices(
TestRequestSender sender, ServiceHost h, long serviceCount, String selfLinkPostfix, String factoryLink) {
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
ServiceDocument initState = new ServiceDocument();
initState.documentSelfLink = i + selfLinkPostfix;
Operation post = Operation.createPost(
UriUtils.buildUri(h, factoryLink)).setBody(initState);
ops.add(post);
}
sender.sendAndWait(ops, ServiceDocument.class);
}
@Test
public void synchCounts() throws Throwable {
synchCountsDo(ExampleService.FACTORY_LINK);
synchCountsDo(InMemoryExampleService.FACTORY_LINK);
}
public void synchCountsDo(String factoryLink) throws Throwable {
this.host.createExampleServices(this.host, this.serviceCount, null, false, factoryLink);
SynchronizationTaskService.State task = createSynchronizationTaskState(Long.MAX_VALUE, factoryLink);
// Add pagination in query results.
task.queryResultLimit = this.serviceCount / 2;
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
TestRequestSender sender = new TestRequestSender(this.host);
SynchronizationTaskService.State result = sender
.sendAndWait(op, SynchronizationTaskService.State.class);
assertTrue (result.taskInfo.stage == TaskState.TaskStage.FINISHED);
assertTrue (result.synchCompletionCount == this.serviceCount);
// Restart the task to verify counter was reset.
task = createSynchronizationTaskState(Long.MAX_VALUE);
task.queryResultLimit = this.serviceCount / 2;
op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
assertTrue(result.taskInfo.stage == TaskState.TaskStage.FINISHED);
assertTrue(result.synchCompletionCount == this.serviceCount);
}
@Test
public void synchAfterOwnerRestart() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(ExampleService.FACTORY_LINK);
}
@Test
public void synchAfterOwnerRestartInMemoryService() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(InMemoryExampleService.FACTORY_LINK);
}
@Test
public void synchAfterOwnerRestartODLService() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(ExampleODLService.FACTORY_LINK);
}
public ExampleServiceState synchAfterOwnerRestartDo(
String factoryLink) throws Throwable {
TestRequestSender sender = new TestRequestSender(this.host);
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
ExampleServiceState state = exampleStatesMap.entrySet().iterator().next().getValue();
// Find out which is the the owner node and restart it
VerificationHost owner = this.host.getInProcessHostMap().values().stream()
.filter(host -> host.getId().contentEquals(state.documentOwner)).findFirst()
.orElseThrow(() -> new RuntimeException("couldn't find owner node"));
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
restartHost(owner);
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Verify that state was synced with restarted node.
Operation op = Operation.createGet(owner, state.documentSelfLink);
ExampleServiceState newState = sender.sendAndWait(op, ExampleServiceState.class);
assertNotNull(newState);
return newState;
}
@Test
@Ignore
public void synchAfterClusterRestart() throws Throwable {
setUpMultiNode();
String factoryLink = ExampleService.FACTORY_LINK;
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
List<VerificationHost> hosts = new ArrayList<>();
// Stop all nodes and preserve their state.
for (Map.Entry<URI, VerificationHost> entry : this.host.getInProcessHostMap().entrySet()) {
VerificationHost host = entry.getValue();
this.host.stopHostAndPreserveState(host);
hosts.add(host);
}
// Create new nodes with same sandbox and port, but different Id.
for (VerificationHost host : hosts) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.sandbox = Paths.get(host.getStorageSandbox()).getParent();
args.port = 0;
VerificationHost newHost = VerificationHost.create(args);
newHost.setPort(host.getPort());
newHost.start();
this.host.addPeerNode(newHost);
}
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount, this.nodeCount);
// Verify that all states are replicated and synched.
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Remove one old node.
VerificationHost nodeToStop = this.host.getPeerHost();
this.host.stopHost(nodeToStop);
// Add new node and verify that state is replicated.
this.host.setUpLocalPeerHost(nodeToStop.getPort(),
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null, null);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount, this.nodeCount);
// Verify that all states are replicated and synched.
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
}
@Test
public void consistentStateAfterOwnerStops() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(ExampleService.FACTORY_LINK);
}
@Test
public void consistentStateAfterOwnerStopsInMemoryService() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(InMemoryExampleService.FACTORY_LINK);
}
@Test
@Ignore
public void consistentStateAfterOwnerStopsODLService() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(ExampleODLService.FACTORY_LINK);
}
public void consistentStateAfterOwnerStop(
String factoryLink) throws Throwable {
long patchCount = 5;
TestRequestSender sender = new TestRequestSender(this.host);
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
ExampleServiceState state = exampleStatesMap.entrySet().iterator().next().getValue();
VerificationHost owner = this.host.getInProcessHostMap().values().stream()
.filter(host -> host.getId().contentEquals(state.documentOwner)).findFirst()
.orElseThrow(() -> new RuntimeException("couldn't find owner node"));
// Send updates to all services and check consistency after owner stops
for (ExampleServiceState st : exampleStates) {
for (int i = 1; i <= patchCount; i++) {
URI serviceUri = UriUtils.buildUri(owner, st.documentSelfLink);
ExampleServiceState s = new ExampleServiceState();
s.counter = (long) i + st.counter;
Operation patch = Operation.createPatch(serviceUri).setBody(s);
sender.sendAndWait(patch);
}
}
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Stop the current owner and make sure that new owner is selected and state is consistent
this.host.stopHost(owner);
VerificationHost peer = this.host.getPeerHost();
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount - 1);
// Verify that state is consistent after original owner node stopped.
Operation op = Operation.createGet(peer, state.documentSelfLink);
ExampleServiceState newState = sender.sendAndWait(op, ExampleServiceState.class);
assertNotNull(newState);
assertEquals((Long) (state.counter + patchCount), newState.counter);
assertNotEquals(newState.documentOwner, state.documentOwner);
}
private VerificationHost restartHost(VerificationHost hostToRestart) throws Throwable {
this.host.stopHostAndPreserveState(hostToRestart);
this.host.waitForNodeGroupConvergence(this.nodeCount - 1, this.nodeCount - 1);
hostToRestart.setPort(0);
VerificationHost.restartStatefulHost(hostToRestart, false);
// Start in-memory index service, and in-memory example factory.
hostToRestart.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
hostToRestart.startFactory(InMemoryExampleService.class, InMemoryExampleService::createFactory);
hostToRestart.startServiceAndWait(InMemoryLuceneDocumentIndexService.class,
InMemoryLuceneDocumentIndexService.SELF_LINK);
hostToRestart.addPrivilegedService(ExampleODLService.class);
hostToRestart.startFactory(ExampleODLService.class, ExampleODLService::createFactory);
this.host.addPeerNode(hostToRestart);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
return hostToRestart;
}
@Test
public void synchTaskStopsSelfPatchingOnFactoryDelete() throws Throwable {
String factoryLink = ExampleService.FACTORY_LINK;
this.host.createExampleServices(this.host, this.serviceCount, null, false, factoryLink);
SynchronizationTaskService.State task = createSynchronizationTaskState(Long.MAX_VALUE, factoryLink);
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
TestRequestSender sender = new TestRequestSender(this.host);
sender.sendRequest(Operation.createDelete(UriUtils.buildUri(this.host, factoryLink)));
SynchronizationTaskService.State result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
// Verify that patch count stops incrementing after a while
AtomicInteger previousValue = new AtomicInteger();
this.host.waitFor("Expected synch task to stop patching itself", () -> {
// Get the latest patch count
URI statsURI = UriUtils.buildStatsUri(this.host, result.documentSelfLink);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsURI);
ServiceStats.ServiceStat synchRetryCount = stats.entries
.get(STAT_NAME_PATCH_REQUEST_COUNT);
return previousValue.getAndSet((int)synchRetryCount.latestValue) == synchRetryCount.latestValue;
});
}
@Test
public void taskRestartability() throws Throwable {
// This test verifies that If the synchronization task
// is already running and another request arrives, the
// task will restart itself if the request had a higher
// membershipUpdateTime.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
SynchronizationTaskService.State task = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
assertTrue(task.taskInfo.stage == TaskState.TaskStage.FINISHED);
long membershipUpdateTimeMicros = task.membershipUpdateTimeMicros;
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < this.updateCount; i++) {
membershipUpdateTimeMicros += 1;
SynchronizationTaskService.State state =
createSynchronizationTaskState(membershipUpdateTimeMicros);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri());
ops.add(op);
}
TestRequestSender sender = new TestRequestSender(this.host);
List<Operation> responses = sender.sendAndWait(ops, false);
for (Operation o : responses) {
if (o.getStatusCode() == Operation.STATUS_CODE_OK) {
SynchronizationTaskService.State r = o.getBody(
SynchronizationTaskService.State.class);
assertTrue(r.taskInfo.stage == TaskState.TaskStage.FINISHED);
} else if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ServiceErrorResponse r = o.getBody(ServiceErrorResponse.class);
assertTrue(r.getErrorCode() == ServiceErrorResponse.ERROR_CODE_OUTDATED_SYNCH_REQUEST);
} else {
throw new IllegalStateException("Unexpected operation response: "
+ o.getStatusCode());
}
}
final long updateTime = membershipUpdateTimeMicros;
this.host.waitFor("membershipUpdateTimeMicros was not set correctly", () -> {
SynchronizationTaskService.State t = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
return t.membershipUpdateTimeMicros == updateTime;
});
}
@Test
public void outdatedSynchronizationRequests() throws Throwable {
// This test verifies that the synch task will only get
// restarted if the synch time is new. For requests with
// older time-stamps, the synch task ignores the request.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
SynchronizationTaskService.State task = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
assertTrue(task.taskInfo.stage == TaskState.TaskStage.FINISHED);
List<Operation> ops = new ArrayList<>();
long membershipUpdateTimeMicros = task.membershipUpdateTimeMicros;
for (int i = 0; i < 10; i++) {
membershipUpdateTimeMicros -= 1;
SynchronizationTaskService.State state =
createSynchronizationTaskState(membershipUpdateTimeMicros);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri());
ops.add(op);
}
TestRequestSender sender = new TestRequestSender(this.host);
List<Operation> results = sender.sendAndWait(ops, false);
for (Operation op : results) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST);
ServiceErrorResponse body = op.getBody(ServiceErrorResponse.class);
assertTrue(body.getErrorCode() == ServiceErrorResponse.ERROR_CODE_OUTDATED_SYNCH_REQUEST);
}
}
@Test
public void stateValidation() throws Throwable {
// This test verifies state validation when
// a synchronization task is created.
// handleStart validation.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
validateInvalidStartState(taskFactoryUri, true, s -> s.factorySelfLink = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.factoryStateKind = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.nodeSelectorLink = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.queryResultLimit = -1);
validateInvalidStartState(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = 10L);
validateInvalidStartState(taskFactoryUri, true, s -> s.queryPageReference = taskFactoryUri);
validateInvalidStartState(taskFactoryUri, true,
s -> s.subStage = SynchronizationTaskService.SubStage.SYNCHRONIZE);
validateInvalidStartState(taskFactoryUri, true,
s -> s.childOptions = EnumSet.of(Service.ServiceOption.PERSISTENCE));
validateInvalidStartState(taskFactoryUri, true,
s -> {
s.taskInfo = new TaskState();
s.taskInfo.stage = TaskState.TaskStage.STARTED;
});
// handlePut validation
validateInvalidPutRequest(taskFactoryUri, true, s -> s.queryResultLimit = -1);
validateInvalidPutRequest(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = null);
validateInvalidPutRequest(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = 0L);
// Let's also test successful requests, to make sure our
// test methods are doing the right thing.
validateInvalidStartState(taskFactoryUri, false, null);
validateInvalidPutRequest(taskFactoryUri, false, null);
}
private long getLatestMembershipUpdateTime(URI nodeUri) throws Throwable {
NodeGroupService.NodeGroupState ngs = this.host.getServiceState(null,
NodeGroupService.NodeGroupState.class,
UriUtils.buildUri(nodeUri, ServiceUriPaths.DEFAULT_NODE_GROUP));
return ngs.membershipUpdateTimeMicros;
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros) {
return createSynchronizationTaskState(
membershipUpdateTimeMicros, ExampleService.FACTORY_LINK, ExampleService.ExampleServiceState.class);
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros, String factoryLink) {
return createSynchronizationTaskState(
membershipUpdateTimeMicros, factoryLink, ExampleService.ExampleServiceState.class);
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros, String factoryLink, Class<? extends ServiceDocument> type) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(factoryLink);
task.factorySelfLink = factoryLink;
task.factoryStateKind = Utils.buildKind(type);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
return task;
}
private void validateInvalidStartState(URI taskFactoryUri,
boolean expectFailure, Consumer<SynchronizationTaskService.State> stateSetter)
throws Throwable {
String factorySelfLink = UUID.randomUUID().toString();
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(factorySelfLink));
SynchronizationTaskService.State task = createSynchronizationTaskState(null);
task.factorySelfLink = factorySelfLink;
task.documentSelfLink = factorySelfLink;
if (stateSetter != null) {
stateSetter.accept(task);
}
TestContext ctx = testCreate(1);
Operation post = Operation
.createPost(taskUri)
.setBody(task)
.setCompletion((o, e) -> {
if (expectFailure) {
if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to fail"));
} else {
if (o.getStatusCode() == Operation.STATUS_CODE_ACCEPTED) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to succeed"));
}
});
SynchronizationTaskService service = SynchronizationTaskService
.create(() -> new ExampleService());
this.host.startService(post, service);
testWait(ctx);
}
private void validateInvalidPutRequest(URI taskFactoryUri,
boolean expectFailure, Consumer<SynchronizationTaskService.State> stateSetter)
throws Throwable {
SynchronizationTaskService.State state =
createSynchronizationTaskState(Long.MAX_VALUE);
if (stateSetter != null) {
stateSetter.accept(state);
}
TestContext ctx = testCreate(1);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (expectFailure) {
if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to fail"));
} else {
if (o.getStatusCode() == Operation.STATUS_CODE_OK) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to succeed"));
}
});
this.host.sendRequest(op);
testWait(ctx);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_5 |
crossvul-java_data_bad_3081_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_1 |
crossvul-java_data_bad_3083_5 | /*
* Copyright (c) 2014-2016 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleODLService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.InMemoryLuceneDocumentIndexService;
import com.vmware.xenon.services.common.NodeGroupService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TestLuceneDocumentIndexService.InMemoryExampleService;
public class TestSynchronizationTaskService extends BasicTestCase {
public static class SynchRetryExampleService extends StatefulService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/test-retry-examples";
public static final FactoryService createFactory() {
return FactoryService.create(SynchRetryExampleService.class);
}
public SynchRetryExampleService() {
super(ServiceDocument.class);
toggleOption(ServiceOption.PERSISTENCE, true);
toggleOption(ServiceOption.OWNER_SELECTION, true);
toggleOption(ServiceOption.REPLICATION, true);
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void handleRequest(Operation op) {
if (getSelfLink().endsWith("fail")) {
if (op.hasPragmaDirective(Operation.PRAGMA_DIRECTIVE_SYNCH_OWNER)) {
op.fail(500);
return;
}
}
super.handleRequest(op);
}
}
public static final String STAT_NAME_PATCH_REQUEST_COUNT = "PATCHrequestCount";
public int updateCount = 10;
public int serviceCount = 10;
public int nodeCount = 3;
private BiPredicate<ExampleServiceState, ExampleServiceState> exampleStateConvergenceChecker = (
initial, current) -> {
if (current.name == null) {
return false;
}
return current.name.equals(initial.name);
};
@BeforeClass
public static void setUpClass() throws Exception {
System.setProperty(
SynchronizationTaskService.PROPERTY_NAME_SYNCHRONIZATION_LOGGING, "true");
}
@AfterClass
public static void tearDownClass() throws Exception {
System.setProperty(
SynchronizationTaskService.PROPERTY_NAME_SYNCHRONIZATION_LOGGING, "false");
}
@Override
public void beforeHostStart(VerificationHost host) throws Throwable {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(
VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
this.host.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
this.host.startServiceAndWait(InMemoryLuceneDocumentIndexService.class,
InMemoryLuceneDocumentIndexService.SELF_LINK);
this.host.startFactory(InMemoryExampleService.class, InMemoryExampleService::createFactory);
}
@Before
public void setUp() {
CommandLineArgumentParser.parseFromProperties(this);
URI exampleFactoryUri = UriUtils.buildUri(
this.host.getUri(), ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(
exampleFactoryUri);
}
private void setUpMultiNode() throws Throwable {
this.host.setUpPeerHosts(this.nodeCount);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
URI exampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(exampleFactoryUri);
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
h.startCoreServicesSynchronously(new InMemoryLuceneDocumentIndexService());
h.startFactory(new InMemoryExampleService());
h.startFactory(new ExampleODLService());
}
URI inMemoryExampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(InMemoryExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(inMemoryExampleFactoryUri);
URI ODLExampleFactoryUri = UriUtils.buildUri(
this.host.getPeerServiceUri(InMemoryExampleService.FACTORY_LINK));
this.host.waitForReplicatedFactoryServiceAvailable(ODLExampleFactoryUri);
}
@After
public void tearDown() {
this.host.tearDownInProcessPeers();
this.host.tearDown();
}
@Test
public void ownershipValidation() throws Throwable {
// This test verifies that only the owner node
// executes the synchronization task. If the task
// is started on a non-owner node, the task should
// self-cancel.
setUpMultiNode();
ownershipValidationDo(ExampleService.FACTORY_LINK);
ownershipValidationDo(InMemoryExampleService.FACTORY_LINK);
}
public void ownershipValidationDo(String factoryLink) throws Throwable {
this.host.createExampleServices(this.host.getPeerHost(), this.serviceCount, null, false, factoryLink);
long membershipUpdateTimeMicros = getLatestMembershipUpdateTime(this.host.getPeerHostUri());
SynchronizationTaskService.State task = createSynchronizationTaskState(membershipUpdateTimeMicros, factoryLink);
List<Operation> ops = this.host.getInProcessHostMap().keySet().stream()
.map(uri -> Operation
.createPost(UriUtils.buildUri(uri, SynchronizationTaskService.FACTORY_LINK))
.setBody(task)
.setReferer(this.host.getUri())
).collect(toList());
TestRequestSender sender = new TestRequestSender(this.host);
List<SynchronizationTaskService.State> results = sender
.sendAndWait(ops, SynchronizationTaskService.State.class);
int finishedCount = 0;
for (SynchronizationTaskService.State r : results) {
assertTrue(r.taskInfo.stage == TaskState.TaskStage.FINISHED ||
r.taskInfo.stage == TaskState.TaskStage.CANCELLED);
if (r.taskInfo.stage == TaskState.TaskStage.FINISHED) {
finishedCount++;
}
}
assertTrue(finishedCount == 1);
}
@Test
public void serviceResynchOnFailure() throws Throwable {
TestRequestSender sender = new TestRequestSender(this.host);
// Test with all failed to synch services, after all retries the task will be in failed state.
this.host.startFactory(SynchRetryExampleService.class, SynchRetryExampleService::createFactory);
URI factoryUri = UriUtils.buildUri(
this.host, SynchRetryExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
createExampleServices(sender, this.host, this.serviceCount, "fail", SynchRetryExampleService.FACTORY_LINK);
SynchronizationTaskService.State task = createSynchronizationTaskState(
null, SynchRetryExampleService.FACTORY_LINK, ServiceDocument.class);
task.membershipUpdateTimeMicros = Utils.getNowMicrosUtc();
// Add pagination in query results.
task.queryResultLimit = this.serviceCount / 2;
// Speed up the retries.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(1));
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
SynchronizationTaskService.State result = sender
.sendAndWait(op, SynchronizationTaskService.State.class);
assertEquals(TaskState.TaskStage.FAILED, result.taskInfo.stage);
assertEquals(0, result.synchCompletionCount);
// Verify that half of the child services were failed.
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue == task.queryResultLimit);
// Test after all retries the task will be in failed state with at-least half
// successful synched services in each page.
createExampleServices(sender, this.host, this.serviceCount * 3, "pass", SynchRetryExampleService.FACTORY_LINK);
task.queryResultLimit = this.serviceCount * 4;
op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
assertEquals(TaskState.TaskStage.FAILED, result.taskInfo.stage);
assertEquals(this.serviceCount * 3, result.synchCompletionCount);
// Verify that this.serviceCount of the child services were failed.
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue == this.serviceCount);
waitForSynchRetries(result, SynchronizationTaskService.STAT_NAME_SYNCH_RETRY_COUNT,
(synchRetryCount) -> synchRetryCount.latestValue > 0);
}
private void waitForSynchRetries(SynchronizationTaskService.State state, String statName,
Function<ServiceStats.ServiceStat, Boolean> check) {
this.host.waitFor("Expected retries not completed", () -> {
URI statsURI = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsURI);
ServiceStats.ServiceStat synchRetryCount = stats.entries
.get(statName);
return synchRetryCount != null && check.apply(synchRetryCount);
});
}
private void createExampleServices(
TestRequestSender sender, ServiceHost h, long serviceCount, String selfLinkPostfix, String factoryLink) {
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
ServiceDocument initState = new ServiceDocument();
initState.documentSelfLink = i + selfLinkPostfix;
Operation post = Operation.createPost(
UriUtils.buildUri(h, factoryLink)).setBody(initState);
ops.add(post);
}
sender.sendAndWait(ops, ServiceDocument.class);
}
@Test
public void synchCounts() throws Throwable {
synchCountsDo(ExampleService.FACTORY_LINK);
synchCountsDo(InMemoryExampleService.FACTORY_LINK);
}
public void synchCountsDo(String factoryLink) throws Throwable {
this.host.createExampleServices(this.host, this.serviceCount, null, false, factoryLink);
SynchronizationTaskService.State task = createSynchronizationTaskState(Long.MAX_VALUE, factoryLink);
// Add pagination in query results.
task.queryResultLimit = this.serviceCount / 2;
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
TestRequestSender sender = new TestRequestSender(this.host);
SynchronizationTaskService.State result = sender
.sendAndWait(op, SynchronizationTaskService.State.class);
assertTrue (result.taskInfo.stage == TaskState.TaskStage.FINISHED);
assertTrue (result.synchCompletionCount == this.serviceCount);
// Restart the task to verify counter was reset.
task = createSynchronizationTaskState(Long.MAX_VALUE);
task.queryResultLimit = this.serviceCount / 2;
op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
assertTrue(result.taskInfo.stage == TaskState.TaskStage.FINISHED);
assertTrue(result.synchCompletionCount == this.serviceCount);
}
@Test
public void synchAfterOwnerRestart() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(ExampleService.FACTORY_LINK);
}
@Test
public void synchAfterOwnerRestartInMemoryService() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(InMemoryExampleService.FACTORY_LINK);
}
@Test
public void synchAfterOwnerRestartODLService() throws Throwable {
setUpMultiNode();
synchAfterOwnerRestartDo(ExampleODLService.FACTORY_LINK);
}
public ExampleServiceState synchAfterOwnerRestartDo(
String factoryLink) throws Throwable {
TestRequestSender sender = new TestRequestSender(this.host);
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
ExampleServiceState state = exampleStatesMap.entrySet().iterator().next().getValue();
// Find out which is the the owner node and restart it
VerificationHost owner = this.host.getInProcessHostMap().values().stream()
.filter(host -> host.getId().contentEquals(state.documentOwner)).findFirst()
.orElseThrow(() -> new RuntimeException("couldn't find owner node"));
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
restartHost(owner);
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Verify that state was synced with restarted node.
Operation op = Operation.createGet(owner, state.documentSelfLink);
ExampleServiceState newState = sender.sendAndWait(op, ExampleServiceState.class);
assertNotNull(newState);
return newState;
}
@Test
public void synchAfterClusterRestart() throws Throwable {
setUpMultiNode();
String factoryLink = ExampleService.FACTORY_LINK;
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
List<VerificationHost> hosts = new ArrayList<>();
// Stop all nodes and preserve their state.
for (Map.Entry<URI, VerificationHost> entry : this.host.getInProcessHostMap().entrySet()) {
VerificationHost host = entry.getValue();
this.host.stopHostAndPreserveState(host);
hosts.add(host);
}
// Create new nodes with same sandbox and port, but different Id.
for (VerificationHost host : hosts) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.sandbox = Paths.get(host.getStorageSandbox()).getParent();
args.port = 0;
VerificationHost newHost = VerificationHost.create(args);
newHost.setPort(host.getPort());
newHost.start();
this.host.addPeerNode(newHost);
}
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount, this.nodeCount);
// Verify that all states are replicated and synched.
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Remove one old node.
VerificationHost nodeToStop = this.host.getPeerHost();
this.host.stopHost(nodeToStop);
// Add new node and verify that state is replicated.
this.host.setUpLocalPeerHost(nodeToStop.getPort(),
VerificationHost.FAST_MAINT_INTERVAL_MILLIS, null, null);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
this.host.waitForNodeGroupConvergence(this.nodeCount, this.nodeCount);
// Verify that all states are replicated and synched.
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
}
@Test
public void consistentStateAfterOwnerStops() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(ExampleService.FACTORY_LINK);
}
@Test
public void consistentStateAfterOwnerStopsInMemoryService() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(InMemoryExampleService.FACTORY_LINK);
}
@Test
@Ignore
public void consistentStateAfterOwnerStopsODLService() throws Throwable {
setUpMultiNode();
consistentStateAfterOwnerStop(ExampleODLService.FACTORY_LINK);
}
public void consistentStateAfterOwnerStop(
String factoryLink) throws Throwable {
long patchCount = 5;
TestRequestSender sender = new TestRequestSender(this.host);
this.host.setNodeGroupQuorum(this.nodeCount - 1);
this.host.waitForNodeGroupConvergence();
List<ExampleServiceState> exampleStates = this.host.createExampleServices(
this.host.getPeerHost(), this.serviceCount, null, factoryLink);
Map<String, ExampleServiceState> exampleStatesMap =
exampleStates.stream().collect(Collectors.toMap(s -> s.documentSelfLink, s -> s));
ExampleServiceState state = exampleStatesMap.entrySet().iterator().next().getValue();
VerificationHost owner = this.host.getInProcessHostMap().values().stream()
.filter(host -> host.getId().contentEquals(state.documentOwner)).findFirst()
.orElseThrow(() -> new RuntimeException("couldn't find owner node"));
// Send updates to all services and check consistency after owner stops
for (ExampleServiceState st : exampleStates) {
for (int i = 1; i <= patchCount; i++) {
URI serviceUri = UriUtils.buildUri(owner, st.documentSelfLink);
ExampleServiceState s = new ExampleServiceState();
s.counter = (long) i + st.counter;
Operation patch = Operation.createPatch(serviceUri).setBody(s);
sender.sendAndWait(patch);
}
}
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount);
// Stop the current owner and make sure that new owner is selected and state is consistent
this.host.stopHost(owner);
VerificationHost peer = this.host.getPeerHost();
this.host.waitForReplicatedFactoryChildServiceConvergence(
this.host.getNodeGroupToFactoryMap(factoryLink),
exampleStatesMap,
this.exampleStateConvergenceChecker,
exampleStatesMap.size(),
0, this.nodeCount - 1);
// Verify that state is consistent after original owner node stopped.
Operation op = Operation.createGet(peer, state.documentSelfLink);
ExampleServiceState newState = sender.sendAndWait(op, ExampleServiceState.class);
assertNotNull(newState);
assertEquals((Long) (state.counter + patchCount), newState.counter);
assertNotEquals(newState.documentOwner, state.documentOwner);
}
private VerificationHost restartHost(VerificationHost hostToRestart) throws Throwable {
this.host.stopHostAndPreserveState(hostToRestart);
this.host.waitForNodeGroupConvergence(this.nodeCount - 1, this.nodeCount - 1);
hostToRestart.setPort(0);
VerificationHost.restartStatefulHost(hostToRestart, false);
// Start in-memory index service, and in-memory example factory.
hostToRestart.addPrivilegedService(InMemoryLuceneDocumentIndexService.class);
hostToRestart.startFactory(InMemoryExampleService.class, InMemoryExampleService::createFactory);
hostToRestart.startServiceAndWait(InMemoryLuceneDocumentIndexService.class,
InMemoryLuceneDocumentIndexService.SELF_LINK);
hostToRestart.addPrivilegedService(ExampleODLService.class);
hostToRestart.startFactory(ExampleODLService.class, ExampleODLService::createFactory);
this.host.addPeerNode(hostToRestart);
this.host.joinNodesAndVerifyConvergence(this.nodeCount);
return hostToRestart;
}
@Test
public void synchTaskStopsSelfPatchingOnFactoryDelete() throws Throwable {
String factoryLink = ExampleService.FACTORY_LINK;
this.host.createExampleServices(this.host, this.serviceCount, null, false, factoryLink);
SynchronizationTaskService.State task = createSynchronizationTaskState(Long.MAX_VALUE, factoryLink);
Operation op = Operation
.createPost(UriUtils.buildUri(this.host, SynchronizationTaskService.FACTORY_LINK))
.setBody(task);
TestRequestSender sender = new TestRequestSender(this.host);
sender.sendRequest(Operation.createDelete(UriUtils.buildUri(this.host, factoryLink)));
SynchronizationTaskService.State result = sender.sendAndWait(op, SynchronizationTaskService.State.class);
// Verify that patch count stops incrementing after a while
AtomicInteger previousValue = new AtomicInteger();
this.host.waitFor("Expected synch task to stop patching itself", () -> {
// Get the latest patch count
URI statsURI = UriUtils.buildStatsUri(this.host, result.documentSelfLink);
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class, statsURI);
ServiceStats.ServiceStat synchRetryCount = stats.entries
.get(STAT_NAME_PATCH_REQUEST_COUNT);
return previousValue.getAndSet((int)synchRetryCount.latestValue) == synchRetryCount.latestValue;
});
}
@Test
public void taskRestartability() throws Throwable {
// This test verifies that If the synchronization task
// is already running and another request arrives, the
// task will restart itself if the request had a higher
// membershipUpdateTime.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
SynchronizationTaskService.State task = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
assertTrue(task.taskInfo.stage == TaskState.TaskStage.FINISHED);
long membershipUpdateTimeMicros = task.membershipUpdateTimeMicros;
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < this.updateCount; i++) {
membershipUpdateTimeMicros += 1;
SynchronizationTaskService.State state =
createSynchronizationTaskState(membershipUpdateTimeMicros);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri());
ops.add(op);
}
TestRequestSender sender = new TestRequestSender(this.host);
List<Operation> responses = sender.sendAndWait(ops, false);
for (Operation o : responses) {
if (o.getStatusCode() == Operation.STATUS_CODE_OK) {
SynchronizationTaskService.State r = o.getBody(
SynchronizationTaskService.State.class);
assertTrue(r.taskInfo.stage == TaskState.TaskStage.FINISHED);
} else if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ServiceErrorResponse r = o.getBody(ServiceErrorResponse.class);
assertTrue(r.getErrorCode() == ServiceErrorResponse.ERROR_CODE_OUTDATED_SYNCH_REQUEST);
} else {
throw new IllegalStateException("Unexpected operation response: "
+ o.getStatusCode());
}
}
final long updateTime = membershipUpdateTimeMicros;
this.host.waitFor("membershipUpdateTimeMicros was not set correctly", () -> {
SynchronizationTaskService.State t = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
return t.membershipUpdateTimeMicros == updateTime;
});
}
@Test
public void outdatedSynchronizationRequests() throws Throwable {
// This test verifies that the synch task will only get
// restarted if the synch time is new. For requests with
// older time-stamps, the synch task ignores the request.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(ExampleService.FACTORY_LINK));
SynchronizationTaskService.State task = this.host.getServiceState(
null, SynchronizationTaskService.State.class, taskUri);
assertTrue(task.taskInfo.stage == TaskState.TaskStage.FINISHED);
List<Operation> ops = new ArrayList<>();
long membershipUpdateTimeMicros = task.membershipUpdateTimeMicros;
for (int i = 0; i < 10; i++) {
membershipUpdateTimeMicros -= 1;
SynchronizationTaskService.State state =
createSynchronizationTaskState(membershipUpdateTimeMicros);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri());
ops.add(op);
}
TestRequestSender sender = new TestRequestSender(this.host);
List<Operation> results = sender.sendAndWait(ops, false);
for (Operation op : results) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST);
ServiceErrorResponse body = op.getBody(ServiceErrorResponse.class);
assertTrue(body.getErrorCode() == ServiceErrorResponse.ERROR_CODE_OUTDATED_SYNCH_REQUEST);
}
}
@Test
public void stateValidation() throws Throwable {
// This test verifies state validation when
// a synchronization task is created.
// handleStart validation.
URI taskFactoryUri = UriUtils.buildUri(
this.host.getUri(), SynchronizationTaskService.FACTORY_LINK);
validateInvalidStartState(taskFactoryUri, true, s -> s.factorySelfLink = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.factoryStateKind = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.nodeSelectorLink = null);
validateInvalidStartState(taskFactoryUri, true, s -> s.queryResultLimit = -1);
validateInvalidStartState(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = 10L);
validateInvalidStartState(taskFactoryUri, true, s -> s.queryPageReference = taskFactoryUri);
validateInvalidStartState(taskFactoryUri, true,
s -> s.subStage = SynchronizationTaskService.SubStage.SYNCHRONIZE);
validateInvalidStartState(taskFactoryUri, true,
s -> s.childOptions = EnumSet.of(Service.ServiceOption.PERSISTENCE));
validateInvalidStartState(taskFactoryUri, true,
s -> {
s.taskInfo = new TaskState();
s.taskInfo.stage = TaskState.TaskStage.STARTED;
});
// handlePut validation
validateInvalidPutRequest(taskFactoryUri, true, s -> s.queryResultLimit = -1);
validateInvalidPutRequest(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = null);
validateInvalidPutRequest(taskFactoryUri, true, s -> s.membershipUpdateTimeMicros = 0L);
// Let's also test successful requests, to make sure our
// test methods are doing the right thing.
validateInvalidStartState(taskFactoryUri, false, null);
validateInvalidPutRequest(taskFactoryUri, false, null);
}
private long getLatestMembershipUpdateTime(URI nodeUri) throws Throwable {
NodeGroupService.NodeGroupState ngs = this.host.getServiceState(null,
NodeGroupService.NodeGroupState.class,
UriUtils.buildUri(nodeUri, ServiceUriPaths.DEFAULT_NODE_GROUP));
return ngs.membershipUpdateTimeMicros;
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros) {
return createSynchronizationTaskState(
membershipUpdateTimeMicros, ExampleService.FACTORY_LINK, ExampleService.ExampleServiceState.class);
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros, String factoryLink) {
return createSynchronizationTaskState(
membershipUpdateTimeMicros, factoryLink, ExampleService.ExampleServiceState.class);
}
private SynchronizationTaskService.State createSynchronizationTaskState(
Long membershipUpdateTimeMicros, String factoryLink, Class<? extends ServiceDocument> type) {
SynchronizationTaskService.State task = new SynchronizationTaskService.State();
task.documentSelfLink = UriUtils.convertPathCharsFromLink(factoryLink);
task.factorySelfLink = factoryLink;
task.factoryStateKind = Utils.buildKind(type);
task.membershipUpdateTimeMicros = membershipUpdateTimeMicros;
task.nodeSelectorLink = ServiceUriPaths.DEFAULT_NODE_SELECTOR;
task.queryResultLimit = 1000;
task.taskInfo = TaskState.create();
task.taskInfo.isDirect = true;
return task;
}
private void validateInvalidStartState(URI taskFactoryUri,
boolean expectFailure, Consumer<SynchronizationTaskService.State> stateSetter)
throws Throwable {
String factorySelfLink = UUID.randomUUID().toString();
URI taskUri = UriUtils.extendUri(
taskFactoryUri, UriUtils.convertPathCharsFromLink(factorySelfLink));
SynchronizationTaskService.State task = createSynchronizationTaskState(null);
task.factorySelfLink = factorySelfLink;
task.documentSelfLink = factorySelfLink;
if (stateSetter != null) {
stateSetter.accept(task);
}
TestContext ctx = testCreate(1);
Operation post = Operation
.createPost(taskUri)
.setBody(task)
.setCompletion((o, e) -> {
if (expectFailure) {
if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to fail"));
} else {
if (o.getStatusCode() == Operation.STATUS_CODE_ACCEPTED) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to succeed"));
}
});
SynchronizationTaskService service = SynchronizationTaskService
.create(() -> new ExampleService());
this.host.startService(post, service);
testWait(ctx);
}
private void validateInvalidPutRequest(URI taskFactoryUri,
boolean expectFailure, Consumer<SynchronizationTaskService.State> stateSetter)
throws Throwable {
SynchronizationTaskService.State state =
createSynchronizationTaskState(Long.MAX_VALUE);
if (stateSetter != null) {
stateSetter.accept(state);
}
TestContext ctx = testCreate(1);
Operation op = Operation
.createPost(taskFactoryUri)
.setBody(state)
.setReferer(this.host.getUri())
.setCompletion((o, e) -> {
if (expectFailure) {
if (o.getStatusCode() == Operation.STATUS_CODE_BAD_REQUEST) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to fail"));
} else {
if (o.getStatusCode() == Operation.STATUS_CODE_OK) {
ctx.completeIteration();
return;
}
ctx.failIteration(new IllegalStateException(
"request was expected to succeed"));
}
});
this.host.sendRequest(op);
testWait(ctx);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_5 |
crossvul-java_data_bad_3081_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT);
if (http1PendingCount == null) {
this.host.log("http1 pending op stats not present");
return false;
}
ServiceStat http2PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT);
if (http2PendingCount == null) {
this.host.log("http2 pending op stats not present");
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertTrue(this.host.getServiceStage(servicePath) == ProcessingStage.AVAILABLE);
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void getAvailableServicesWithOptions() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_3 |
crossvul-java_data_bad_3078_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_2 |
crossvul-java_data_bad_3076_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3076_5 |
crossvul-java_data_bad_3079_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void testSubscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = new TestContext(1, Duration.ofSeconds(5));
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = new TestContext(1, Duration.ofSeconds(5));
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.host.getMaintenanceIntervalMicros() * 2;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
Map<URI, ServiceSubscriptionState> subStates = this.host.getServiceState(null,
ServiceSubscriptionState.class, subUris);
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged = false;
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged = false;
break;
}
}
}
if (isConverged) {
return true;
}
if (!wait) {
return false;
}
Thread.sleep(250);
}
throw new TimeoutException("Subscriber count did not converge to " + subscriberCount);
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_3 |
crossvul-java_data_good_3079_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
// wait for factory availability
this.host.setSystemAuthorizationContext();
this.host.waitForReplicatedFactoryServiceAvailable(usersLink);
this.host.resetAuthorizationContext();
String basicAuth = constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_2 |
crossvul-java_data_good_3075_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.services.common.authn.BasicAuthenticationUtils.constructBasicAuth;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.ResourceGroupService.ResourceGroupState;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationService;
/**
* Consider using {@link com.vmware.xenon.common.AuthorizationSetupHelper}
*/
public class AuthorizationHelper {
private String userGroupLink;
private String resourceGroupLink;
private String roleLink;
VerificationHost host;
public AuthorizationHelper(VerificationHost host) {
this.host = host;
}
public static String createUserService(VerificationHost host, ServiceHost target, String email) throws Throwable {
final String[] userUriPath = new String[1];
UserState userState = new UserState();
userState.documentSelfLink = email;
userState.email = email;
URI postUserUri = UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USERS);
host.testStart(1);
host.send(Operation
.createPost(postUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
host.failIteration(e);
return;
}
UserState state = o.getBody(UserState.class);
userUriPath[0] = state.documentSelfLink;
host.completeIteration();
}));
host.testWait();
return userUriPath[0];
}
public void patchUserService(ServiceHost target, String userServiceLink, UserState userState) throws Throwable {
URI patchUserUri = UriUtils.buildUri(target, userServiceLink);
this.host.testStart(1);
this.host.send(Operation
.createPatch(patchUserUri)
.setBody(userState)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.completeIteration();
}));
this.host.testWait();
}
/**
* Find user document and return the path.
* ex: /core/authz/users/sample@vmware.com
*
* @see VerificationHost#assumeIdentity(String)
*/
public String findUserServiceLink(String userEmail) throws Throwable {
Query userQuery = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(UserState.class))
.addFieldClause(UserState.FIELD_NAME_EMAIL, userEmail)
.build();
QueryTask queryTask = QueryTask.Builder.createDirectTask()
.setQuery(userQuery)
.build();
URI queryTaskUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_QUERY_TASKS);
String[] userServiceLink = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation postQuery = Operation.createPost(queryTaskUri)
.setBody(queryTask)
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
QueryTask queryResponse = op.getBody(QueryTask.class);
int resultSize = queryResponse.results.documentLinks.size();
if (queryResponse.results.documentLinks.size() != 1) {
String msg = String
.format("Could not find user %s, found=%d", userEmail, resultSize);
ctx.failIteration(new IllegalStateException(msg));
return;
} else {
userServiceLink[0] = queryResponse.results.documentLinks.get(0);
}
ctx.completeIteration();
});
this.host.send(postQuery);
this.host.testWait(ctx);
return userServiceLink[0];
}
/**
* Call BasicAuthenticationService and returns auth token.
*/
public String login(String email, String password) throws Throwable {
String basicAuth = constructBasicAuth(email, password);
URI loginUri = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
TestContext ctx = this.host.testCreate(1);
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(BasicAuthenticationService.AUTHORIZATION_HEADER_NAME,
basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
ctx.failIteration(ex);
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
if (authToken[0] == null) {
ctx.failIteration(
new IllegalStateException("Missing auth token in login response"));
return;
}
ctx.completeIteration();
});
this.host.send(loginPost);
this.host.testWait(ctx);
assertTrue(authToken[0] != null);
return authToken[0];
}
public void setUserGroupLink(String userGroupLink) {
this.userGroupLink = userGroupLink;
}
public void setResourceGroupLink(String resourceGroupLink) {
this.resourceGroupLink = resourceGroupLink;
}
public void setRoleLink(String roleLink) {
this.roleLink = roleLink;
}
public String getUserGroupLink() {
return this.userGroupLink;
}
public String getResourceGroupLink() {
return this.resourceGroupLink;
}
public String getRoleLink() {
return this.roleLink;
}
public String createUserService(ServiceHost target, String email) throws Throwable {
return createUserService(this.host, target, email);
}
public Collection<String> createRoles(ServiceHost target, String email) throws Throwable {
return createRoles(target, email, true);
}
public String getUserGroupName(String email) {
String emailPrefix = email.substring(0, email.indexOf("@"));
return emailPrefix + "-user-group";
}
public Collection<String> createRoles(ServiceHost target, String email, boolean createUserGroupByEmail) throws Throwable {
String emailPrefix = email.substring(0, email.indexOf("@"));
String userGroupLink = null;
// Create user group
if (createUserGroupByEmail) {
userGroupLink = createUserGroup(target, getUserGroupName(email), Builder.create()
.addFieldClause(
"email",
email)
.build());
} else {
String groupName = getUserGroupName(email);
userGroupLink = createUserGroup(target, groupName, Builder.create()
.addFieldClause(
QuerySpecification
.buildCollectionItemName(UserState.FIELD_NAME_USER_GROUP_LINKS),
UriUtils.buildUriPath(UserGroupService.FACTORY_LINK, groupName))
.build());
}
setUserGroupLink(userGroupLink);
// Create resource group for example service state
String exampleServiceResourceGroupLink =
createResourceGroup(target, emailPrefix + "-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
emailPrefix)
.build());
setResourceGroupLink(exampleServiceResourceGroupLink);
// Create resource group to allow access on ALL query tasks created by user
String queryTaskResourceGroupLink =
createResourceGroup(target, "any-query-task-resource-group", Builder.create()
.addFieldClause(
QueryTask.FIELD_NAME_KIND,
Utils.buildKind(QueryTask.class))
.addFieldClause(
QueryTask.FIELD_NAME_AUTH_PRINCIPAL_LINK,
UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, email))
.build());
// Create resource group to allow access on utility paths
String statsResourceGroupLink = createResourceGroup(target, "stats-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS)
.build());
String subscriptionsResourceGroupLink = createResourceGroup(target, "subs-resource-group",
Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
ServiceUriPaths.CORE_LOCAL_QUERY_TASKS
+ ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)
.build());
Collection<String> paths = new HashSet<>();
// Create roles tying these together
String exampleRoleLink = createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST)));
setRoleLink(exampleRoleLink);
paths.add(exampleRoleLink);
// Create another role with PATCH permission to test if we calculate overall permissions correctly across roles.
paths.add(createRole(target, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Collections.singletonList(Action.PATCH))));
// Create role authorizing access to the user's own query tasks
paths.add(createRole(target, userGroupLink, queryTaskResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /stats
paths.add(createRole(target, userGroupLink, statsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
// Create role authorizing access to /subscriptions of query tasks
paths.add(createRole(target, userGroupLink, subscriptionsResourceGroupLink,
new HashSet<>(
Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE))));
return paths;
}
public String createUserGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postUserGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_USER_GROUPS);
String selfLink =
UriUtils.extendUri(postUserGroupsUri, name).getPath();
// Create user group
UserGroupState userGroupState = new UserGroupState();
userGroupState.documentSelfLink = selfLink;
userGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postUserGroupsUri)
.setBody(userGroupState));
return selfLink;
}
public String createResourceGroup(ServiceHost target, String name, Query q) throws Throwable {
URI postResourceGroupsUri =
UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS);
String selfLink =
UriUtils.extendUri(postResourceGroupsUri, name).getPath();
ResourceGroupState resourceGroupState = new ResourceGroupState();
resourceGroupState.documentSelfLink = selfLink;
resourceGroupState.query = q;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(postResourceGroupsUri)
.setBody(resourceGroupState));
return selfLink;
}
public String createRole(ServiceHost target, String userGroupLink, String resourceGroupLink, Set<Action> verbs) throws Throwable {
// Build selfLink from user group, resource group, and verbs
String userGroupSegment = userGroupLink.substring(userGroupLink.lastIndexOf('/') + 1);
String resourceGroupSegment = resourceGroupLink.substring(resourceGroupLink.lastIndexOf('/') + 1);
String verbSegment = "";
for (Action a : verbs) {
if (verbSegment.isEmpty()) {
verbSegment = a.toString();
} else {
verbSegment += "+" + a.toString();
}
}
String selfLink = userGroupSegment + "-" + resourceGroupSegment + "-" + verbSegment;
RoleState roleState = new RoleState();
roleState.documentSelfLink = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_ROLES, selfLink);
roleState.userGroupLink = userGroupLink;
roleState.resourceGroupLink = resourceGroupLink;
roleState.verbs = verbs;
roleState.policy = Policy.ALLOW;
this.host.sendAndWaitExpectSuccess(Operation
.createPost(UriUtils.buildUri(target, ServiceUriPaths.CORE_AUTHZ_ROLES))
.setBody(roleState));
return roleState.documentSelfLink;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3075_5 |
crossvul-java_data_good_3080_7 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common.test;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static javax.xml.bind.DatatypeConverter.printBase64Binary;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SupportedCipherSuiteFilter;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Claims;
import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.DeferredResult;
import com.vmware.xenon.common.NodeSelectorService;
import com.vmware.xenon.common.NodeSelectorState;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.OperationContext;
import com.vmware.xenon.common.Service;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceClient;
import com.vmware.xenon.common.ServiceConfigUpdateRequest;
import com.vmware.xenon.common.ServiceConfiguration;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceDocumentDescription.Builder;
import com.vmware.xenon.common.ServiceDocumentQueryResult;
import com.vmware.xenon.common.ServiceErrorResponse;
import com.vmware.xenon.common.ServiceHost;
import com.vmware.xenon.common.ServiceStats;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.TaskState;
import com.vmware.xenon.common.TestResults;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.http.netty.NettyChannelContext;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.serialization.KryoSerializers;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ConsistentHashingNodeSelectorService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.MinimalTestService.MinimalTestServiceErrorResponse;
import com.vmware.xenon.services.common.NodeGroupService.JoinPeerRequest;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeGroupService.UpdateQuorumRequest;
import com.vmware.xenon.services.common.NodeGroupUtils;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.NodeState.NodeOption;
import com.vmware.xenon.services.common.NodeState.NodeStatus;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification;
import com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.QueryValidationTestService.NestedType;
import com.vmware.xenon.services.common.QueryValidationTestService.QueryValidationServiceState;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.TaskService;
public class VerificationHost extends ExampleServiceHost {
public static final int FAST_MAINT_INTERVAL_MILLIS = 100;
public static final String LOCATION1 = "L1";
public static final String LOCATION2 = "L2";
private volatile TestContext context;
private int timeoutSeconds = 30;
private long testStartMicros;
private long testEndMicros;
private long expectedCompletionCount;
private Throwable failure;
private URI referer;
/**
* Command line argument. Comma separated list of one or more peer nodes to join through Nodes
* must be defined in URI form, e.g --peerNodes=http://192.168.1.59:8000,http://192.168.1.82
*/
public String[] peerNodes;
/**
* When {@link #peerNodes} is configured this flag will trigger join of the remote nodes.
*/
public boolean joinNodes;
/**
* Command line argument indicating this is a stress test
*/
public boolean isStressTest;
/**
* Command line argument indicating this is a multi-location test
*/
public boolean isMultiLocationTest;
/**
* Command line argument for test duration, set for long running tests
*/
public long testDurationSeconds;
/**
* Command line argument
*/
public long maintenanceIntervalMillis = FAST_MAINT_INTERVAL_MILLIS;
/**
* Command line argument
*/
public String connectionTag;
private String lastTestName;
private TemporaryFolder temporaryFolder;
private TestRequestSender sender;
public static AtomicInteger hostNumber = new AtomicInteger();
public static VerificationHost create() {
return new VerificationHost();
}
public static VerificationHost create(Integer port) throws Exception {
ServiceHost.Arguments args = buildDefaultServiceHostArguments(port);
return initialize(new VerificationHost(), args);
}
public static ServiceHost.Arguments buildDefaultServiceHostArguments(Integer port) {
ServiceHost.Arguments args = new ServiceHost.Arguments();
args.id = "host-" + hostNumber.incrementAndGet();
args.port = port;
args.sandbox = null;
args.bindAddress = ServiceHost.LOOPBACK_ADDRESS;
return args;
}
public static VerificationHost create(ServiceHost.Arguments args)
throws Exception {
return initialize(new VerificationHost(), args);
}
public static VerificationHost initialize(VerificationHost h, ServiceHost.Arguments args)
throws Exception {
if (args.sandbox == null) {
h.setTemporaryFolder(new TemporaryFolder());
h.getTemporaryFolder().create();
args.sandbox = h.getTemporaryFolder().getRoot().toPath();
}
try {
h.initialize(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
h.sender = new TestRequestSender(h);
return h;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
if (NettyChannelContext.isALPNEnabled()) {
SslContext http2ClientContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
}
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
public void tearDown() {
stop();
TemporaryFolder tempFolder = this.getTemporaryFolder();
if (tempFolder != null) {
tempFolder.delete();
}
}
public Operation createServiceStartPost(TestContext ctx) {
Operation post = Operation.createPost(null);
post.setUri(UriUtils.buildUri(this, "service/" + post.getId()));
return post.setCompletion(ctx.getCompletion());
}
public CompletionHandler getCompletion() {
return (o, e) -> {
if (e != null) {
failIteration(e);
return;
}
completeIteration();
};
}
public <T> BiConsumer<T, ? super Throwable> getCompletionDeferred() {
return (ignore, e) -> {
if (e != null) {
if (e instanceof CompletionException) {
e = e.getCause();
}
failIteration(e);
return;
}
completeIteration();
};
}
public CompletionHandler getExpectedFailureCompletion() {
return getExpectedFailureCompletion(null);
}
public CompletionHandler getExpectedFailureCompletion(Integer statusCode) {
return (o, e) -> {
if (e == null) {
failIteration(new IllegalStateException("Failure expected"));
return;
}
if (statusCode != null) {
if (!statusCode.equals(o.getStatusCode())) {
failIteration(new IllegalStateException(
"Expected different status code "
+ statusCode + " got " + o.getStatusCode()));
return;
}
}
if (e instanceof TimeoutException) {
if (o.getStatusCode() != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"TImeout exception did not have timeout status code"));
return;
}
}
if (o.hasBody()) {
ServiceErrorResponse rsp = o.getErrorResponseBody();
if (rsp.message != null && rsp.message.toLowerCase().contains("timeout")
&& rsp.statusCode != Operation.STATUS_CODE_TIMEOUT) {
failIteration(new IllegalArgumentException(
"Service error response did not have timeout status code:"
+ Utils.toJsonHtml(rsp)));
return;
}
}
completeIteration();
};
}
public VerificationHost setTimeoutSeconds(int seconds) {
this.timeoutSeconds = seconds;
if (this.sender != null) {
this.sender.setTimeout(Duration.ofSeconds(seconds));
}
return this;
}
public int getTimeoutSeconds() {
return this.timeoutSeconds;
}
public void send(Operation op) {
op.setReferer(getReferer());
super.sendRequest(op);
}
@Override
public DeferredResult<Operation> sendWithDeferredResult(Operation operation) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation);
}
@Override
public <T> DeferredResult<T> sendWithDeferredResult(Operation operation, Class<T> resultType) {
operation.setReferer(getReferer());
return super.sendWithDeferredResult(operation, resultType);
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(int c) {
return TestContext.create(c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
/**
* Creates a test wait context that can be nested and isolated from other wait contexts
*/
public TestContext testCreate(long c) {
return testCreate((int) c);
}
/**
* Starts a test context used for a single synchronous test execution for the entire host
* @param c Expected completions
*/
public void testStart(long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use testCreate on singleton, shared host instances");
}
String testName = buildTestNameFromStack();
testStart(
testName,
EnumSet.noneOf(TestProperty.class), c);
}
public String buildTestNameFromStack() {
StackTraceElement[] stack = new Exception().getStackTrace();
String rootTestMethod = "";
for (StackTraceElement s : stack) {
if (s.getClassName().contains("vmware")) {
rootTestMethod = s.getMethodName();
}
}
String testName = rootTestMethod + ":" + stack[2].getMethodName();
return testName;
}
public void testStart(String testName, EnumSet<TestProperty> properties, long c) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (this.context != null) {
throw new IllegalStateException("A test is already started");
}
String negative = properties != null && properties.contains(TestProperty.FORCE_FAILURE)
? "(NEGATIVE)"
: "";
if (c > 1) {
log("%sTest %s, iterations %d, started", negative, testName, c);
}
this.failure = null;
this.expectedCompletionCount = c;
this.testStartMicros = Utils.getSystemNowMicrosUtc();
this.context = TestContext.create((int) c, TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
}
public void completeIteration() {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
String error = "testStart() and testWait() not paired properly" +
" or testStart(N) was called with N being less than actual completions";
log(error);
return;
}
ctx.completeIteration();
}
public void failIteration(Throwable e) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
if (isStopping()) {
log("Received completion after stop");
return;
}
TestContext ctx = this.context;
if (ctx == null) {
log("Test finished, ignoring completion. This might indicate wrong count was used in testStart(count)");
return;
}
log("test failed: %s", e.toString());
ctx.failIteration(e);
}
public void testWait(TestContext ctx) {
ctx.await();
}
public void testWait() {
testWait(new Exception().getStackTrace()[1].getMethodName(),
this.timeoutSeconds);
}
public void testWait(int timeoutSeconds) {
testWait(new Exception().getStackTrace()[1].getMethodName(), timeoutSeconds);
}
public void testWait(String testName, int timeoutSeconds) {
if (this.isSingleton) {
throw new IllegalStateException("Use startTest on singleton, shared host instances");
}
TestContext ctx = this.context;
if (ctx == null) {
throw new IllegalStateException("testStart() was not called before testWait()");
}
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, waiting ...", testName,
this.expectedCompletionCount);
}
try {
ctx.await();
this.testEndMicros = Utils.getSystemNowMicrosUtc();
if (this.expectedCompletionCount > 1) {
log("Test %s, iterations %d, complete!", testName,
this.expectedCompletionCount);
}
} finally {
this.context = null;
this.lastTestName = testName;
}
}
public double calculateThroughput() {
double t = this.testEndMicros - this.testStartMicros;
t /= 1000000.0;
t = this.expectedCompletionCount / t;
return t;
}
public long computeIterationsFromMemory(int serviceCount) {
return computeIterationsFromMemory(EnumSet.noneOf(TestProperty.class), serviceCount);
}
public long computeIterationsFromMemory(EnumSet<TestProperty> props, int serviceCount) {
long total = Runtime.getRuntime().totalMemory();
total /= 512;
total /= serviceCount;
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
if (props.contains(TestProperty.FORCE_REMOTE)) {
total /= 5;
}
if (props.contains(TestProperty.PERSISTED)) {
total /= 5;
}
if (props.contains(TestProperty.FORCE_FAILURE)
|| props.contains(TestProperty.EXPECT_FAILURE)) {
total = 10;
}
if (!this.isStressTest) {
total /= 100;
total = Math.max(Runtime.getRuntime().availableProcessors() * 16, total);
}
total = Math.max(1, total);
if (props.contains(TestProperty.SINGLE_ITERATION)) {
total = 1;
}
return total;
}
public void logThroughput() {
log("Test %s iterations per second: %f", this.lastTestName, calculateThroughput());
logMemoryInfo();
}
public void log(String fmt, Object... args) {
super.log(Level.INFO, 3, fmt, args);
}
public ServiceDocument buildMinimalTestState() {
return buildMinimalTestState(20);
}
public MinimalTestServiceState buildMinimalTestState(int bytes) {
MinimalTestServiceState minState = new MinimalTestServiceState();
minState.id = new Operation().getId() + "";
byte[] body = new byte[bytes];
new Random().nextBytes(body);
minState.stringValue = DatatypeConverter.printBase64Binary(body);
return minState;
}
public CompletableFuture<Operation> sendWithFuture(Operation op) {
if (op.getCompletion() != null) {
throw new IllegalStateException("completion handler must not be set");
}
CompletableFuture<Operation> res = new CompletableFuture<>();
op.setCompletion((o, e) -> {
if (e != null) {
res.completeExceptionally(e);
} else {
res.complete(o);
}
});
this.send(op);
return res;
}
/**
* Use built in Java synchronous HTTP client to verify DCP HttpListener is compliant
*/
public String sendWithJavaClient(URI serviceUri, String contentType, String body)
throws IOException {
URL url = serviceUri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.addRequestProperty(Operation.CONTENT_TYPE_HEADER, contentType);
if (body != null) {
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes(Utils.CHARSET));
}
BufferedReader in = null;
try {
try {
in = new BufferedReader(
new InputStreamReader(
connection.getInputStream(), Utils.CHARSET));
} catch (Throwable e) {
InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
in = new BufferedReader(
new InputStreamReader(errorStream, Utils.CHARSET));
}
}
StringBuilder stringResponseBuilder = new StringBuilder();
if (in == null) {
return "";
}
do {
String line = in.readLine();
if (line == null) {
break;
}
stringResponseBuilder.append(line);
} while (true);
return stringResponseBuilder.toString();
} finally {
if (in != null) {
in.close();
}
}
}
public URI createQueryTaskService(QueryTask create) {
return createQueryTaskService(create, false);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote) {
return createQueryTaskService(create, forceRemote, false, null, null);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, String sourceLink) {
return createQueryTaskService(create, forceRemote, false, null, sourceLink);
}
public URI createQueryTaskService(QueryTask create, boolean forceRemote, boolean isDirect,
QueryTask taskResult,
String sourceLink) {
return createQueryTaskService(null, create, forceRemote, isDirect, taskResult, sourceLink);
}
public URI createQueryTaskService(URI factoryUri, QueryTask create, boolean forceRemote,
boolean isDirect,
QueryTask taskResult,
String sourceLink) {
if (create.documentExpirationTimeMicros == 0) {
create.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.getOperationTimeoutMicros());
}
if (factoryUri == null) {
VerificationHost h = this;
if (!getInProcessHostMap().isEmpty()) {
// pick one host to create the query task
h = getInProcessHostMap().values().iterator().next();
}
factoryUri = UriUtils.buildUri(h, ServiceUriPaths.CORE_QUERY_TASKS);
}
create.documentSelfLink = UUID.randomUUID().toString();
create.documentSourceLink = sourceLink;
create.taskInfo.isDirect = isDirect;
Operation startPost = Operation.createPost(factoryUri).setBody(create);
if (forceRemote) {
startPost.forceRemote();
}
QueryTask result;
try {
result = this.sender.sendAndWait(startPost, QueryTask.class);
} catch (RuntimeException e) {
// throw original exception
throw ExceptionTestUtils.throwAsUnchecked(e.getSuppressed()[0]);
}
if (isDirect) {
taskResult.results = result.results;
taskResult.taskInfo.durationMicros = result.results.queryTimeMicros;
}
return UriUtils.extendUri(factoryUri, create.documentSelfLink);
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish) {
return waitForQueryTaskCompletion(q, totalDocuments, versionCount, u, forceRemote,
deleteOnFinish, true);
}
public boolean isOwner(String documentSelfLink, String nodeSelector) {
final boolean[] isOwner = new boolean[1];
log("Selecting owner for %s on %s", documentSelfLink, nodeSelector);
TestContext ctx = this.testCreate(1);
Operation op = Operation
.createPost(null)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(10)))
.setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
NodeSelectorService.SelectOwnerResponse rsp =
o.getBody(NodeSelectorService.SelectOwnerResponse.class);
log("Is owner: %s for %s", rsp.isLocalHostOwner, rsp.key);
isOwner[0] = rsp.isLocalHostOwner;
ctx.completeIteration();
});
this.selectOwner(nodeSelector, documentSelfLink, op);
ctx.await();
return isOwner[0];
}
public QueryTask waitForQueryTaskCompletion(QuerySpecification q, int totalDocuments,
int versionCount, URI u, boolean forceRemote, boolean deleteOnFinish,
boolean throwOnFailure) {
long startNanos = System.nanoTime();
if (q.options == null) {
q.options = EnumSet.noneOf(QueryOption.class);
}
EnumSet<TestProperty> props = EnumSet.noneOf(TestProperty.class);
if (forceRemote) {
props.add(TestProperty.FORCE_REMOTE);
}
waitFor("Query did not complete in time", () -> {
QueryTask taskState = getServiceState(props, QueryTask.class, u);
return taskState.taskInfo.stage == TaskState.TaskStage.FINISHED
|| taskState.taskInfo.stage == TaskState.TaskStage.FAILED
|| taskState.taskInfo.stage == TaskState.TaskStage.CANCELLED;
});
QueryTask latestTaskState = getServiceState(props, QueryTask.class, u);
// Throw if task was expected to be successful
if (throwOnFailure && (latestTaskState.taskInfo.stage == TaskState.TaskStage.FAILED)) {
throw new IllegalStateException(Utils.toJsonHtml(latestTaskState.taskInfo.failure));
}
if (totalDocuments * versionCount > 1) {
long endNanos = System.nanoTime();
double deltaSeconds = endNanos - startNanos;
deltaSeconds /= TimeUnit.SECONDS.toNanos(1);
double thpt = totalDocuments / deltaSeconds;
log("Options: %s. Throughput (documents / sec): %f", q.options.toString(), thpt);
}
// Delete task, if not direct
if (latestTaskState.taskInfo.isDirect) {
return latestTaskState;
}
if (deleteOnFinish) {
send(Operation.createDelete(u).setBody(new ServiceDocument()));
}
return latestTaskState;
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), fieldName, fieldValue, documentCount,
expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(fieldName, fieldValue, documentCount,
expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(hostUri, fieldName, fieldValue,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
String fieldName, String fieldValue, long documentCount, long expectedResultCount,
TestResults testResults) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(fieldName).setTermMatchValue(fieldValue);
return createAndWaitSimpleDirectQuery(hostUri, q,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QueryTask.QuerySpecification spec,
long documentCount, long expectedResultCount) {
return createAndWaitSimpleDirectQuery(spec,
documentCount, expectedResultCount, null);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(
QuerySpecification spec,
long documentCount, long expectedResultCount, TestResults testResults) {
return createAndWaitSimpleDirectQuery(this.getUri(), spec,
documentCount, expectedResultCount, testResults);
}
public ServiceDocumentQueryResult createAndWaitSimpleDirectQuery(URI hostUri,
QuerySpecification spec, long documentCount, long expectedResultCount, TestResults testResults) {
long start = System.nanoTime() / 1000;
QueryTask[] tasks = new QueryTask[1];
waitFor("", () -> {
QueryTask task = QueryTask.create(spec).setDirect(true);
createQueryTaskService(UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_QUERY_TASKS),
task, false, true, task, null);
if (task.results.documentLinks.size() == expectedResultCount) {
tasks[0] = task;
return true;
}
log("Expected %d, got %d, Query task: %s", expectedResultCount,
task.results.documentLinks.size(), task);
return false;
});
QueryTask resultTask = tasks[0];
assertTrue(
String.format("Got %d links, expected %d", resultTask.results.documentLinks.size(),
expectedResultCount),
resultTask.results.documentLinks.size() == expectedResultCount);
long end = System.nanoTime() / 1000;
double delta = (end - start) / 1000000.0;
double thpt = documentCount / delta;
log("Document count: %d, Expected match count: %d, Documents / sec: %f",
documentCount, expectedResultCount, thpt);
if (testResults != null) {
String key = spec.query.term.propertyName + " docs/s";
testResults.getReport().all(key, thpt);
}
return resultTask.results;
}
public void validatePermanentServiceDocumentDeletion(String linkPrefix, long count,
boolean failOnMismatch)
throws Throwable {
long start = Utils.getNowMicrosUtc();
while (Utils.getNowMicrosUtc() - start < this.getOperationTimeoutMicros()) {
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query = new QueryTask.Query()
.setTermPropertyName(ServiceDocument.FIELD_NAME_SELF_LINK)
.setTermMatchType(MatchType.WILDCARD)
.setTermMatchValue(linkPrefix + UriUtils.URI_WILDCARD_CHAR);
URI u = createQueryTaskService(QueryTask.create(q), false);
QueryTask finishedTaskState = waitForQueryTaskCompletion(q,
(int) count, (int) count, u, false, true);
if (finishedTaskState.results.documentLinks.size() == count) {
return;
}
log("got %d links back, expected %d: %s",
finishedTaskState.results.documentLinks.size(), count,
Utils.toJsonHtml(finishedTaskState));
if (!failOnMismatch) {
return;
}
Thread.sleep(100);
}
if (failOnMismatch) {
throw new TimeoutException();
}
}
public String sendHttpRequest(ServiceClient client, String uri, String requestBody, int count) {
Object[] rspBody = new Object[1];
TestContext ctx = testCreate(count);
Operation op = Operation.createGet(URI.create(uri)).setCompletion(
(o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
rspBody[0] = o.getBodyRaw();
ctx.completeIteration();
});
if (requestBody != null) {
op.setAction(Action.POST).setBody(requestBody);
}
op.setExpiration(Utils.fromNowMicrosUtc(getOperationTimeoutMicros()));
op.setReferer(getReferer());
ServiceClient c = client != null ? client : getClient();
for (int i = 0; i < count; i++) {
c.send(op);
}
ctx.await();
String htmlResponse = (String) rspBody[0];
return htmlResponse;
}
public Operation sendUIHttpRequest(String uri, String requestBody, int count) {
Operation op = Operation.createGet(URI.create(uri));
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < count; i++) {
ops.add(op);
}
List<Operation> responses = this.sender.sendAndWait(ops);
return responses.get(0);
}
public <T extends ServiceDocument> T getServiceState(EnumSet<TestProperty> props, Class<T> type,
URI uri) {
Map<URI, T> r = getServiceState(props, type, new URI[] { uri });
return r.values().iterator().next();
}
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
Collection<URI> uris) {
URI[] array = new URI[uris.size()];
int i = 0;
for (URI u : uris) {
array[i++] = u;
}
return getServiceState(props, type, array);
}
public <T extends TaskService.TaskServiceState> T getServiceStateUsingQueryTask(
Class<T> type, String uri) {
QueryTask.Query q = QueryTask.Query.Builder.create()
.setTerm(ServiceDocument.FIELD_NAME_SELF_LINK, uri)
.build();
QueryTask queryTask = new QueryTask();
queryTask.querySpec = new QueryTask.QuerySpecification();
queryTask.querySpec.query = q;
queryTask.querySpec.options.add(QueryOption.EXPAND_CONTENT);
this.createQueryTaskService(null, queryTask, false, true, queryTask, null);
return Utils.fromJson(queryTask.results.documents.get(uri), type);
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*
* @param type
* @param uris
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type, URI... uris) {
if (type == null) {
throw new IllegalArgumentException("type is required");
}
if (uris == null || uris.length == 0) {
throw new IllegalArgumentException("uris are required");
}
List<Operation> ops = new ArrayList<>();
for (URI u : uris) {
Operation get = Operation.createGet(u).setReferer(getReferer());
if (props != null && props.contains(TestProperty.FORCE_REMOTE)) {
get.forceRemote();
}
if (props != null && props.contains(TestProperty.HTTP2)) {
get.setConnectionSharing(true);
}
if (props != null && props.contains(TestProperty.DISABLE_CONTEXT_ID_VALIDATION)) {
get.setContextId(TestProperty.DISABLE_CONTEXT_ID_VALIDATION.toString());
}
ops.add(get);
}
Map<URI, T> results = new HashMap<>();
List<Operation> responses = this.sender.sendAndWait(ops);
for (Operation response : responses) {
T doc = response.getBody(type);
results.put(UriUtils.buildUri(response.getUri(), doc.documentSelfLink), doc);
}
return results;
}
/**
* Retrieve in parallel, state from N services. This method will block execution until responses
* are received or a failure occurs. It is not optimized for throughput measurements
*/
public <T extends ServiceDocument> Map<URI, T> getServiceState(EnumSet<TestProperty> props,
Class<T> type,
List<Service> services) {
URI[] uris = new URI[services.size()];
int i = 0;
for (Service s : services) {
uris[i++] = s.getUri();
}
return this.getServiceState(props, type, uris);
}
public ServiceDocumentQueryResult getFactoryState(URI factoryUri) {
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public ServiceDocumentQueryResult getExpandedFactoryState(URI factoryUri) {
factoryUri = UriUtils.buildExpandLinksQueryUri(factoryUri);
return this.getServiceState(null, ServiceDocumentQueryResult.class, factoryUri);
}
public Map<String, ServiceStat> getServiceStats(URI serviceUri) {
AuthorizationContext ctx = null;
if (this.isAuthorizationEnabled()) {
ctx = OperationContext.getAuthorizationContext();
this.setSystemAuthorizationContext();
}
ServiceStats stats = this.sender.sendStatsGetAndWait(serviceUri);
if (this.isAuthorizationEnabled()) {
this.setAuthorizationContext(ctx);
}
return stats.entries;
}
public void doExampleServiceUpdateAndQueryByVersion(URI hostUri, int serviceCount) {
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
o.setBody(s);
};
Map<URI, ExampleServiceState> services = doFactoryChildServiceStart(null,
serviceCount,
ExampleServiceState.class, bodySetter,
UriUtils.buildUri(hostUri, ExampleService.FACTORY_LINK));
Map<URI, ExampleServiceState> statesBeforeUpdate = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesBeforeUpdate.values()) {
assertEquals(state.documentVersion, 0);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, null,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 1L,
null);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 10L,
null);
}
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
doServiceUpdates(services.keySet(), Action.PUT, body);
Map<URI, ExampleServiceState> statesAfterPut = getServiceState(null,
ExampleServiceState.class, services.keySet());
for (ExampleServiceState state : statesAfterPut.values()) {
assertEquals(state.documentVersion, 1);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, null,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 10L,
null);
}
doServiceUpdates(services.keySet(), Action.DELETE, body);
for (ExampleServiceState state : statesAfterPut.values()) {
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.POST, 0L,
0L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.PUT, 1L,
1L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE, 2L,
2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
null, 2L);
queryDocumentIndexByVersionAndVerify(hostUri, state.documentSelfLink, Action.DELETE,
10L, null);
}
}
public void doServiceUpdates(Collection<URI> serviceUris, Action action,
ServiceDocument body) {
List<Operation> ops = new ArrayList<>();
for (URI u : serviceUris) {
Operation update = Operation.createPost(u)
.setAction(action)
.setBody(body);
ops.add(update);
}
this.sender.sendAndWait(ops);
}
private void queryDocumentIndexByVersionAndVerify(URI hostUri, String selfLink,
Action expectedAction,
Long version,
Long latestVersion) {
URI localQueryUri = UriUtils.buildDefaultDocumentQueryUri(
hostUri,
selfLink,
false,
true,
ServiceOption.PERSISTENCE);
if (version != null) {
localQueryUri = UriUtils.appendQueryParam(localQueryUri,
ServiceDocument.FIELD_NAME_VERSION,
Long.toString(version));
}
Operation remoteGet = Operation.createGet(localQueryUri);
Operation result = this.sender.sendAndWait(remoteGet);
if (latestVersion == null) {
assertFalse("Document not expected", result.hasBody());
return;
}
ServiceDocument doc = result.getBody(ServiceDocument.class);
int expectedVersion = version == null ? latestVersion.intValue() : version.intValue();
assertEquals("Invalid document version returned", doc.documentVersion, expectedVersion);
String action = doc.documentUpdateAction;
assertEquals("Invalid document update action returned:" + action, expectedAction.name(),
action);
}
public <T> double doPutPerService(List<Service> services)
throws Throwable {
return doPutPerService(EnumSet.noneOf(TestProperty.class), services);
}
public <T> double doPutPerService(EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doPutPerService(computeIterationsFromMemory(properties, services.size()),
properties,
services);
}
public <T> double doPatchPerService(long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PATCH, count, properties, services);
}
public <T> double doPutPerService(long count, EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
return doServiceUpdates(Action.PUT, count, properties, services);
}
public double doServiceUpdates(Action action, long count,
EnumSet<TestProperty> properties,
List<Service> services) throws Throwable {
if (properties == null) {
properties = EnumSet.noneOf(TestProperty.class);
}
logMemoryInfo();
StackTraceElement[] e = new Exception().getStackTrace();
String testName = String.format(
"Parent: %s, %s test with properties %s, service caps: %s",
e[1].getMethodName(),
action, properties.toString(), services.get(0).getOptions());
Map<URI, MinimalTestServiceState> statesBeforeUpdate = getServiceState(properties,
MinimalTestServiceState.class, services);
long startTimeMicros = System.nanoTime() / 1000;
TestContext ctx = testCreate(count * services.size());
ctx.setTestName(testName);
ctx.logBefore();
// create a template PUT. Each operation instance is cloned on send, so
// we can re-use across services
Operation updateOp = Operation.createPut(null).setCompletion(ctx.getCompletion());
updateOp.setAction(action);
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.forceRemote();
}
MinimalTestServiceState body = (MinimalTestServiceState) buildMinimalTestState();
byte[] binaryBody = null;
// put random values in core document properties to verify they are
// ignored
if (!this.isStressTest()) {
body.documentSelfLink = UUID.randomUUID().toString();
body.documentKind = UUID.randomUUID().toString();
} else {
body.stringValue = UUID.randomUUID().toString();
body.id = UUID.randomUUID().toString();
body.responseDelay = 10;
body.documentVersion = 10;
body.documentEpoch = 10L;
body.documentOwner = UUID.randomUUID().toString();
}
if (properties.contains(TestProperty.SET_EXPIRATION)) {
// set expiration to the maintenance interval, which should already be very small
// when the caller sets this test property
body.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
+this.getMaintenanceIntervalMicros());
}
final int maxByteCount = 256 * 1024;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
Random r = new Random();
int byteCount = getClient().getRequestPayloadSizeLimit() / 4;
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
if (properties.contains(TestProperty.FORCE_FAILURE)) {
byteCount = getClient().getRequestPayloadSizeLimit() * 2;
} else {
// make sure we do not blow memory if max request size is high
byteCount = Math.min(maxByteCount, byteCount);
}
} else {
byteCount = maxByteCount;
}
byte[] data = new byte[byteCount];
r.nextBytes(data);
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
binaryBody = data;
} else {
body.stringValue = printBase64Binary(data);
}
}
if (properties.contains(TestProperty.HTTP2)) {
updateOp.setConnectionSharing(true);
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM);
updateOp.setCompletion((o, eb) -> {
if (eb != null) {
ctx.fail(eb);
return;
}
if (!Operation.MEDIA_TYPE_APPLICATION_OCTET_STREAM.equals(o.getContentType())) {
ctx.fail(new IllegalArgumentException("unexpected content type: "
+ o.getContentType()));
return;
}
ctx.complete();
});
}
boolean isFailureExpected = false;
if (properties.contains(TestProperty.FORCE_FAILURE)
|| properties.contains(TestProperty.EXPECT_FAILURE)) {
toggleNegativeTestMode(true);
isFailureExpected = true;
if (properties.contains(TestProperty.LARGE_PAYLOAD)) {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("expected failure"));
} else {
ctx.complete();
}
});
} else {
updateOp.setCompletion((o, ex) -> {
if (ex == null) {
ctx.fail(new IllegalStateException("failure expected"));
return;
}
MinimalTestServiceErrorResponse rsp = o
.getBody(MinimalTestServiceErrorResponse.class);
if (!MinimalTestServiceErrorResponse.KIND.equals(rsp.documentKind)) {
ctx.fail(new IllegalStateException("Response not expected:"
+ Utils.toJson(rsp)));
return;
}
ctx.complete();
});
}
}
int byteCount = Utils.toJson(body).getBytes(Utils.CHARSET).length;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
long c = KryoSerializers.serializeDocument(body, 4096).position();
byteCount = (int) c;
}
log("Bytes per payload %s", byteCount);
boolean isConcurrentSend = properties.contains(TestProperty.CONCURRENT_SEND);
final boolean isFailureExpectedFinal = isFailureExpected;
for (Service s : services) {
if (properties.contains(TestProperty.FORCE_REMOTE)) {
updateOp.setConnectionTag(this.connectionTag);
}
long[] expectedVersion = new long[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version to match expected current
// version
MinimalTestServiceState initialState = statesBeforeUpdate.get(s.getUri());
expectedVersion[0] = isFailureExpected ? Integer.MAX_VALUE
: initialState.documentVersion;
}
URI sUri = s.getUri();
updateOp.setUri(sUri);
for (int i = 0; i < count; i++) {
if (!isFailureExpected) {
body.id = "" + i;
} else if (!properties.contains(TestProperty.LARGE_PAYLOAD)) {
body.id = null;
}
CountDownLatch[] l = new CountDownLatch[1];
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// only used for strict update checking, serialized requests
l[0] = new CountDownLatch(1);
// we have to serialize requests and properly set version
body.documentVersion = expectedVersion[0];
updateOp.setCompletion((o, ex) -> {
if (ex == null || isFailureExpectedFinal) {
MinimalTestServiceState rsp = o.getBody(MinimalTestServiceState.class);
expectedVersion[0] = rsp.documentVersion;
ctx.complete();
l[0].countDown();
return;
}
ctx.fail(ex);
l[0].countDown();
});
}
Object b = binaryBody != null ? binaryBody : body;
if (properties.contains(TestProperty.BINARY_SERIALIZATION)) {
// provide hints to runtime on how to serialize the body,
// using binary serialization and a buffer size equal to content length
updateOp.setContentLength(byteCount);
updateOp.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM);
}
if (isConcurrentSend) {
Operation putClone = updateOp.clone();
putClone.setBody(b).setUri(sUri);
run(() -> {
s.sendRequest(putClone);
});
} else {
s.sendRequest(updateOp.setBody(b));
}
if (s.hasOption(ServiceOption.STRICT_UPDATE_CHECKING)) {
// we have to serialize requests and properly set version
if (!isFailureExpected) {
l[0].await();
}
if (this.failure != null) {
throw this.failure;
}
}
}
}
testWait(ctx);
double throughput = ctx.logAfter();
if (isFailureExpected) {
this.toggleNegativeTestMode(false);
return throughput;
}
if (properties.contains(TestProperty.BINARY_PAYLOAD)) {
return throughput;
}
List<URI> getUris = new ArrayList<>();
if (services.get(0).hasOption(ServiceOption.PERSISTENCE)) {
for (Service s : services) {
// bypass the services, which rely on caching, and go straight to the index
URI u = UriUtils.buildDocumentQueryUri(this, s.getSelfLink(), true, false,
ServiceOption.PERSISTENCE);
getUris.add(u);
}
} else {
for (Service s : services) {
getUris.add(s.getUri());
}
}
Map<URI, MinimalTestServiceState> statesAfterUpdate = getServiceState(
properties,
MinimalTestServiceState.class, getUris);
for (MinimalTestServiceState st : statesAfterUpdate.values()) {
URI serviceUri = UriUtils.buildUri(this, st.documentSelfLink);
ServiceDocument beforeSt = statesBeforeUpdate.get(serviceUri);
long expectedVersion = beforeSt.documentVersion + count;
if (st.documentVersion != expectedVersion) {
QueryTestUtils.logVersionInfoForService(this.sender, serviceUri, expectedVersion);
throw new IllegalStateException("got " + st.documentVersion + ", expected "
+ (beforeSt.documentVersion + count));
}
assertTrue(st.documentVersion == beforeSt.documentVersion + count);
assertTrue(st.id != null);
assertTrue(st.documentSelfLink != null
&& st.documentSelfLink.equals(beforeSt.documentSelfLink));
assertTrue(st.documentKind != null
&& st.documentKind.equals(Utils.buildKind(MinimalTestServiceState.class)));
assertTrue(st.documentUpdateTimeMicros > startTimeMicros);
assertTrue(st.documentUpdateAction != null);
assertTrue(st.documentUpdateAction.equals(action.toString()));
}
logMemoryInfo();
return throughput;
}
public void logMemoryInfo() {
log("Memory free:%d, available:%s, total:%s", Runtime.getRuntime().freeMemory(),
Runtime.getRuntime().totalMemory(),
Runtime.getRuntime().maxMemory());
}
public URI getReferer() {
if (this.referer == null) {
this.referer = getUri();
}
return this.referer;
}
public void waitForServiceAvailable(String... links) {
for (String link : links) {
TestContext ctx = testCreate(1);
this.registerForServiceAvailability(ctx.getCompletion(), link);
ctx.await();
}
}
public void waitForReplicatedFactoryServiceAvailable(URI u) {
waitForReplicatedFactoryServiceAvailable(u, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
}
public void waitForReplicatedFactoryServiceAvailable(URI u, String nodeSelectorPath) {
waitFor("replicated available check time out for " + u, () -> {
boolean[] isReady = new boolean[1];
TestContext ctx = testCreate(1);
NodeGroupUtils.checkServiceAvailability((o, e) -> {
if (e != null) {
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
}, this, u, nodeSelectorPath);
ctx.await();
return isReady[0];
});
}
public void waitForServiceAvailable(URI u) {
boolean[] isReady = new boolean[1];
log("Starting /available check on %s", u);
waitFor("available check timeout for " + u, () -> {
TestContext ctx = testCreate(1);
URI available = UriUtils.buildAvailableUri(u);
Operation get = Operation.createGet(available).setCompletion((o, e) -> {
if (e != null) {
// not ready
isReady[0] = false;
ctx.completeIteration();
return;
}
isReady[0] = true;
ctx.completeIteration();
return;
});
send(get);
ctx.await();
if (isReady[0]) {
log("%s /available returned success", get.getUri());
return true;
}
return false;
});
}
public <T extends ServiceDocument> Map<URI, T> doFactoryChildServiceStart(
EnumSet<TestProperty> props,
long c,
Class<T> bodyType,
Consumer<Operation> setInitialStateConsumer,
URI factoryURI) {
Map<URI, T> initialStates = new HashMap<>();
if (props == null) {
props = EnumSet.noneOf(TestProperty.class);
}
log("Sending %d POST requests to %s", c, factoryURI);
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < c; i++) {
Operation createPost = Operation.createPost(factoryURI);
// call callback to set the body
setInitialStateConsumer.accept(createPost);
if (props.contains(TestProperty.FORCE_REMOTE)) {
createPost.forceRemote();
}
ops.add(createPost);
}
List<T> responses = this.sender.sendAndWait(ops, bodyType);
Map<URI, T> docByChildURI = responses.stream().collect(
toMap(doc -> UriUtils.buildUri(factoryURI, doc.documentSelfLink), identity()));
initialStates.putAll(docByChildURI);
log("Done with %d POST requests to %s", c, factoryURI);
return initialStates;
}
public List<Service> doThroughputServiceStart(long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(EnumSet.noneOf(TestProperty.class), c, type, initialState,
options, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove) throws Throwable {
return doThroughputServiceStart(props, c, type, initialState,
options, optionsToRemove, null);
}
public List<Service> doThroughputServiceStart(
EnumSet<TestProperty> props,
long c, Class<? extends Service> type,
ServiceDocument initialState,
EnumSet<Service.ServiceOption> options,
EnumSet<Service.ServiceOption> optionsToRemove,
Long maintIntervalMicros) throws Throwable {
List<Service> services = new ArrayList<>();
TestContext ctx = testCreate((int) c);
for (int i = 0; i < c; i++) {
Service e = type.newInstance();
if (options != null) {
for (Service.ServiceOption cap : options) {
e.toggleOption(cap, true);
}
}
if (optionsToRemove != null) {
for (ServiceOption opt : optionsToRemove) {
e.toggleOption(opt, false);
}
}
Operation post = createServiceStartPost(ctx);
if (initialState != null) {
post.setBody(initialState);
}
if (props != null && props.contains(TestProperty.SET_CONTEXT_ID)) {
post.setContextId(TestProperty.SET_CONTEXT_ID.toString());
}
if (maintIntervalMicros != null) {
e.setMaintenanceIntervalMicros(maintIntervalMicros);
}
startService(post, e);
services.add(e);
}
ctx.await();
logThroughput();
return services;
}
public Service startServiceAndWait(Class<? extends Service> serviceType,
String uriPath)
throws Throwable {
return startServiceAndWait(serviceType.newInstance(), uriPath, null);
}
public Service startServiceAndWait(Service s,
String uriPath,
ServiceDocument body)
throws Throwable {
TestContext ctx = testCreate(1);
URI u = null;
if (uriPath != null) {
u = UriUtils.buildUri(this, uriPath);
}
Operation post = Operation
.createPost(u)
.setBody(body)
.setCompletion(ctx.getCompletion());
startService(post, s);
ctx.await();
return s;
}
public <T extends ServiceDocument> void doServiceRestart(List<Service> services,
Class<T> stateType,
EnumSet<Service.ServiceOption> caps)
throws Throwable {
ServiceDocumentDescription sdd = buildDescription(stateType);
// first collect service state before shutdown so we can compare after
// they restart
Map<URI, T> statesBeforeRestart = getServiceState(null, stateType, services);
List<Service> freshServices = new ArrayList<>();
List<Operation> ops = new ArrayList<>();
for (Service s : services) {
// delete with no body means stop the service
Operation delete = Operation.createDelete(s.getUri());
ops.add(delete);
}
this.sender.sendAndWait(ops);
// restart services
TestContext ctx = testCreate(services.size());
for (Service oldInstance : services) {
Service e = oldInstance.getClass().newInstance();
for (Service.ServiceOption cap : caps) {
e.toggleOption(cap, true);
}
// use the same exact URI so the document index can find the service
// state by self link
startService(
Operation.createPost(oldInstance.getUri()).setCompletion(ctx.getCompletion()),
e);
freshServices.add(e);
}
ctx.await();
services = null;
Map<URI, T> statesAfterRestart = getServiceState(null, stateType, freshServices);
for (Entry<URI, T> e : statesAfterRestart.entrySet()) {
T stateAfter = e.getValue();
if (stateAfter.documentSelfLink == null) {
throw new IllegalStateException("missing selflink");
}
if (stateAfter.documentKind == null) {
throw new IllegalStateException("missing kind");
}
T stateBefore = statesBeforeRestart.get(e.getKey());
if (stateBefore == null) {
throw new IllegalStateException(
"New service has new self link, not in previous service instances");
}
if (!stateBefore.documentKind.equals(stateAfter.documentKind)) {
throw new IllegalStateException("kind mismatch");
}
if (!caps.contains(Service.ServiceOption.PERSISTENCE)) {
continue;
}
if (stateBefore.documentVersion != stateAfter.documentVersion) {
String error = String.format(
"Version mismatch. Before State: %s%n%n After state:%s",
Utils.toJson(stateBefore),
Utils.toJson(stateAfter));
throw new IllegalStateException(error);
}
if (stateBefore.documentUpdateTimeMicros != stateAfter.documentUpdateTimeMicros) {
throw new IllegalStateException("update time mismatch");
}
if (stateBefore.documentVersion == 0) {
throw new IllegalStateException("PUT did not appear to take place before restart");
}
if (!ServiceDocument.equals(sdd, stateBefore, stateAfter)) {
throw new IllegalStateException("content signature mismatch");
}
}
}
private Map<String, NodeState> peerHostIdToNodeState = new ConcurrentHashMap<>();
private Map<URI, URI> peerNodeGroups = new ConcurrentHashMap<>();
private Map<URI, VerificationHost> localPeerHosts = new ConcurrentHashMap<>();
private boolean isRemotePeerTest;
private boolean isSingleton;
public Map<URI, VerificationHost> getInProcessHostMap() {
return new HashMap<>(this.localPeerHosts);
}
public Map<URI, URI> getNodeGroupMap() {
return new HashMap<>(this.peerNodeGroups);
}
public Map<String, NodeState> getNodeStateMap() {
return new HashMap<>(this.peerHostIdToNodeState);
}
public void scheduleSynchronizationIfAutoSyncDisabled(String selectorPath) {
if (this.isPeerSynchronizationEnabled()) {
return;
}
for (VerificationHost peerHost : getInProcessHostMap().values()) {
peerHost.scheduleNodeGroupChangeMaintenance(selectorPath);
ServiceStats selectorStats = getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(peerHost, selectorPath));
ServiceStat synchStat = selectorStats.entries
.get(ConsistentHashingNodeSelectorService.STAT_NAME_SYNCHRONIZATION_COUNT);
if (synchStat != null && synchStat.latestValue > 0) {
throw new IllegalStateException("Automatic synchronization was triggered");
}
}
}
public void setUpPeerHosts(int localHostCount) {
CommandLineArgumentParser.parseFromProperties(this);
if (this.peerNodes == null) {
this.setUpLocalPeersHosts(localHostCount, null);
} else {
this.setUpWithRemotePeers(this.peerNodes);
}
}
public void setUpLocalPeersHosts(int localHostCount, Long maintIntervalMillis) {
testStart(localHostCount);
if (maintIntervalMillis == null) {
maintIntervalMillis = this.maintenanceIntervalMillis;
}
final long intervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
for (int i = 0; i < localHostCount; i++) {
String location = this.isMultiLocationTest
? ((i < localHostCount / 2) ? LOCATION1 : LOCATION2)
: null;
run(() -> {
try {
this.setUpLocalPeerHost(null, intervalMicros, location);
} catch (Throwable e) {
failIteration(e);
}
});
}
testWait();
}
public Map<URI, URI> getNodeGroupToFactoryMap(String factoryLink) {
Map<URI, URI> nodeGroupToFactoryMap = new HashMap<>();
for (URI nodeGroup : this.peerNodeGroups.values()) {
nodeGroupToFactoryMap.put(nodeGroup,
UriUtils.buildUri(nodeGroup.getScheme(), nodeGroup.getHost(),
nodeGroup.getPort(), factoryLink, null));
}
return nodeGroupToFactoryMap;
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts)
throws Throwable {
return setUpLocalPeerHost(port, maintIntervalMicros, hosts, null);
}
public VerificationHost setUpLocalPeerHost(Collection<ServiceHost> hosts,
long maintIntervalMicros, String location) throws Throwable {
return setUpLocalPeerHost(0, maintIntervalMicros, hosts, location);
}
public VerificationHost setUpLocalPeerHost(int port, long maintIntervalMicros,
Collection<ServiceHost> hosts, String location)
throws Throwable {
VerificationHost h = VerificationHost.create(port);
h.setPeerSynchronizationEnabled(this.isPeerSynchronizationEnabled());
h.setAuthorizationEnabled(this.isAuthorizationEnabled());
if (this.getCurrentHttpScheme() == HttpScheme.HTTPS_ONLY) {
// disable HTTP on new peer host
h.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
// request a random HTTPS port
h.setSecurePort(0);
}
if (this.isAuthorizationEnabled()) {
h.setAuthorizationService(new AuthorizationContextService());
}
try {
VerificationHost.createAndAttachSSLClient(h);
// override with parent cert info.
// Within same node group, all hosts are required to use same cert, private key, and
// passphrase for now.
h.setCertificateFileReference(this.getState().certificateFileReference);
h.setPrivateKeyFileReference(this.getState().privateKeyFileReference);
h.setPrivateKeyPassphrase(this.getState().privateKeyPassphrase);
if (location != null) {
h.setLocation(location);
}
h.start();
h.setMaintenanceIntervalMicros(maintIntervalMicros);
} catch (Throwable e) {
throw new Exception(e);
}
addPeerNode(h);
if (hosts != null) {
hosts.add(h);
}
this.completeIteration();
return h;
}
public void setUpWithRemotePeers(String[] peerNodes) {
this.isRemotePeerTest = true;
this.peerNodeGroups.clear();
for (String remoteNode : peerNodes) {
URI remoteHostBaseURI = URI.create(remoteNode);
if (remoteHostBaseURI.getPort() == 80 || remoteHostBaseURI.getPort() == -1) {
remoteHostBaseURI = UriUtils.buildUri(remoteNode, ServiceHost.DEFAULT_PORT, "",
null);
}
URI remoteNodeGroup = UriUtils.extendUri(remoteHostBaseURI,
ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(remoteHostBaseURI, remoteNodeGroup);
}
}
public void joinNodesAndVerifyConvergence(int nodeCount) throws Throwable {
joinNodesAndVerifyConvergence(null, nodeCount, nodeCount, null);
}
public boolean isRemotePeerTest() {
return this.isRemotePeerTest;
}
public int getPeerCount() {
return this.peerNodeGroups.size();
}
public URI getPeerHostUri() {
return getPeerServiceUri("");
}
public URI getPeerNodeGroupUri() {
return getPeerServiceUri(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
/**
* Randomly returns one of peer hosts.
*/
public VerificationHost getPeerHost() {
URI hostUri = getPeerServiceUri(null);
if (hostUri != null) {
return this.localPeerHosts.get(hostUri);
}
return null;
}
public URI getPeerServiceUri(String link) {
if (!this.localPeerHosts.isEmpty()) {
List<URI> localPeerList = new ArrayList<>();
for (VerificationHost h : this.localPeerHosts.values()) {
if (h.isStopping() || !h.isStarted()) {
continue;
}
localPeerList.add(h.getUri());
}
return getUriFromList(link, localPeerList);
} else {
List<URI> peerList = new ArrayList<>(this.peerNodeGroups.keySet());
return getUriFromList(link, peerList);
}
}
/**
* Randomly choose one uri from uriList and extend with the link
*/
private URI getUriFromList(String link, List<URI> uriList) {
if (!uriList.isEmpty()) {
Collections.shuffle(uriList, new Random(System.nanoTime()));
URI baseUri = uriList.iterator().next();
return UriUtils.extendUri(baseUri, link);
}
return null;
}
public void createCustomNodeGroupOnPeers(String customGroupName) {
createCustomNodeGroupOnPeers(customGroupName, null);
}
public void createCustomNodeGroupOnPeers(String customGroupName,
Map<URI, NodeState> selfState) {
if (selfState == null) {
selfState = new HashMap<>();
}
// create a custom node group on all peer nodes
List<Operation> ops = new ArrayList<>();
for (URI peerHostBaseUri : getNodeGroupMap().keySet()) {
URI nodeGroupFactoryUri = UriUtils.buildUri(peerHostBaseUri,
ServiceUriPaths.NODE_GROUP_FACTORY);
Operation op = getCreateCustomNodeGroupOperation(customGroupName, nodeGroupFactoryUri,
selfState.get(peerHostBaseUri));
ops.add(op);
}
this.sender.sendAndWait(ops);
}
private Operation getCreateCustomNodeGroupOperation(String customGroupName,
URI nodeGroupFactoryUri,
NodeState selfState) {
NodeGroupState body = new NodeGroupState();
body.documentSelfLink = customGroupName;
if (selfState != null) {
body.nodes.put(selfState.id, selfState);
}
return Operation.createPost(nodeGroupFactoryUri).setBody(body);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode)
throws Throwable {
joinNodesAndVerifyConvergence(customGroupPath, hostCount, memberCount,
expectedOptionsPerNode, true);
}
public void joinNodesAndVerifyConvergence(int hostCount, boolean waitForTimeSync)
throws Throwable {
joinNodesAndVerifyConvergence(hostCount, hostCount, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(int hostCount, int memberCount,
boolean waitForTimeSync) throws Throwable {
joinNodesAndVerifyConvergence(null, hostCount, memberCount, null, waitForTimeSync);
}
public void joinNodesAndVerifyConvergence(String customGroupPath, int hostCount,
int memberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode,
boolean waitForTimeSync) throws Throwable {
// invoke op as system user
setAuthorizationContext(getSystemAuthorizationContext());
if (hostCount == 0) {
return;
}
Map<URI, URI> nodeGroupPerHost = new HashMap<>();
if (customGroupPath != null) {
for (Entry<URI, URI> e : this.peerNodeGroups.entrySet()) {
URI ngUri = UriUtils.buildUri(e.getKey(), customGroupPath);
nodeGroupPerHost.put(e.getKey(), ngUri);
}
} else {
nodeGroupPerHost = this.peerNodeGroups;
}
if (this.isRemotePeerTest()) {
memberCount = getPeerCount();
}
if (!isRemotePeerTest() || (isRemotePeerTest() && this.joinNodes)) {
for (URI initialNodeGroupService : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
initialNodeGroupService = UriUtils.buildUri(initialNodeGroupService,
customGroupPath);
}
for (URI nodeGroup : this.peerNodeGroups.values()) {
if (customGroupPath != null) {
nodeGroup = UriUtils.buildUri(nodeGroup, customGroupPath);
}
if (initialNodeGroupService.equals(nodeGroup)) {
continue;
}
testStart(1);
joinNodeGroup(nodeGroup, initialNodeGroupService, memberCount);
testWait();
}
}
}
// for local or remote tests, we still want to wait for convergence
waitForNodeGroupConvergence(nodeGroupPerHost.values(), memberCount, null,
expectedOptionsPerNode, waitForTimeSync);
waitForNodeGroupIsAvailableConvergence(customGroupPath);
//reset auth context
setAuthorizationContext(null);
}
public void joinNodeGroup(URI newNodeGroupService,
URI nodeGroup, Integer quorum) {
if (nodeGroup.equals(newNodeGroupService)) {
return;
}
// to become member of a group of nodes, you send a POST to self
// (the local node group service) with the URI of the remote node
// group you wish to join
JoinPeerRequest joinBody = JoinPeerRequest.create(nodeGroup, quorum);
log("Joining %s through %s", newNodeGroupService, nodeGroup);
// send the request to the node group instance we have picked as the
// "initial" one
send(Operation.createPost(newNodeGroupService)
.setBody(joinBody)
.setCompletion(getCompletion()));
}
public void joinNodeGroup(URI newNodeGroupService, URI nodeGroup) {
joinNodeGroup(newNodeGroupService, nodeGroup, null);
}
public void subscribeForNodeGroupConvergence(URI nodeGroup, int expectedAvailableCount,
CompletionHandler convergedCompletion) {
TestContext ctx = testCreate(1);
Operation subscribeToNodeGroup = Operation.createPost(
UriUtils.buildSubscriptionUri(nodeGroup))
.setCompletion(ctx.getCompletion())
.setReferer(getUri());
startSubscriptionService(subscribeToNodeGroup, (op) -> {
op.complete();
if (op.getAction() != Action.PATCH) {
return;
}
NodeGroupState ngs = op.getBody(NodeGroupState.class);
if (ngs.nodes == null && ngs.nodes.isEmpty()) {
return;
}
int c = 0;
for (NodeState ns : ngs.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
c++;
}
}
if (c != expectedAvailableCount) {
return;
}
convergedCompletion.handle(op, null);
});
ctx.await();
}
public void waitForNodeGroupIsAvailableConvergence() {
waitForNodeGroupIsAvailableConvergence(ServiceUriPaths.DEFAULT_NODE_GROUP);
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath) {
waitForNodeGroupIsAvailableConvergence(nodeGroupPath, this.peerNodeGroups.values());
}
public void waitForNodeGroupIsAvailableConvergence(String nodeGroupPath,
Collection<URI> nodeGroupUris) {
if (nodeGroupPath == null) {
nodeGroupPath = ServiceUriPaths.DEFAULT_NODE_GROUP;
}
String finalNodeGroupPath = nodeGroupPath;
waitFor("Node group is not available for convergence", () -> {
boolean isConverged = true;
for (URI nodeGroupUri : nodeGroupUris) {
URI u = UriUtils.buildUri(nodeGroupUri, finalNodeGroupPath);
URI statsUri = UriUtils.buildStatsUri(u);
ServiceStats stats = getServiceState(null, ServiceStats.class, statsUri);
ServiceStat availableStat = stats.entries.get(Service.STAT_NAME_AVAILABLE);
if (availableStat == null || availableStat.latestValue != Service.STAT_VALUE_TRUE) {
log("Service stat available is missing or not 1.0");
isConverged = false;
break;
}
}
return isConverged;
});
}
public void waitForNodeGroupConvergence(int memberCount) {
waitForNodeGroupConvergence(memberCount, null);
}
public void waitForNodeGroupConvergence(int healthyMemberCount, Integer totalMemberCount) {
waitForNodeGroupConvergence(this.peerNodeGroups.values(), healthyMemberCount,
totalMemberCount, true);
}
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris, int healthyMemberCount,
Integer totalMemberCount,
boolean waitForTimeSync) {
waitForNodeGroupConvergence(nodeGroupUris, healthyMemberCount, totalMemberCount,
new HashMap<>(), waitForTimeSync);
}
/**
* Check node group convergence.
*
* Due to the implementation of {@link NodeGroupUtils#isNodeGroupAvailable}, quorum needs to
* be set less than the available node counts.
*
* Since {@link TestNodeGroupManager} requires all passing nodes to be in a same nodegroup,
* hosts in in-memory host map({@code this.localPeerHosts}) that do not match with the given
* nodegroup will be skipped for check.
*
* For existing API compatibility, keeping unused variables in signature.
* Only {@code nodeGroupUris} parameter is used.
*
* Sample node group URI: http://127.0.0.1:8000/core/node-groups/default
*
* @see TestNodeGroupManager#waitForConvergence()
*/
public void waitForNodeGroupConvergence(Collection<URI> nodeGroupUris,
int healthyMemberCount,
Integer totalMemberCount,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNodeGroupUri,
boolean waitForTimeSync) {
Set<String> nodeGroupNames = nodeGroupUris.stream()
.map(URI::getPath)
.map(UriUtils::getLastPathSegment)
.collect(toSet());
if (nodeGroupNames.size() != 1) {
throw new RuntimeException("Multiple nodegroups are not supported. " + nodeGroupNames);
}
String nodeGroupName = nodeGroupNames.iterator().next();
Date exp = getTestExpiration();
Duration timeout = Duration.between(Instant.now(), exp.toInstant());
// Convert "http://127.0.0.1:1234/core/node-groups/default" to "http://127.0.0.1:1234"
Set<URI> baseUris = nodeGroupUris.stream()
.map(uri -> uri.toString().replace(uri.getPath(), ""))
.map(URI::create)
.collect(toSet());
// pick up hosts that match with the base uris of given node group uris
Set<ServiceHost> hosts = getInProcessHostMap().values().stream()
.filter(host -> baseUris.contains(host.getPublicUri()))
.collect(toSet());
// perform "waitForConvergence()"
if (hosts != null && !hosts.isEmpty()) {
TestNodeGroupManager manager = new TestNodeGroupManager(nodeGroupName);
manager.addHosts(hosts);
manager.setTimeout(timeout);
manager.waitForConvergence();
} else {
this.waitFor("Node group did not converge", () -> {
String nodeGroupPath = ServiceUriPaths.NODE_GROUP_FACTORY + "/" + nodeGroupName;
List<Operation> nodeGroupOps = baseUris.stream()
.map(u -> UriUtils.buildUri(u, nodeGroupPath))
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStates = getTestRequestSender()
.sendAndWait(nodeGroupOps, NodeGroupState.class);
for (NodeGroupState nodeGroupState : nodeGroupStates) {
TestContext testContext = this.testCreate(1);
// placeholder operation
Operation parentOp = Operation.createGet(null)
.setReferer(this.getUri())
.setCompletion(testContext.getCompletion());
try {
NodeGroupUtils.checkConvergenceFromAnyHost(this, nodeGroupState, parentOp);
testContext.await();
} catch (Exception e) {
return false;
}
}
return true;
});
}
// To be compatible with old behavior, populate peerHostIdToNodeState same way as before
List<Operation> nodeGroupGetOps = nodeGroupUris.stream()
.map(UriUtils::buildExpandLinksQueryUri)
.map(Operation::createGet)
.collect(toList());
List<NodeGroupState> nodeGroupStats = this.sender.sendAndWait(nodeGroupGetOps, NodeGroupState.class);
for (NodeGroupState nodeGroupStat : nodeGroupStats) {
for (NodeState nodeState : nodeGroupStat.nodes.values()) {
if (nodeState.status == NodeStatus.AVAILABLE) {
this.peerHostIdToNodeState.put(nodeState.id, nodeState);
}
}
}
}
public int calculateHealthyNodeCount(NodeGroupState r) {
int healthyNodeCount = 0;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodeCount++;
}
}
return healthyNodeCount;
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost) {
getNodeState(nodeGroup, nodesPerHost, null);
}
public void getNodeState(URI nodeGroup, Map<URI, NodeGroupState> nodesPerHost,
TestContext ctx) {
URI u = UriUtils.buildExpandLinksQueryUri(nodeGroup);
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
NodeGroupState ngs = null;
if (e != null) {
// failure is OK, since we might have just stopped a host
log("Host %s failed GET with %s", nodeGroup, e.getMessage());
ngs = new NodeGroupState();
} else {
ngs = o.getBody(NodeGroupState.class);
}
synchronized (nodesPerHost) {
nodesPerHost.put(nodeGroup, ngs);
}
if (ctx == null) {
completeIteration();
} else {
ctx.completeIteration();
}
});
send(get);
}
public void validateNodes(NodeGroupState r, int expectedNodesPerGroup,
Map<URI, EnumSet<NodeOption>> expectedOptionsPerNode) {
int healthyNodes = 0;
NodeState localNode = null;
for (NodeState ns : r.nodes.values()) {
if (ns.status == NodeStatus.AVAILABLE) {
healthyNodes++;
}
assertTrue(ns.documentKind.equals(Utils.buildKind(NodeState.class)));
if (ns.documentSelfLink.endsWith(r.documentOwner)) {
localNode = ns;
}
assertTrue(ns.options != null);
EnumSet<NodeOption> expectedOptions = expectedOptionsPerNode.get(ns.groupReference);
if (expectedOptions == null) {
expectedOptions = NodeState.DEFAULT_OPTIONS;
}
for (NodeOption eo : expectedOptions) {
assertTrue(ns.options.contains(eo));
}
assertTrue(ns.id != null);
assertTrue(ns.groupReference != null);
assertTrue(ns.documentSelfLink.startsWith(ns.groupReference.getPath()));
}
assertTrue(healthyNodes >= expectedNodesPerGroup);
assertTrue(localNode != null);
}
public void doNodeGroupStatsVerification(Map<URI, URI> defaultNodeGroupsPerHost) {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : defaultNodeGroupsPerHost.values()) {
Operation get = Operation.createGet(UriUtils.extendUri(nodeGroup,
ServiceHost.SERVICE_URI_SUFFIX_STATS));
ops.add(get);
}
List<Operation> results = this.sender.sendAndWait(ops);
for (Operation result : results) {
ServiceStats stats = result.getBody(ServiceStats.class);
assertTrue(!stats.entries.isEmpty());
}
}
public void setNodeGroupConfig(NodeGroupConfig config) {
setSystemAuthorizationContext();
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
NodeGroupState body = new NodeGroupState();
body.config = config;
body.nodes = null;
ops.add(Operation.createPatch(nodeGroup).setBody(body));
}
this.sender.sendAndWait(ops);
resetAuthorizationContext();
}
public void setNodeGroupQuorum(Integer quorum, URI nodeGroup) {
setNodeGroupQuorum(quorum, null, nodeGroup);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum, URI nodeGroup) {
UpdateQuorumRequest body = UpdateQuorumRequest.create(true);
if (quorum != null) {
body.setMembershipQuorum(quorum);
}
if (locationQuorum != null) {
body.setLocationQuorum(locationQuorum);
}
this.sender.sendAndWait(Operation.createPatch(nodeGroup).setBody(body));
}
public void setNodeGroupQuorum(Integer quorum) throws Throwable {
setNodeGroupQuorum(quorum, (Integer) null);
}
public void setNodeGroupQuorum(Integer quorum, Integer locationQuorum) throws Throwable {
// we can issue the update to any one node and it will update
// everyone in the group
setSystemAuthorizationContext();
for (URI nodeGroup : getNodeGroupMap().values()) {
if (quorum != null) {
log("Changing quorum to %d on group %s", quorum, nodeGroup);
}
if (locationQuorum != null) {
log("Changing location quorum to %d on group %s", locationQuorum, nodeGroup);
}
setNodeGroupQuorum(quorum, locationQuorum, nodeGroup);
// nodes might not be joined, so we need to ask each node to set quorum
}
resetAuthorizationContext();
waitFor("quorum did not converge", () -> {
setSystemAuthorizationContext();
for (URI n : this.peerNodeGroups.values()) {
NodeGroupState s = getServiceState(null, NodeGroupState.class, n);
for (NodeState ns : s.nodes.values()) {
if (!NodeStatus.AVAILABLE.equals(ns.status)) {
continue;
}
if (quorum != ns.membershipQuorum) {
return false;
}
if (locationQuorum != null && !locationQuorum.equals(ns.locationQuorum)) {
return false;
}
}
}
resetAuthorizationContext();
return true;
});
}
public void waitForNodeSelectorQuorumConvergence(String nodeSelectorPath, int quorum) {
waitFor("quorum not updated", () -> {
for (URI peerHostUri : getNodeGroupMap().keySet()) {
URI nodeSelectorUri = UriUtils.buildUri(peerHostUri, nodeSelectorPath);
NodeSelectorState nss = getServiceState(null, NodeSelectorState.class,
nodeSelectorUri);
if (nss.membershipQuorum != quorum) {
return false;
}
}
return true;
});
}
public <T extends ServiceDocument> void validateDocumentPartitioning(
Map<URI, T> provisioningTasks,
Class<T> type) {
Map<String, Map<String, Long>> taskToOwnerCount = new HashMap<>();
for (URI baseHostURI : getNodeGroupMap().keySet()) {
List<URI> documentsPerDcpHost = new ArrayList<>();
for (URI serviceUri : provisioningTasks.keySet()) {
URI u = UriUtils.extendUri(baseHostURI, serviceUri.getPath());
documentsPerDcpHost.add(u);
}
Map<URI, T> tasksOnThisHost = getServiceState(
null,
type, documentsPerDcpHost);
for (T task : tasksOnThisHost.values()) {
Map<String, Long> ownerCount = taskToOwnerCount.get(task.documentSelfLink);
if (ownerCount == null) {
ownerCount = new HashMap<>();
taskToOwnerCount.put(task.documentSelfLink, ownerCount);
}
Long count = ownerCount.get(task.documentOwner);
if (count == null) {
count = 0L;
}
count++;
ownerCount.put(task.documentOwner, count);
}
}
// now verify that each task had a single owner assigned to it
for (Entry<String, Map<String, Long>> e : taskToOwnerCount.entrySet()) {
Map<String, Long> owners = e.getValue();
if (owners.size() > 1) {
throw new IllegalStateException("Multiple owners assigned on task " + e.getKey());
}
}
}
public void createExampleServices(ServiceHost h,
long serviceCount, List<URI> exampleURIs, Long expiration) {
createExampleServices(h, serviceCount, exampleURIs, expiration, false);
}
public void createExampleServices(ServiceHost h, long serviceCount, List<URI> exampleURIs,
Long expiration, boolean skipAvailabilityCheck) {
if (!skipAvailabilityCheck) {
waitForServiceAvailable(ExampleService.FACTORY_LINK);
}
ExampleServiceState initialState = new ExampleServiceState();
URI exampleFactoryUri = UriUtils.buildFactoryUri(h,
ExampleService.class);
// create example services
List<Operation> ops = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
initialState.counter = 123L;
if (expiration != null) {
initialState.documentExpirationTimeMicros = expiration;
}
initialState.name = initialState.documentSelfLink = UUID.randomUUID().toString();
exampleURIs.add(UriUtils.extendUri(exampleFactoryUri, initialState.documentSelfLink));
Operation createPost = Operation.createPost(exampleFactoryUri).setBody(initialState);
ops.add(createPost);
}
this.sender.sendAndWait(ops);
}
public Date getTestExpiration() {
long duration = this.timeoutSeconds + this.testDurationSeconds;
return new Date(new Date().getTime()
+ TimeUnit.SECONDS.toMillis(duration));
}
public boolean isStressTest() {
return this.isStressTest;
}
public void setStressTest(boolean isStressTest) {
this.isStressTest = isStressTest;
if (isStressTest) {
this.timeoutSeconds = 600;
this.setOperationTimeOutMicros(TimeUnit.SECONDS.toMicros(this.timeoutSeconds));
} else {
this.timeoutSeconds = (int) TimeUnit.MICROSECONDS.toSeconds(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
}
}
public boolean isMultiLocationTest() {
return this.isMultiLocationTest;
}
public void setMultiLocationTest(boolean isMultiLocationTest) {
this.isMultiLocationTest = isMultiLocationTest;
}
public void toggleServiceOptions(URI serviceUri, EnumSet<ServiceOption> optionsToEnable,
EnumSet<ServiceOption> optionsToDisable) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = optionsToDisable;
updateBody.addOptions = optionsToEnable;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
public void setOperationQueueLimit(URI serviceUri, int limit) {
// send a set limit configuration request
ServiceConfigUpdateRequest body = ServiceConfigUpdateRequest.create();
body.operationQueueLimit = limit;
URI configUri = UriUtils.buildConfigUri(serviceUri);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(body));
// verify new operation limit is set
ServiceConfiguration config = this.sender.sendAndWait(Operation.createGet(configUri),
ServiceConfiguration.class);
assertEquals("Invalid queue limit", body.operationQueueLimit,
(Integer) config.operationQueueLimit);
}
public void toggleNegativeTestMode(boolean enable) {
log("++++++ Negative test mode %s, failure logs expected: %s", enable, enable);
}
public void logNodeProcessLogs(Set<URI> keySet, String logSuffix) {
List<URI> logServices = new ArrayList<>();
for (URI host : keySet) {
logServices.add(UriUtils.extendUri(host, logSuffix));
}
Map<URI, LogServiceState> states = this.getServiceState(null, LogServiceState.class,
logServices);
for (Entry<URI, LogServiceState> entry : states.entrySet()) {
log("Process log for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void logNodeManagementState(Set<URI> keySet) {
List<URI> services = new ArrayList<>();
for (URI host : keySet) {
services.add(UriUtils.extendUri(host, ServiceUriPaths.CORE_MANAGEMENT));
}
Map<URI, ServiceHostState> states = this.getServiceState(null, ServiceHostState.class,
services);
for (Entry<URI, ServiceHostState> entry : states.entrySet()) {
log("Management state for node %s\n\n%s", entry.getKey(),
Utils.toJsonHtml(entry.getValue()));
}
}
public void tearDownInProcessPeers() {
for (VerificationHost h : this.localPeerHosts.values()) {
if (h == null) {
continue;
}
stopHost(h);
}
}
public void stopHost(VerificationHost host) {
log("Stopping host %s (%s)", host.getUri(), host.getId());
host.tearDown();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public void stopHostAndPreserveState(ServiceHost host) {
log("Stopping host %s", host.getUri());
// Do not delete the temporary directory with the lucene index. Notice that
// we do not call host.tearDown(), which will delete disk state, we simply
// stop the host and remove it from the peer node tracking tables
host.stop();
this.peerHostIdToNodeState.remove(host.getId());
this.peerNodeGroups.remove(host.getUri());
this.localPeerHosts.remove(host.getUri());
}
public boolean isLongDurationTest() {
return this.testDurationSeconds > 0;
}
public void logServiceStats(URI uri, TestResults testResults) {
ServiceStats serviceStats = logServiceStats(uri);
if (testResults != null) {
testResults.getReport().stats(uri, serviceStats);
}
}
public ServiceStats logServiceStats(URI uri) {
ServiceStats stats = null;
try {
stats = getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(uri));
if (stats == null || stats.entries == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append(String.format("Stats for %s%n", uri));
sb.append(String.format("\tCount\t\t\tAvg\t\tTotal\t\t\tName%n"));
stats.entries.values().stream()
.sorted((s1, s2) -> s1.name.compareTo(s2.name))
.forEach((s) -> logStat(uri, s, sb));
log(sb.toString());
} catch (Throwable e) {
log("Failure getting stats: %s", e.getMessage());
}
return stats;
}
private void logStat(URI serviceUri, ServiceStat st, StringBuilder sb) {
ServiceStatLogHistogram hist = st.logHistogram;
st.logHistogram = null;
double total = st.accumulatedValue != 0 ? st.accumulatedValue : st.latestValue;
double avg = total / st.version;
sb.append(
String.format("\t%08d\t\t%08.2f\t%010.2f\t%s%n", st.version, avg, total, st.name));
if (hist == null) {
return;
}
}
/**
* Retrieves node group service state from all peers and logs it in JSON format
*/
public void logNodeGroupState() {
List<Operation> ops = new ArrayList<>();
for (URI nodeGroup : getNodeGroupMap().values()) {
ops.add(Operation.createGet(nodeGroup));
}
List<NodeGroupState> stats = this.sender.sendAndWait(ops, NodeGroupState.class);
for (NodeGroupState stat : stats) {
log("%s", Utils.toJsonHtml(stat));
}
}
public void setServiceMaintenanceIntervalMicros(String path, long micros) {
setServiceMaintenanceIntervalMicros(UriUtils.buildUri(this, path), micros);
}
public void setServiceMaintenanceIntervalMicros(URI u, long micros) {
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.maintenanceIntervalMicros = micros;
URI configUri = UriUtils.extendUri(u, ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.sender.sendAndWait(Operation.createPatch(configUri).setBody(updateBody));
}
/**
* Toggles the operation tracing service
*
* @param baseHostURI the uri of the tracing service
* @param enable state to toggle to
*/
public void toggleOperationTracing(URI baseHostURI, boolean enable) {
ServiceHostManagementService.ConfigureOperationTracingRequest r = new ServiceHostManagementService.ConfigureOperationTracingRequest();
r.enable = enable ? ServiceHostManagementService.OperationTracingEnable.START
: ServiceHostManagementService.OperationTracingEnable.STOP;
r.kind = ServiceHostManagementService.ConfigureOperationTracingRequest.KIND;
this.setSystemAuthorizationContext();
this.sender.sendAndWait(Operation.createPatch(
UriUtils.extendUri(baseHostURI, ServiceHostManagementService.SELF_LINK))
.setBody(r));
this.resetAuthorizationContext();
}
public CompletionHandler getSuccessOrFailureCompletion() {
return (o, e) -> {
completeIteration();
};
}
public static QueryValidationServiceState buildQueryValidationState() {
QueryValidationServiceState newState = new QueryValidationServiceState();
newState.ignoredStringValue = "should be ignored by index";
newState.exampleValue = new ExampleServiceState();
newState.exampleValue.counter = 10L;
newState.exampleValue.name = "example name";
newState.nestedComplexValue = new NestedType();
newState.nestedComplexValue.id = UUID.randomUUID().toString();
newState.nestedComplexValue.longValue = Long.MIN_VALUE;
newState.listOfExampleValues = new ArrayList<>();
ExampleServiceState exampleItem = new ExampleServiceState();
exampleItem.name = "nested name";
newState.listOfExampleValues.add(exampleItem);
newState.listOfStrings = new ArrayList<>();
for (int i = 0; i < 10; i++) {
newState.listOfStrings.add(UUID.randomUUID().toString());
}
newState.arrayOfExampleValues = new ExampleServiceState[2];
newState.arrayOfExampleValues[0] = new ExampleServiceState();
newState.arrayOfExampleValues[0].name = UUID.randomUUID().toString();
newState.arrayOfStrings = new String[2];
newState.arrayOfStrings[0] = UUID.randomUUID().toString();
newState.arrayOfStrings[1] = UUID.randomUUID().toString();
newState.mapOfStrings = new HashMap<>();
String keyOne = "keyOne";
String keyTwo = "keyTwo";
String valueOne = UUID.randomUUID().toString();
String valueTwo = UUID.randomUUID().toString();
newState.mapOfStrings.put(keyOne, valueOne);
newState.mapOfStrings.put(keyTwo, valueTwo);
newState.mapOfBooleans = new HashMap<>();
newState.mapOfBooleans.put("trueKey", true);
newState.mapOfBooleans.put("falseKey", false);
newState.mapOfBytesArrays = new HashMap<>();
newState.mapOfBytesArrays.put("bytes", new byte[] { 0x01, 0x02 });
newState.mapOfDoubles = new HashMap<>();
newState.mapOfDoubles.put("one", 1.0);
newState.mapOfDoubles.put("minusOne", -1.0);
newState.mapOfEnums = new HashMap<>();
newState.mapOfEnums.put("GET", Service.Action.GET);
newState.mapOfLongs = new HashMap<>();
newState.mapOfLongs.put("one", 1L);
newState.mapOfLongs.put("two", 2L);
newState.mapOfNestedTypes = new HashMap<>();
newState.mapOfNestedTypes.put("nested", newState.nestedComplexValue);
newState.mapOfUris = new HashMap<>();
newState.mapOfUris.put("uri", UriUtils.buildUri("/foo/bar"));
newState.ignoredArrayOfStrings = new String[2];
newState.ignoredArrayOfStrings[0] = UUID.randomUUID().toString();
newState.ignoredArrayOfStrings[1] = UUID.randomUUID().toString();
newState.binaryContent = UUID.randomUUID().toString().getBytes();
return newState;
}
public void updateServiceOptions(Collection<String> selfLinks,
ServiceConfigUpdateRequest cfgBody) {
List<Operation> ops = new ArrayList<>();
for (String link : selfLinks) {
URI bUri = UriUtils.buildUri(getUri(), link,
ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
ops.add(Operation.createPatch(bUri).setBody(cfgBody));
}
this.sender.sendAndWait(ops);
}
public void addPeerNode(VerificationHost h) {
URI localBaseURI = h.getPublicUri();
URI nodeGroup = UriUtils.buildUri(h.getPublicUri(), ServiceUriPaths.DEFAULT_NODE_GROUP);
this.peerNodeGroups.put(localBaseURI, nodeGroup);
this.localPeerHosts.put(localBaseURI, h);
}
public void addPeerNode(URI ngUri) {
URI hostUri = UriUtils.buildUri(ngUri.getScheme(), ngUri.getHost(), ngUri.getPort(), null,
null);
this.peerNodeGroups.put(hostUri, ngUri);
}
public ServiceDocumentDescription buildDescription(Class<? extends ServiceDocument> type) {
EnumSet<ServiceOption> options = EnumSet.noneOf(ServiceOption.class);
return Builder.create().buildDescription(type, options);
}
public void logAllDocuments(Set<URI> baseHostUris) {
QueryTask task = new QueryTask();
task.setDirect(true);
task.querySpec = new QuerySpecification();
task.querySpec.query.setTermPropertyName("documentSelfLink").setTermMatchValue("*");
task.querySpec.query.setTermMatchType(MatchType.WILDCARD);
task.querySpec.options = EnumSet.of(QueryOption.EXPAND_CONTENT);
List<Operation> ops = new ArrayList<>();
for (URI baseHost : baseHostUris) {
Operation queryPost = Operation
.createPost(UriUtils.buildUri(baseHost, ServiceUriPaths.CORE_QUERY_TASKS))
.setBody(task);
ops.add(queryPost);
}
List<QueryTask> queryTasks = this.sender.sendAndWait(ops, QueryTask.class);
for (QueryTask queryTask : queryTasks) {
log(Utils.toJsonHtml(queryTask));
}
}
public void setSystemAuthorizationContext() {
setAuthorizationContext(getSystemAuthorizationContext());
}
public void resetSystemAuthorizationContext() {
super.setAuthorizationContext(null);
}
@Override
public void addPrivilegedService(Class<? extends Service> serviceType) {
// Overriding just for test cases
super.addPrivilegedService(serviceType);
}
@Override
public void setAuthorizationContext(AuthorizationContext context) {
super.setAuthorizationContext(context);
}
public void resetAuthorizationContext() {
super.setAuthorizationContext(null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
*/
public AuthorizationContext assumeIdentity(String userServicePath)
throws GeneralSecurityException {
return assumeIdentity(userServicePath, null);
}
/**
* Inject user identity into operation context.
*
* @param userServicePath user document link
* @param properties custom properties in claims
* @throws GeneralSecurityException any generic security exception
*/
public AuthorizationContext assumeIdentity(String userServicePath,
Map<String, String> properties) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
builder.setProperties(properties);
Claims claims = builder.getResult();
String token = getTokenSigner().sign(claims);
AuthorizationContext.Builder ab = AuthorizationContext.Builder.create();
ab.setClaims(claims);
ab.setToken(token);
// Associate resulting authorization context with this thread
AuthorizationContext authContext = ab.getResult();
setAuthorizationContext(authContext);
return authContext;
}
public void deleteAllChildServices(URI factoryURI) {
deleteOrStopAllChildServices(factoryURI, false);
}
public void deleteOrStopAllChildServices(URI factoryURI, boolean stopOnly) {
ServiceDocumentQueryResult res = getFactoryState(factoryURI);
if (res.documentLinks.isEmpty()) {
return;
}
List<Operation> ops = new ArrayList<>();
for (String link : res.documentLinks) {
Operation op = Operation.createDelete(UriUtils.buildUri(factoryURI, link));
if (stopOnly) {
op.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
} else {
op.addRequestHeader(Operation.REPLICATION_QUORUM_HEADER,
Operation.REPLICATION_QUORUM_HEADER_VALUE_ALL);
}
ops.add(op);
}
this.sender.sendAndWait(ops);
}
public <T extends ServiceDocument> ServiceDocument verifyPost(Class<T> documentType,
String factoryLink,
T state,
int expectedStatusCode) {
URI uri = UriUtils.buildUri(this, factoryLink);
Operation op = Operation.createPost(uri).setBody(state);
Operation response = this.sender.sendAndWait(op);
String message = String.format("Status code expected: %s, actual: %s", expectedStatusCode,
response.getStatusCode());
assertEquals(message, expectedStatusCode, response.getStatusCode());
return response.getBody(documentType);
}
protected TemporaryFolder getTemporaryFolder() {
return this.temporaryFolder;
}
public void setTemporaryFolder(TemporaryFolder temporaryFolder) {
this.temporaryFolder = temporaryFolder;
}
/**
* Sends an operation and waits for completion. CompletionHandler on passed operation will be cleared.
*/
public void sendAndWaitExpectSuccess(Operation op) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
this.sender.sendAndWait(op);
}
public void sendAndWaitExpectFailure(Operation op) {
sendAndWaitExpectFailure(op, null);
}
public void sendAndWaitExpectFailure(Operation op, Integer expectedFailureCode) {
// to be compatible with old behavior, clear the completion handler
op.setCompletion(null);
FailureResponse resposne = this.sender.sendAndWaitFailure(op);
if (expectedFailureCode == null) {
return;
}
String msg = "got unexpected status: " + expectedFailureCode;
assertEquals(msg, (int) expectedFailureCode, resposne.op.getStatusCode());
}
/**
* Sends an operation and waits for completion.
*/
public void sendAndWait(Operation op) {
// assume completion is attached, using our getCompletion() or
// getExpectedFailureCompletion()
testStart(1);
send(op);
testWait();
}
/**
* Sends an operation, waits for completion and return the response representation.
*/
public Operation waitForResponse(Operation op) {
final Operation[] result = new Operation[1];
op.nestCompletion((o, e) -> {
result[0] = o;
completeIteration();
});
sendAndWait(op);
return result[0];
}
/**
* Decorates a {@link CompletionHandler} with a try/catch-all
* and fails the current iteration on exception. Allow for calling
* Assert.assert* directly in a handler.
*
* A safe handler will call completeIteration or failIteration exactly once.
*
* @param handler
* @return
*/
public CompletionHandler getSafeHandler(CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
completeIteration();
} catch (Throwable t) {
failIteration(t);
}
};
}
public CompletionHandler getSafeHandler(TestContext ctx, CompletionHandler handler) {
return (o, e) -> {
try {
handler.handle(o, e);
ctx.completeIteration();
} catch (Throwable t) {
ctx.failIteration(t);
}
};
}
/**
* Creates a new service instance of type {@code service} via a {@code HTTP POST} to the service
* factory URI (which is discovered automatically based on {@code service}). It passes {@code
* state} as the body of the {@code POST}.
* <p/>
* See javadoc for <i>handler</i> param for important details on how to properly use this
* method. If your test expects the service instance to be created successfully, you might use:
* <pre>
* String[] taskUri = new String[1];
* CompletionHandler successHandler = getCompletionWithUri(taskUri);
* sendFactoryPost(ExampleTaskService.class, new ExampleTaskServiceState(), successHandler);
* </pre>
*
* @param service the type of service to create
* @param state the body of the {@code POST} to use to create the service instance
* @param handler the completion handler to use when creating the service instance.
* <b>IMPORTANT</b>: This handler must properly call {@code host.failIteration()}
* or {@code host.completeIteration()}.
* @param <T> the state that represents the service instance
*/
public <T extends ServiceDocument> void sendFactoryPost(Class<? extends Service> service,
T state, CompletionHandler handler) {
URI factoryURI = UriUtils.buildFactoryUri(this, service);
log(Level.INFO, "Creating POST for [uri=%s] [body=%s]", factoryURI, state);
Operation createPost = Operation.createPost(factoryURI)
.setBody(state)
.setCompletion(handler);
this.sender.sendAndWait(createPost);
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects valid response to be returned; no exceptions when processing the operation</li>
* <li>Expects a {@code ServiceDocument} to be returned in the response body. The response's
* {@link ServiceDocument#documentSelfLink} will be stored in {@code storeUri[0]} so it can be
* used for test assertions and logic</li>
* </ul>
*
* @param storedLink The {@code documentSelfLink} of the created {@code ServiceDocument} will be
* stored in {@code storedLink[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getCompletionWithSelflink(String[] storedLink) {
if (storedLink == null || storedLink.length == 0) {
throw new IllegalArgumentException(
"storeUri must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex != null) {
failIteration(ex);
return;
}
ServiceDocument response = op.getBody(ServiceDocument.class);
if (response == null) {
failIteration(new IllegalStateException(
"Expected non-null ServiceDocument in response body"));
return;
}
log(Level.INFO, "Created service instance. [selfLink=%s] [kind=%s]",
response.documentSelfLink, response.documentKind);
storedLink[0] = response.documentSelfLink;
completeIteration();
};
}
/**
* Helper completion handler that:
* <ul>
* <li>Expects an exception when processing the handler; it is a {@code failIteration} if an
* exception is <b>not</b> thrown.</li>
* <li>The exception will be stored in {@code storeException[0]} so it can be used for test
* assertions and logic.</li>
* </ul>
*
* @param storeException the exception that occurred in completion handler will be stored in
* {@code storeException[0]} so it can be used for test assertions and
* logic. This must be non-null and its length cannot be zero.
* @return a completion handler, handy for using in methods like {@link
* #sendFactoryPost(Class, ServiceDocument, CompletionHandler)}
*/
public CompletionHandler getExpectedFailureCompletionReturningThrowable(
Throwable[] storeException) {
if (storeException == null || storeException.length == 0) {
throw new IllegalArgumentException(
"storeException must be initialized and have room for at least one item");
}
return (op, ex) -> {
if (ex == null) {
failIteration(new IllegalStateException("Failure expected"));
}
storeException[0] = ex;
completeIteration();
};
}
/**
* Helper method that waits for a query task to reach the expected stage
*/
public QueryTask waitForQueryTask(URI uri, TaskState.TaskStage expectedStage) {
// If the task's state ever reaches one of these "final" stages, we can stop waiting...
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED, expectedStage);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
QueryTask state = this.getServiceState(null, QueryTask.class, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (finalTaskStages.contains(state.taskInfo.stage)) {
return true;
}
}
return false;
});
return (QueryTask) r[0];
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FINISHED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it's {@code FINISHED}
*/
public <T extends TaskService.TaskServiceState> T waitForFinishedTask(Class<T> type,
URI taskUri) {
return waitForTask(type, taskUri.toString(), TaskState.TaskStage.FINISHED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* TaskStage.FAILED}.
*
* @param type The class type that represent's the task's state
* @param taskUri the URI of the task to wait for
* @param <T> the type that represent's the task's state
* @return the state of the task once's it s {@code FAILED}
*/
public <T extends TaskService.TaskServiceState> T waitForFailedTask(Class<T> type,
String taskUri) {
return waitForTask(type, taskUri, TaskState.TaskStage.FAILED);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage) {
return waitForTask(type, taskUri, expectedStage, false);
}
/**
* Helper method that waits for {@code taskUri} to have a {@link TaskState.TaskStage} == {@code
* expectedStage}.
*
* @param type The class type of that represents the task's state
* @param taskUri the URI of the task to wait for
* @param expectedStage the stage we expect the task to eventually get to
* @param useQueryTask Uses {@link QueryTask} to retrieve the current stage of the Task
* @param <T> the type that represents the task's state
* @return the state of the task once it's {@link TaskState.TaskStage} == {@code expectedStage}
*/
@SuppressWarnings("unchecked")
public <T extends TaskService.TaskServiceState> T waitForTask(Class<T> type, String taskUri,
TaskState.TaskStage expectedStage, boolean useQueryTask) {
URI uri = UriUtils.buildUri(taskUri);
if (!uri.isAbsolute()) {
uri = UriUtils.buildUri(this, taskUri);
}
List<TaskState.TaskStage> finalTaskStages = Arrays
.asList(TaskState.TaskStage.CANCELLED, TaskState.TaskStage.FAILED,
TaskState.TaskStage.FINISHED);
String error = String.format("Task did not reach expected state %s", expectedStage);
Object[] r = new Object[1];
final URI finalUri = uri;
waitFor(error, () -> {
T state = (useQueryTask)
? this.getServiceStateUsingQueryTask(type, taskUri)
: this.getServiceState(null, type, finalUri);
r[0] = state;
if (state.taskInfo != null) {
if (expectedStage == state.taskInfo.stage) {
return true;
}
if (finalTaskStages.contains(state.taskInfo.stage)) {
fail(String.format(
"Task was expected to reach stage %s but reached a final stage %s",
expectedStage, state.taskInfo.stage));
}
}
return false;
});
return (T) r[0];
}
@FunctionalInterface
public interface WaitHandler {
boolean isReady() throws Throwable;
}
public void waitFor(String timeoutMsg, WaitHandler wh) {
ExceptionTestUtils.executeSafely(() -> {
Date exp = getTestExpiration();
while (new Date().before(exp)) {
if (wh.isReady()) {
return;
}
// sleep for a tenth of the maintenance interval
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(getMaintenanceIntervalMicros()) / 10);
}
throw new TimeoutException(timeoutMsg);
});
}
public void setSingleton(boolean enable) {
this.isSingleton = enable;
}
/*
* Running restart tests in VMs, in over provisioned CI will cause a restart using the same
* index sand box to fail, due to a file system LockHeldException.
* The sleep just reduces the false negative test failure rate, but it can still happen.
* Not much else we can do other adding some weird polling on all the index files.
*
* Returns true of host restarted, false if retry attempts expired or other exceptions where thrown
*/
public static boolean restartStatefulHost(ServiceHost host) throws Throwable {
long exp = Utils.fromNowMicrosUtc(host.getOperationTimeoutMicros());
do {
Thread.sleep(2000);
try {
if (host.isAuthorizationEnabled()) {
host.setAuthenticationService(new AuthorizationContextService());
}
host.start();
return true;
} catch (Throwable e) {
Logger.getAnonymousLogger().warning(String
.format("exception on host restart: %s", e.getMessage()));
try {
host.stop();
} catch (Throwable e1) {
return false;
}
if (e instanceof LockObtainFailedException) {
Logger.getAnonymousLogger()
.warning("Lock held exception on host restart, retrying");
continue;
}
return false;
}
} while (Utils.getSystemNowMicrosUtc() < exp);
return false;
}
public void waitForGC() {
if (!isStressTest()) {
return;
}
for (int k = 0; k < 10; k++) {
Runtime.getRuntime().gc();
Runtime.getRuntime().runFinalization();
}
}
public TestRequestSender getTestRequestSender() {
return this.sender;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_7 |
crossvul-java_data_good_3082_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
OperationContext.setAuthorizationContext(null);
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
OperationContext.setAuthorizationContext(null);
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testODLGetWithAuthorization() throws Throwable {
long cacheDelayInterval = TimeUnit.MILLISECONDS.toMicros(100);
this.host.setMaintenanceIntervalMicros(cacheDelayInterval);
this.host.setServiceCacheClearDelayMicros(cacheDelayInterval);
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
Query resourceGroupQuery = Query.Builder.create().addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK, "*", MatchType.WILDCARD).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, email, resourceGroupQuery);
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
// verify services have stopped
this.host.waitFor("wait for services to stop.", () -> {
for (Service service : services) {
if (this.host.getServiceStage(service.getSelfLink()) != null) {
return false;
}
}
return true;
});
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectFailure(
Operation.createGet(UriUtils.buildUri(this.host, services.get(0).getSelfLink())));
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.of(Action.GET));
// Assume identity, GET should now succeed
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, services.get(0).getSelfLink())));
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
URI uri = UriUtils.buildUri(this.host, selfLink);
Operation patchOperation =
Operation.createPatch(uri)
.setBody(exampleServices.get(uri))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_1 |
crossvul-java_data_bad_4667_1 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Provides utility methods for working with {@linkplain File files}.
*
* <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
* JDK's {@link java.nio.file.Files} class.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@GwtIncompatible
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered reader
*/
@Beta
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
* java.nio.file.OpenOption...)}.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered writer
*/
@Beta
public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a new {@link ByteSource} for reading bytes from the given file.
*
* @since 14.0
*/
public static ByteSource asByteSource(File file) {
return new FileByteSource(file);
}
private static final class FileByteSource extends ByteSource {
private final File file;
private FileByteSource(File file) {
this.file = checkNotNull(file);
}
@Override
public FileInputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public Optional<Long> sizeIfKnown() {
if (file.isFile()) {
return Optional.of(file.length());
} else {
return Optional.absent();
}
}
@Override
public long size() throws IOException {
if (!file.isFile()) {
throw new FileNotFoundException(file.toString());
}
return file.length();
}
@Override
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
@Override
public String toString() {
return "Files.asByteSource(" + file + ")";
}
}
/**
* Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
* control how the file is opened for writing. When no mode is provided, the file will be
* truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
* will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static ByteSink asByteSink(File file, FileWriteMode... modes) {
return new FileByteSink(file, modes);
}
private static final class FileByteSink extends ByteSink {
private final File file;
private final ImmutableSet<FileWriteMode> modes;
private FileByteSink(File file, FileWriteMode... modes) {
this.file = checkNotNull(file);
this.modes = ImmutableSet.copyOf(modes);
}
@Override
public FileOutputStream openStream() throws IOException {
return new FileOutputStream(file, modes.contains(APPEND));
}
@Override
public String toString() {
return "Files.asByteSink(" + file + ", " + modes + ")";
}
}
/**
* Returns a new {@link CharSource} for reading character data from the given file using the given
* character set.
*
* @since 14.0
*/
public static CharSource asCharSource(File file, Charset charset) {
return asByteSource(file).asCharSource(charset);
}
/**
* Returns a new {@link CharSink} for writing character data to the given file using the given
* character set. The given {@code modes} control how the file is opened for writing. When no mode
* is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
* APPEND} mode is provided, writes will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
return asByteSink(file, modes).asCharSink(charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest possible byte array
* (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
@Beta
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
/**
* Reads all characters from a file into a {@link String}, using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static String toString(File file, Charset charset) throws IOException {
return asCharSource(file, charset).read();
}
/**
* Overwrites a file with the contents of a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
@Beta
public static void write(byte[] from, File to) throws IOException {
asByteSink(to).write(from);
}
/**
* Writes a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset).write(from);
}
/**
* Copies all bytes from a file to an output stream.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
@Beta
public static void copy(File from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Copies all the bytes from one file to another.
*
* <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process
* termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
* need to guard against those conditions, you should employ other file-level synchronization.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten
* with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i>
* file, the contents of that file will be deleted.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void copy(File from, File to) throws IOException {
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
asByteSource(from).copyTo(asByteSink(to));
}
/**
* Copies all characters from a file to an appendable object, using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static void copy(File from, Charset charset, Appendable to) throws IOException {
asCharSource(from, charset).copyTo(to);
}
/**
* Appends a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
* method is scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static void append(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, FileWriteMode.APPEND).write(from);
}
/**
* Returns true if the given files exist, are not directories, and contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
@Beta
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
@Beta
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
@SuppressWarnings("GoodTime") // reading system time without TimeSource
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException(
"Failed to create directory within "
+ TEMP_DIR_ATTEMPTS
+ " attempts (tried "
+ baseName
+ "0 to "
+ baseName
+ (TEMP_DIR_ATTEMPTS - 1)
+ ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the same as the unix command of
* the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
@Beta
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified file. Note that if
* this operation fails it may have succeeded in creating some (but not all) of the necessary
* parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
* directories of the specified file could not be created.
* @since 4.0
*/
@Beta
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
* mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
* -- or even that the caller can create it, but this method makes no such guarantees even for
* non-root files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves a file from one path to another. This method can rename a file and/or move it to a
* different directory. In either case {@code to} must be the target path for the file itself; not
* just the new name for the file or the path to the new parent directory.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include line-termination characters, but
* does include other leading and trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static String readFirstLine(File file, Charset charset) throws IOException {
return asCharSource(file, charset).readFirstLine();
}
/**
* Reads all of the lines from a file. The lines do not include line-termination characters, but
* do include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Files.asCharSource(file, charset).readLines()}.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
@Beta
public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return asCharSource(file, charset)
.readLines(
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Streams lines from a {@link File}, stopping when our callback returns false, or we have read
* all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
* @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
/**
* Fully maps a file read-only in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
* MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
return mapInternal(file, mode, -1);
}
/**
* Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
* long, long)} using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
* with the requested {@code size}. Thus this method is useful for creating memory mapped files
* which do not yet exist.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
checkArgument(size >= 0, "size (%s) may not be negative", size);
return mapInternal(file, mode, size);
}
private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
Closer closer = Closer.create();
try {
RandomAccessFile raf =
closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
FileChannel channel = closer.register(raf.getChannel());
return channel.map(mode, 0, size == -1 ? channel.size() : size);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent
* to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* <p>These heuristics do not always match the behavior of the filesystem. In particular, consider
* the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
* symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
* sibling of {@code a} referred to by {@code b}.
*
* @since 11.0
*/
@Beta
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<>();
// resolve ., .., and //
for (String component : components) {
switch (component) {
case ".":
continue;
case "..":
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
break;
default:
path.add(component);
break;
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for
* the given file name, or the empty string if the file has no extension. The result does not
* include the '{@code .}'.
*
* <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's
* name as determined by {@link File#getName}. It does not account for any filesystem-specific
* behavior that the {@link File} API does not already account for. For example, on NTFS it will
* report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
* will drop the {@code ":.txt"} part of the name when the file is actually created on the
* filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>.
*
* @since 11.0
*/
@Beta
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its <a
* href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
@Beta
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
/**
* Returns a {@link TreeTraverser} instance for {@link File} trees.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* @since 15.0
* @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
* {@link #fileTraverser()} instead with the same semantics as this method.
*/
@Deprecated
static TreeTraverser<File> fileTreeTraverser() {
return FILE_TREE_TRAVERSER;
}
private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
new TreeTraverser<File>() {
@Override
public Iterable<File> children(File file) {
return fileTreeChildren(file);
}
@Override
public String toString() {
return "Files.fileTreeTraverser()";
}
};
/**
* Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
* starts from a {@link File} and will return all files and directories it encounters.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
* except that it doesn't follow symbolic links and returns {@code Path} instances.
*
* <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
* a directory, no exception will be thrown and the returned {@link Iterable} will contain a
* single element: that file.
*
* <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
* with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
* "/home/alice", ...]}
*
* @since 23.5
*/
@Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
private static final SuccessorsFunction<File> FILE_TREE =
new SuccessorsFunction<File>() {
@Override
public Iterable<File> successors(File file) {
return fileTreeChildren(file);
}
};
private static Iterable<File> fileTreeChildren(File file) {
// check isDirectory() just because it may be faster than listFiles() on a non-directory
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return Collections.unmodifiableList(Arrays.asList(files));
}
}
return Collections.emptyList();
}
/**
* Returns a predicate that returns the result of {@link File#isDirectory} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isDirectory() {
return FilePredicate.IS_DIRECTORY;
}
/**
* Returns a predicate that returns the result of {@link File#isFile} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isFile() {
return FilePredicate.IS_FILE;
}
private enum FilePredicate implements Predicate<File> {
IS_DIRECTORY {
@Override
public boolean apply(File file) {
return file.isDirectory();
}
@Override
public String toString() {
return "Files.isDirectory()";
}
},
IS_FILE {
@Override
public boolean apply(File file) {
return file.isFile();
}
@Override
public String toString() {
return "Files.isFile()";
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_4667_1 |
crossvul-java_data_bad_3078_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.TestAuthorization.AuthzStatefulService.AuthzState;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.RoleService;
import com.vmware.xenon.services.common.RoleService.Policy;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.TransactionService.TransactionServiceState;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
@Override
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public static class AuthzStatefulService extends StatefulService {
public static class AuthzState extends ServiceDocument {
public String userLink;
}
public AuthzStatefulService() {
super(AuthzState.class);
}
@Override
public void handleStart(Operation post) {
AuthzState body = post.getBody(AuthzState.class);
AuthorizationContext authorizationContext = getAuthorizationContextForSubject(
body.userLink);
if (authorizationContext == null ||
!authorizationContext.getClaims().getSubject().equals(body.userLink)) {
post.fail(Operation.STATUS_CODE_INTERNAL_ERROR);
return;
}
post.complete();
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void factoryGetWithOData() {
// GET with ODATA will be implicitly converted to a query task. Query tasks
// require explicit authorization for the principal to be able to create them
URI exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$limit=10");
TestRequestSender sender = this.host.getTestRequestSender();
FailureResponse rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
ServiceErrorResponse errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
exampleFactoryUriWithOData = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK,
"$filter=name eq someone");
rsp = sender.sendAndWaitFailure(Operation.createGet(exampleFactoryUriWithOData));
errorRsp = rsp.op.getErrorResponseBody();
assertTrue(errorRsp.message.toLowerCase().contains("forbidden"));
assertTrue(errorRsp.message.contains(UriUtils.URI_PARAM_ODATA_TENANTLINKS));
// GET without ODATA should succeed but return empty result set
URI exampleFactoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Operation rspOp = sender.sendAndWait(Operation.createGet(exampleFactoryUri));
ServiceDocumentQueryResult queryRsp = rspOp.getBody(ServiceDocumentQueryResult.class);
assertEquals(0L, (long) queryRsp.documentCount);
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
this.host.setOperationTracingLevel(Level.FINER);
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
this.host.setOperationTracingLevel(Level.ALL);
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
// Verify that even though updates to the index are performed
// as a system user; the notification received by the subscriber of
// the continuous query has the same authorization context as that of
// user that created the continuous query.
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid auth subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// Create and subscribe to the continous query as an ordinary user.
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services as the system user
this.host.setSystemAuthorizationContext();
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(this.userServicePath);
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
Map<String, ServiceStats.ServiceStat> stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double currentInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
// Make a second request and verify that the cache did not get updated, instead Xenon re-used
// the cached Guest authorization context.
sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
stat = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT));
double newInsertCount = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_INSERT_COUNT).latestValue;
assertTrue(currentInsertCount == newInsertCount);
// Make sure that Authorization Context cache in Xenon has at least one cached token.
double currentCacheSize = stat.get(
ServiceHostManagementService.STAT_NAME_AUTHORIZATION_CACHE_SIZE).latestValue;
assertTrue(currentCacheSize == newInsertCount);
}
@Test
public void testInvalidUserAndResourceGroup() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
authsetupHelper.createRole(this.host, userGroupLink, "foo", EnumSet.allOf(Action.class));
// Assume identity
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
// set an invalid userGroupLink for the user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
UserState patchUserState = new UserState();
patchUserState.userGroupLinks = Collections.singleton("foo");
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink)).setBody(patchUserState));
this.host.assumeIdentity(userLink);
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void testAllowAndDenyRoles() throws Exception {
// 1) Create example services state as the system user
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
ExampleServiceState state = createExampleServiceState("testExampleOK", 1L);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
state = response.getBody(ExampleServiceState.class);
// 2) verify Jane cannot POST or GET
assertAccess(Policy.DENY);
// 3) build ALLOW role and verify access
buildRole("AllowRole", Policy.ALLOW);
assertAccess(Policy.ALLOW);
// 4) build DENY role and verify access
buildRole("DenyRole", Policy.DENY);
assertAccess(Policy.DENY);
// 5) build another ALLOW role and verify access
buildRole("AnotherAllowRole", Policy.ALLOW);
assertAccess(Policy.DENY);
// 6) delete deny role and verify access
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
response = this.host.waitForResponse(Operation.createDelete(
UriUtils.buildUri(this.host,
UriUtils.buildUriPath(RoleService.FACTORY_LINK, "DenyRole"))));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
assertAccess(Policy.ALLOW);
}
private void buildRole(String roleName, Policy policy) {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
TestContext ctx = this.host.testCreate(1);
AuthorizationSetupHelper.create().setHost(this.host)
.setRoleName(roleName)
.setUserGroupQuery(Query.Builder.create()
.addCollectionItemClause(UserState.FIELD_NAME_EMAIL, "jane@doe.com")
.build())
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK,
ExampleService.FACTORY_LINK,
MatchType.PREFIX)
.build())
.setVerbs(EnumSet.of(Action.POST, Action.PUT, Action.PATCH, Action.GET,
Action.DELETE))
.setPolicy(policy)
.setCompletion((authEx) -> {
if (authEx != null) {
ctx.failIteration(authEx);
return;
}
ctx.completeIteration();
}).setupRole();
this.host.testWait(ctx);
}
private void assertAccess(Policy policy) throws Exception {
this.host.assumeIdentity(this.userServicePath);
Operation response = this.host.waitForResponse(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(createExampleServiceState("testExampleDeny", 2L)));
if (policy == Policy.DENY) {
assertEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
} else {
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
}
response = this.host.waitForResponse(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
assertEquals(Operation.STATUS_CODE_OK, response.getStatusCode());
ServiceDocumentQueryResult result = response.getBody(ServiceDocumentQueryResult.class);
if (policy == Policy.DENY) {
assertEquals(Long.valueOf(0L), result.documentCount);
} else {
assertNotNull(result.documentCount);
assertNotEquals(Long.valueOf(0L), result.documentCount);
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
TestContext ctx1 = this.host.testCreate(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
ctx1.failIteration(new IllegalStateException(message));
return;
}
ctx1.completeIteration();
}));
this.host.testWait(ctx1);
// issue a GET on a factory with no auth context, no documents should be returned
TestContext ctx2 = this.host.testCreate(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
ctx2.failIteration(new IllegalStateException(message));
return;
}
ctx2.completeIteration();
}));
this.host.testWait(ctx2);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
TestContext ctx3 = this.host.testCreate(1);
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
ctx3.completeIteration();
});
this.host.send(getFactory);
this.host.testWait(ctx3);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
// test user impersonation
this.host.setSystemAuthorizationContext();
AuthzStatefulService s = new AuthzStatefulService();
this.host.addPrivilegedService(AuthzStatefulService.class);
AuthzState body = new AuthzState();
body.userLink = this.userServicePath;
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), body);
this.host.resetSystemAuthorizationContext();
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void transactionWithAuth() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"transaction-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_KIND,
Utils.buildKind(TransactionServiceState.class))
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetAuthorizationContext();
// assume identity as Jane and test to see if example service documents can be created
this.host.assumeIdentity(this.userServicePath);
String txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
boolean committed = TestTransactionUtils.commit(this.host, txid);
assertTrue(committed);
OperationContext.setTransactionId(null);
ServiceDocumentQueryResult res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(this.serviceCount), res.documentCount);
// next create docs and abort; these documents must not be present
txid = TestTransactionUtils.newTransaction(this.host);
OperationContext.setTransactionId(txid);
createExampleServices("jane");
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf(2 * this.serviceCount), res.documentCount);
boolean aborted = TestTransactionUtils.abort(this.host, txid);
assertTrue(aborted);
OperationContext.setTransactionId(null);
res = host.getFactoryState(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK));
assertEquals(Long.valueOf( this.serviceCount), res.documentCount);
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3078_1 |
crossvul-java_data_good_3079_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid aith subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.forceRemote()
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
this.host.testStart(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// issue a GET on a factory with no auth context, no documents should be returned
this.host.testStart(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// do GET on factory /stats, we should get 403
Operation statsGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
// do GET on factory /config, we should get 403
Operation configGet = Operation.createGet(this.host,
ExampleService.FACTORY_LINK + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// do GET on utility suffixes in example child services, we should get 403
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
this.host.sendAndWaitExpectFailure(statsGet, Operation.STATUS_CODE_FORBIDDEN);
configGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_CONFIG);
this.host.sendAndWaitExpectFailure(configGet, Operation.STATUS_CODE_FORBIDDEN);
}
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
// do GET on utility suffixes in example child services, we should get 200
for (URI childUri : exampleServices.keySet()) {
statsGet = Operation.createGet(this.host,
childUri.getPath() + ServiceHost.SERVICE_URI_SUFFIX_STATS);
statsGet.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
this.host.sendAndWaitExpectSuccess(statsGet);
}
verifyJaneAccess(exampleServices, authToken);
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email, true);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3079_1 |
crossvul-java_data_bad_3083_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
/**
* Dedupes most well-known strings used as stat names.
*/
private static class StatsKeyDeduper {
private final Map<String, String> map = new HashMap<>();
StatsKeyDeduper() {
register(Service.STAT_NAME_REQUEST_COUNT);
register(Service.STAT_NAME_PRE_AVAILABLE_OP_COUNT);
register(Service.STAT_NAME_AVAILABLE);
register(Service.STAT_NAME_FAILURE_COUNT);
register(Service.STAT_NAME_REQUEST_OUT_OF_ORDER_COUNT);
register(Service.STAT_NAME_REQUEST_FAILURE_QUEUE_LIMIT_EXCEEDED_COUNT);
register(Service.STAT_NAME_STATE_PERSIST_LATENCY);
register(Service.STAT_NAME_OPERATION_QUEUEING_LATENCY);
register(Service.STAT_NAME_SERVICE_HANDLER_LATENCY);
register(Service.STAT_NAME_CREATE_COUNT);
register(Service.STAT_NAME_OPERATION_DURATION);
register(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
register(Service.STAT_NAME_NODE_GROUP_SYNCH_DELAYED_COUNT);
register(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_ON_MAINT_COUNT);
register(Service.STAT_NAME_DOCUMENT_OWNER_TOGGLE_OFF_MAINT_COUNT);
register(Service.STAT_NAME_CACHE_MISS_COUNT);
register(Service.STAT_NAME_CACHE_CLEAR_COUNT);
register(Service.STAT_NAME_VERSION_CONFLICT_COUNT);
register(Service.STAT_NAME_VERSION_IN_CONFLICT);
register(Service.STAT_NAME_PAUSE_COUNT);
register(Service.STAT_NAME_RESUME_COUNT);
register(Service.STAT_NAME_MAINTENANCE_DURATION);
register(Service.STAT_NAME_SYNCH_TASK_RETRY_COUNT);
register(Service.STAT_NAME_CHILD_SYNCH_FAILURE_COUNT);
register(ServiceStatUtils.GET_DURATION);
register(ServiceStatUtils.POST_DURATION);
register(ServiceStatUtils.PATCH_DURATION);
register(ServiceStatUtils.PUT_DURATION);
register(ServiceStatUtils.DELETE_DURATION);
register(ServiceStatUtils.OPTIONS_DURATION);
register(ServiceStatUtils.GET_REQUEST_COUNT);
register(ServiceStatUtils.POST_REQUEST_COUNT);
register(ServiceStatUtils.PATCH_REQUEST_COUNT);
register(ServiceStatUtils.PUT_REQUEST_COUNT);
register(ServiceStatUtils.DELETE_REQUEST_COUNT);
register(ServiceStatUtils.OPTIONS_REQUEST_COUNT);
register(ServiceStatUtils.GET_QLATENCY);
register(ServiceStatUtils.POST_QLATENCY);
register(ServiceStatUtils.PATCH_QLATENCY);
register(ServiceStatUtils.PUT_QLATENCY);
register(ServiceStatUtils.DELETE_QLATENCY);
register(ServiceStatUtils.OPTIONS_QLATENCY);
register(ServiceStatUtils.GET_HANDLER_LATENCY);
register(ServiceStatUtils.POST_HANDLER_LATENCY);
register(ServiceStatUtils.PATCH_HANDLER_LATENCY);
register(ServiceStatUtils.PUT_HANDLER_LATENCY);
register(ServiceStatUtils.DELETE_HANDLER_LATENCY);
register(ServiceStatUtils.OPTIONS_HANDLER_LATENCY);
}
private void register(String s) {
this.map.put(s, s);
}
public String getStatKey(String s) {
return this.map.getOrDefault(s, s);
}
}
private static final StatsKeyDeduper STATS_KEY_DICT = new StatsKeyDeduper();
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
Operation.failActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Exception e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
// sort entries by key (natural ordering)
clone.entries = new TreeMap<>(stats.entries);
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.peerNodeSelectorPath == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
if (updateBody.peerNodeSelectorPath != null) {
this.parent.setPeerNodeSelectorPath(updateBody.peerNodeSelectorPath);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
addHistogram(stat, newValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
private void addHistogram(ServiceStat stat, double newValue) {
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
addHistogram(stat, stat.latestValue);
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
name = STATS_KEY_DICT.getStatKey(name);
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
}
@Override
public void setStat(String name, double newValue) {
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setDocumentIndexPath(String uriPath) {
}
@Override
public String getDocumentIndexPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_0 |
crossvul-java_data_good_4667_1 | /*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.io.FileWriteMode.APPEND;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.TreeTraverser;
import com.google.common.graph.SuccessorsFunction;
import com.google.common.graph.Traverser;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Provides utility methods for working with {@linkplain File files}.
*
* <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the
* JDK's {@link java.nio.file.Files} class.
*
* @author Chris Nokleberg
* @author Colin Decker
* @since 1.0
*/
@GwtIncompatible
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered reader
*/
@Beta
public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given character set.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset,
* java.nio.file.OpenOption...)}.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the buffered writer
*/
@Beta
public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a new {@link ByteSource} for reading bytes from the given file.
*
* @since 14.0
*/
public static ByteSource asByteSource(File file) {
return new FileByteSource(file);
}
private static final class FileByteSource extends ByteSource {
private final File file;
private FileByteSource(File file) {
this.file = checkNotNull(file);
}
@Override
public FileInputStream openStream() throws IOException {
return new FileInputStream(file);
}
@Override
public Optional<Long> sizeIfKnown() {
if (file.isFile()) {
return Optional.of(file.length());
} else {
return Optional.absent();
}
}
@Override
public long size() throws IOException {
if (!file.isFile()) {
throw new FileNotFoundException(file.toString());
}
return file.length();
}
@Override
public byte[] read() throws IOException {
Closer closer = Closer.create();
try {
FileInputStream in = closer.register(openStream());
return ByteStreams.toByteArray(in, in.getChannel().size());
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
@Override
public String toString() {
return "Files.asByteSource(" + file + ")";
}
}
/**
* Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes}
* control how the file is opened for writing. When no mode is provided, the file will be
* truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes
* will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static ByteSink asByteSink(File file, FileWriteMode... modes) {
return new FileByteSink(file, modes);
}
private static final class FileByteSink extends ByteSink {
private final File file;
private final ImmutableSet<FileWriteMode> modes;
private FileByteSink(File file, FileWriteMode... modes) {
this.file = checkNotNull(file);
this.modes = ImmutableSet.copyOf(modes);
}
@Override
public FileOutputStream openStream() throws IOException {
return new FileOutputStream(file, modes.contains(APPEND));
}
@Override
public String toString() {
return "Files.asByteSink(" + file + ", " + modes + ")";
}
}
/**
* Returns a new {@link CharSource} for reading character data from the given file using the given
* character set.
*
* @since 14.0
*/
public static CharSource asCharSource(File file, Charset charset) {
return asByteSource(file).asCharSource(charset);
}
/**
* Returns a new {@link CharSink} for writing character data to the given file using the given
* character set. The given {@code modes} control how the file is opened for writing. When no mode
* is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND
* APPEND} mode is provided, writes will append to the end of the file without truncating it.
*
* @since 14.0
*/
public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) {
return asByteSink(file, modes).asCharSink(charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest possible byte array
* (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
@Beta
public static byte[] toByteArray(File file) throws IOException {
return asByteSource(file).read();
}
/**
* Reads all characters from a file into a {@link String}, using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).read()}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static String toString(File file, Charset charset) throws IOException {
return asCharSource(file, charset).read();
}
/**
* Overwrites a file with the contents of a byte array.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
@Beta
public static void write(byte[] from, File to) throws IOException {
asByteSink(to).write(from);
}
/**
* Writes a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset).write(from)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
public static void write(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset).write(from);
}
/**
* Copies all bytes from a file to an output stream.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
@Beta
public static void copy(File from, OutputStream to) throws IOException {
asByteSource(from).copyTo(to);
}
/**
* Copies all the bytes from one file to another.
*
* <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process
* termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you
* need to guard against those conditions, you should employ other file-level synchronization.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten
* with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i>
* file, the contents of that file will be deleted.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void copy(File from, File to) throws IOException {
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
asByteSource(from).copyTo(asByteSink(to));
}
/**
* Copies all characters from a file to an appendable object, using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static void copy(File from, Charset charset, Appendable to) throws IOException {
asCharSource(from, charset).copyTo(to);
}
/**
* Appends a character sequence (such as a string) to a file using the given character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link StandardCharsets} for
* helpful predefined constants
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This
* method is scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static void append(CharSequence from, File to, Charset charset) throws IOException {
asCharSink(to, charset, FileWriteMode.APPEND).write(from);
}
/**
* Returns true if the given files exist, are not directories, and contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
@Beta
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files denoting system-dependent
* entities such as devices or pipes, in which case we must fall back on comparing the bytes
* directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return asByteSource(file1).contentEquals(asByteSource(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's temporary directory (as
* defined by the {@code java.io.tmpdir} system property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to
* create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
* delete the file and create a directory in its place, but this leads a race condition which can
* be exploited to create security vulnerabilities, especially when executable files are to be
* written into the directory.
*
* <p>Depending on the environmment that this code is run in, the system temporary directory (and
* thus the directory this method creates) may be more visible that a program would like - files
* written to this directory may be read or overwritten by hostile programs running on the same
* machine.
*
* <p>This method assumes that the temporary volume is writable, has free inodes and free blocks,
* and that it will not be called thousands of times per second.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#createTempDirectory}.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
* @deprecated For Android users, see the <a
* href="https://developer.android.com/training/data-storage" target="_blank">Data and File
* Storage overview</a> to select an appropriate temporary directory (perhaps {@code
* context.getCacheDir()}). For developers on Java 7 or later, use {@link
* java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using {@link
* java.nio.file.Path#toFile() toFile()} if needed.
*/
@Beta
@Deprecated
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
@SuppressWarnings("GoodTime") // reading system time without TimeSource
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException(
"Failed to create directory within "
+ TEMP_DIR_ATTEMPTS
+ " attempts (tried "
+ baseName
+ "0 to "
+ baseName
+ (TEMP_DIR_ATTEMPTS - 1)
+ ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the same as the unix command of
* the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
@Beta
@SuppressWarnings("GoodTime") // reading system time without TimeSource
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified file. Note that if
* this operation fails it may have succeeded in creating some (but not all) of the necessary
* parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent
* directories of the specified file could not be created.
* @since 4.0
*/
@Beta
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors exist. This doesn't
* mean that the root itself exists -- consider x:\ on a Windows machine without such a drive
* -- or even that the caller can create it, but this method makes no such guarantees even for
* non-root files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves a file from one path to another. This method can rename a file and/or move it to a
* different directory. In either case {@code to} must be the target path for the file itself; not
* just the new name for the file or the path to the new parent directory.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
@Beta
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include line-termination characters, but
* does include other leading and trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
public
static String readFirstLine(File file, Charset charset) throws IOException {
return asCharSource(file, charset).readFirstLine();
}
/**
* Reads all of the lines from a file. The lines do not include line-termination characters, but
* do include other leading and trailing whitespace.
*
* <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code
* Files.asCharSource(file, charset).readLines()}.
*
* <p><b>{@link java.nio.file.Path} equivalent:</b> {@link
* java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
@Beta
public static List<String> readLines(File file, Charset charset) throws IOException {
// don't use asCharSource(file, charset).readLines() because that returns
// an immutable list, which would change the behavior of this method
return asCharSource(file, charset)
.readLines(
new LineProcessor<List<String>>() {
final List<String> result = Lists.newArrayList();
@Override
public boolean processLine(String line) {
result.add(line);
return true;
}
@Override
public List<String> getResult() {
return result;
}
});
}
/**
* Streams lines from a {@link File}, stopping when our callback returns false, or we have read
* all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link StandardCharsets} for
* helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. This method is
* scheduled to be removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readLines(File file, Charset charset, LineProcessor<T> callback) throws IOException {
return asCharSource(file, charset).readLines(callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
* @deprecated Prefer {@code asByteSource(file).read(processor)}. This method is scheduled to be
* removed in October 2019.
*/
@Beta
@Deprecated
@CanIgnoreReturnValue // some processors won't return a useful result
public
static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException {
return asByteSource(file).read(processor);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
* @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. This method is scheduled to
* be removed in October 2019.
*/
@Beta
@Deprecated
public
static HashCode hash(File file, HashFunction hashFunction) throws IOException {
return asByteSource(file).hash(hashFunction);
}
/**
* Fully maps a file read-only in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per {@link
* FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link
* MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode) throws IOException {
return mapInternal(file, mode, -1);
}
/**
* Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode,
* long, long)} using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created
* with the requested {@code size}. Thus this method is useful for creating memory mapped files
* which do not yet exist.
*
* <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
@Beta
public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException {
checkArgument(size >= 0, "size (%s) may not be negative", size);
return mapInternal(file, mode, size);
}
private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
Closer closer = Closer.create();
try {
RandomAccessFile raf =
closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
FileChannel channel = closer.register(raf.getChannel());
return channel.map(mode, 0, size == -1 ? channel.size() : size);
} catch (Throwable e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent
* to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* <p>These heuristics do not always match the behavior of the filesystem. In particular, consider
* the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a
* symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the
* sibling of {@code a} referred to by {@code b}.
*
* @since 11.0
*/
@Beta
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<>();
// resolve ., .., and //
for (String component : components) {
switch (component) {
case ".":
continue;
case "..":
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
break;
default:
path.add(component);
break;
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for
* the given file name, or the empty string if the file has no extension. The result does not
* include the '{@code .}'.
*
* <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's
* name as determined by {@link File#getName}. It does not account for any filesystem-specific
* behavior that the {@link File} API does not already account for. For example, on NTFS it will
* report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS
* will drop the {@code ":.txt"} part of the name when the file is actually created on the
* filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>.
*
* @since 11.0
*/
@Beta
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its <a
* href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
@Beta
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
/**
* Returns a {@link TreeTraverser} instance for {@link File} trees.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* @since 15.0
* @deprecated The returned {@link TreeTraverser} type is deprecated. Use the replacement method
* {@link #fileTraverser()} instead with the same semantics as this method.
*/
@Deprecated
static TreeTraverser<File> fileTreeTraverser() {
return FILE_TREE_TRAVERSER;
}
private static final TreeTraverser<File> FILE_TREE_TRAVERSER =
new TreeTraverser<File>() {
@Override
public Iterable<File> children(File file) {
return fileTreeChildren(file);
}
@Override
public String toString() {
return "Files.fileTreeTraverser()";
}
};
/**
* Returns a {@link Traverser} instance for the file and directory tree. The returned traverser
* starts from a {@link File} and will return all files and directories it encounters.
*
* <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no
* way to ensure that a symbolic link to a directory is not followed when traversing the tree. In
* this case, iterables created by this traverser could contain files that are outside of the
* given directory or even be infinite if there is a symbolic link loop.
*
* <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same
* except that it doesn't follow symbolic links and returns {@code Path} instances.
*
* <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not
* a directory, no exception will be thrown and the returned {@link Iterable} will contain a
* single element: that file.
*
* <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files
* with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home",
* "/home/alice", ...]}
*
* @since 23.5
*/
@Beta
public static Traverser<File> fileTraverser() {
return Traverser.forTree(FILE_TREE);
}
private static final SuccessorsFunction<File> FILE_TREE =
new SuccessorsFunction<File>() {
@Override
public Iterable<File> successors(File file) {
return fileTreeChildren(file);
}
};
private static Iterable<File> fileTreeChildren(File file) {
// check isDirectory() just because it may be faster than listFiles() on a non-directory
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
return Collections.unmodifiableList(Arrays.asList(files));
}
}
return Collections.emptyList();
}
/**
* Returns a predicate that returns the result of {@link File#isDirectory} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isDirectory() {
return FilePredicate.IS_DIRECTORY;
}
/**
* Returns a predicate that returns the result of {@link File#isFile} on input files.
*
* @since 15.0
*/
@Beta
public static Predicate<File> isFile() {
return FilePredicate.IS_FILE;
}
private enum FilePredicate implements Predicate<File> {
IS_DIRECTORY {
@Override
public boolean apply(File file) {
return file.isDirectory();
}
@Override
public String toString() {
return "Files.isDirectory()";
}
},
IS_FILE {
@Override
public boolean apply(File file) {
return file.isFile();
}
@Override
public String toString() {
return "Files.isFile()";
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_4667_1 |
crossvul-java_data_bad_3081_5 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3081_5 |
crossvul-java_data_good_3083_6 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE;
import static com.vmware.xenon.common.ServiceHost.SERVICE_URI_SUFFIX_UI;
import java.net.URI;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.ServiceStatLogHistogram;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestUtilityService extends BasicReusableHostTestCase {
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<URI> services = this.host.createExampleServices(this.host, count, null);
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.PERIODIC_MAINTENANCE);
updateBody.peerNodeSelectorPath = ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR;
ctx = this.testCreate(services.size());
for (URI u : services) {
configUri = UriUtils.buildConfigUri(u);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (URI serviceUri : services) {
URI u = UriUtils.buildConfigUri(serviceUri);
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.PERIODIC_MAINTENANCE)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
if (!ServiceUriPaths.DEFAULT_1X_NODE_SELECTOR.equals(cfg.peerNodeSelectorPath)) {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
return;
}
ctx3.completeIteration();
}));
}
testWait(ctx3);
// since we enabled periodic maintenance, verify the new maintenance related stat is present
this.host.waitFor("maintenance stat not present", () -> {
for (URI u : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(u);
ServiceStat maintStat = stats.get(Service.STAT_NAME_MAINTENANCE_COUNT);
if (maintStat == null) {
return false;
}
if (maintStat.latestValue == 0) {
return false;
}
}
return true;
});
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void statRESTActions() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = getStats(exampleServiceState);
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = getStats(exampleServiceState);
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
verifyGetWithODataOnStats(exampleServiceState);
verifyStatCreationAttemptAfterGet();
}
private void verifyGetWithODataOnStats(ExampleServiceState exampleServiceState) {
URI exampleStatsUri = UriUtils.buildStatsUri(this.host,
exampleServiceState.documentSelfLink);
// bulk PUT to set stats to a known state
ServiceStats stats = new ServiceStats();
stats.kind = ServiceStats.KIND;
ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key2";
stat.latestValue = 0.0;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "key3";
stat.latestValue = -200;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 1000;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY;
stat.latestValue = 2000;
stats.entries.put(stat.name, stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(exampleStatsUri).setBody(stats));
// negative tests
URI exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_COUNT, Boolean.TRUE.toString());
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_ORDER_BY, "name");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_SKIP_TO, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_TOP, "100");
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// attempt long value LE on latestVersion, should fail
String odataFilterValue = String.format("%s le %d",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
this.host.sendAndWaitExpectFailure(Operation.createGet(exampleStatsUriWithODATA));
// Positive filter tests
String statName = "key1";
// test filter for exact match
odataFilterValue = String.format("%s eq %s",
ServiceStat.FIELD_NAME_NAME,
statName);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries.containsKey(statName));
// test filter with prefix match
odataFilterValue = String.format("%s eq %s*",
ServiceStat.FIELD_NAME_NAME,
"key");
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// three entries start with "key"
assertTrue(filteredStats.entries.size() == 3);
assertTrue(filteredStats.entries.containsKey("key1"));
assertTrue(filteredStats.entries.containsKey("key2"));
assertTrue(filteredStats.entries.containsKey("key3"));
// test filter with suffix match, common for time series filtering
odataFilterValue = String.format("%s eq *%s",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 2);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
assertTrue(filteredStats.entries
.containsKey("someOtherKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
// filter on latestValue, GE
odataFilterValue = String.format("%s ge %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 4);
// filter on latestValue, GT
odataFilterValue = String.format("%s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
0.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 3);
// filter on latestValue, eq
odataFilterValue = String.format("%s eq %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
-200.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 1);
// filter on latestValue, le
odataFilterValue = String.format("%s le %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
assertTrue(filteredStats.entries.size() == 2);
// filter on latestValue, lt AND gt
odataFilterValue = String.format("%s lt %f and %s gt %f",
ServiceStat.FIELD_NAME_LATEST_VALUE,
2000.0,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1000.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// two entries end with "Day"
assertTrue(filteredStats.entries.size() == 0);
// test dual filter with suffix match, and latest value LEQ
odataFilterValue = String.format("%s eq *%s and %s le %f",
ServiceStat.FIELD_NAME_NAME,
ServiceStats.STAT_NAME_SUFFIX_PER_DAY,
ServiceStat.FIELD_NAME_LATEST_VALUE,
1001.0);
exampleStatsUriWithODATA = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
filteredStats = getStats(exampleStatsUriWithODATA);
// single entry ends with "Day" and has latestValue <= 1000
assertTrue(filteredStats.entries.size() == 1);
assertTrue(filteredStats.entries
.containsKey("someKey" + ServiceStats.STAT_NAME_SUFFIX_PER_DAY));
}
private void verifyStatCreationAttemptAfterGet() throws Throwable {
// Create a stat without a log histogram or time series, then try to recreate with
// the extra features and make sure its updated
List<Service> services = this.host.doThroughputServiceStart(
1, MinimalTestService.class,
this.host.buildMinimalTestState(), EnumSet.of(ServiceOption.INSTRUMENTATION), null);
final String statName = "foo";
for (Service service : services) {
service.setStat(statName, 1.0);
ServiceStat st = service.getStat(statName);
assertTrue(st.timeSeriesStats == null);
assertTrue(st.logHistogram == null);
ServiceStat stNew = new ServiceStat();
stNew.name = statName;
stNew.logHistogram = new ServiceStatLogHistogram();
stNew.timeSeriesStats = new TimeSeriesStats(60,
TimeUnit.MINUTES.toMillis(1), EnumSet.of(AggregationType.AVG));
service.setStat(stNew, 11.0);
st = service.getStat(statName);
assertTrue(st.timeSeriesStats != null);
assertTrue(st.logHistogram != null);
}
}
private ServiceStats getStats(ExampleServiceState exampleServiceState) {
return this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
}
private ServiceStats getStats(URI statsUri) {
return this.host.getServiceState(null, ServiceStats.class, statsUri);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval,
EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value, 1);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue, 2);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals((2 * count) - 1));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
assertTrue(lastBin.latest.equals(newValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN,
AggregationType.MAX));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.LATEST));
timeSeriesStats.add(startTime, value, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.sum == null);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
assertTrue(lastBin.latest.equals(value));
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = getStats(returnExampleState);
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version >= 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
if (stat.timeSeriesStats.aggregationType.contains(AggregationType.AVG)) {
double maxCount = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.count > maxCount) {
maxCount = bin.count;
}
}
assertTrue(maxCount >= 1);
}
}
@Test
public void statsKeyOrder() {
ExampleServiceState state = new ExampleServiceState();
state.name = "foo";
Operation post = Operation.createPost(this.host, ExampleService.FACTORY_LINK).setBody(state);
state = this.sender.sendAndWait(post, ExampleServiceState.class);
ServiceStats stats = new ServiceStats();
ServiceStat stat = new ServiceStat();
stat.name = "keyBBB";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyCCC";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
stat = new ServiceStat();
stat.name = "keyAAA";
stat.latestValue = 10;
stats.entries.put(stat.name, stat);
URI exampleStatsUri = UriUtils.buildStatsUri(this.host, state.documentSelfLink);
this.sender.sendAndWait(Operation.createPut(exampleStatsUri).setBody(stats));
// odata stats prefix query
String odataFilterValue = String.format("%s eq %s*", ServiceStat.FIELD_NAME_NAME, "key");
URI filteredStats = UriUtils.extendUriWithQuery(exampleStatsUri,
UriUtils.URI_PARAM_ODATA_FILTER, odataFilterValue);
ServiceStats result = getStats(filteredStats);
// verify stats key order
assertEquals(3, result.entries.size());
List<String> statList = new ArrayList<>(result.entries.keySet());
assertEquals("stat index 0", "keyAAA", statList.get(0));
assertEquals("stat index 1", "keyBBB", statList.get(1));
assertEquals("stat index 2", "keyCCC", statList.get(2));
}
@Test
public void endpointAuthorization() throws Throwable {
VerificationHost host = VerificationHost.create(0);
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
host.start();
TestRequestSender sender = host.getTestRequestSender();
host.setSystemAuthorizationContext();
host.waitForReplicatedFactoryServiceAvailable(UriUtils.buildUri(host, ExampleService.FACTORY_LINK));
String exampleUser = "example@vmware.com";
String examplePass = "password";
TestContext authCtx = host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(host)
.setUserEmail(exampleUser)
.setUserPassword(examplePass)
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.build())
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create a sample service
ExampleServiceState doc = new ExampleServiceState();
doc.name = "foo";
doc.documentSelfLink = "foo";
Operation post = Operation.createPost(host, ExampleService.FACTORY_LINK).setBody(doc);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
host.resetAuthorizationContext();
URI factoryAvailableUri = UriUtils.buildAvailableUri(host, ExampleService.FACTORY_LINK);
URI factoryStatsUri = UriUtils.buildStatsUri(host, ExampleService.FACTORY_LINK);
URI factoryConfigUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
URI factorySubscriptionUri = UriUtils.buildSubscriptionUri(host, ExampleService.FACTORY_LINK);
URI factoryTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_TEMPLATE));
URI factoryUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(ExampleService.FACTORY_LINK, SERVICE_URI_SUFFIX_UI));
URI serviceAvailableUri = UriUtils.buildAvailableUri(host, postResult.documentSelfLink);
URI serviceStatsUri = UriUtils.buildStatsUri(host, postResult.documentSelfLink);
URI serviceConfigUri = UriUtils.buildConfigUri(host, postResult.documentSelfLink);
URI serviceSubscriptionUri = UriUtils.buildSubscriptionUri(host, postResult.documentSelfLink);
URI serviceTemplateUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_TEMPLATE));
URI serviceUiUri = UriUtils.buildUri(host, UriUtils.buildUriPath(postResult.documentSelfLink, SERVICE_URI_SUFFIX_UI));
// check non-authenticated user receives forbidden response
FailureResponse failureResponse;
Operation uiOpResult;
// check factory endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factorySubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(factoryTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check service endpoints
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceAvailableUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceStatsUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceConfigUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceSubscriptionUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
failureResponse = sender.sendAndWaitFailure(Operation.createGet(serviceTemplateUri));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
uiOpResult = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, uiOpResult.getStatusCode());
// check authenticated user does NOT receive forbidden response
AuthTestUtils.login(host, exampleUser, examplePass);
Operation response;
// check factory endpoints
response = sender.sendAndWait(Operation.createGet(factoryAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factorySubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(factoryUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
// check service endpoints
response = sender.sendAndWait(Operation.createGet(serviceAvailableUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceStatsUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceConfigUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceSubscriptionUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceTemplateUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
response = sender.sendAndWait(Operation.createGet(serviceUiUri));
assertNotEquals(Operation.STATUS_CODE_FORBIDDEN, response.getStatusCode());
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3083_6 |
crossvul-java_data_bad_3083_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
@Override
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
// create example service documents across all nodes
List<URI> exampleURIs = serviceHost.createExampleServices(serviceHost, serviceCount, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void subscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = hostWithAuth.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = hostWithAuth.testCreate(1);
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void testSubscriptionsWithExpiry() throws Throwable {
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = this.host.testCreate(1);
TestContext notifyDeleteContext = this.host.testCreate(1);
this.host.startServiceAndWait(s, minimalServiceUUID, serviceState);
Service notificationTarget = new StatelessService() {
@Override
public void authorizeRequest(Operation op) {
op.complete();
return;
}
@Override
public void handleRequest(Operation op) {
if (!op.isNotification()) {
if (op.getAction() == Action.DELETE && op.getUri().equals(getUri())) {
notifyDeleteContext.completeIteration();
}
super.handleRequest(op);
return;
}
if (op.getAction() == Action.PUT) {
notifyContext.completeIteration();
}
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(host, minimalServiceUUID));
subscribe.setReferer(host.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
// Set a 500ms expiry
subscriber.documentExpirationTimeMicros = Utils
.fromNowMicrosUtc(TimeUnit.MILLISECONDS.toMicros(500));
host.startSubscriptionService(subscribe, notificationTarget, subscriber);
host.testWait(notifyContext);
host.testWait(notifyDeleteContext);
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
setUpPeers();
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.fromNowMicrosUtc(
this.host.getMaintenanceIntervalMicros() * 2);
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
AtomicBoolean isConverged = new AtomicBoolean();
this.host.waitFor("subscriber verification timed out", () -> {
isConverged.set(true);
Map<URI, ServiceSubscriptionState> subStates = new ConcurrentSkipListMap<>();
TestContext ctx = this.host.testCreate(uris.length);
for (URI u : subUris) {
this.host.send(Operation.createGet(u).setCompletion((o, e) -> {
ServiceSubscriptionState s = null;
if (e == null) {
s = o.getBody(ServiceSubscriptionState.class);
} else {
this.host.log("error response from %s: %s", o.getUri(), e.getMessage());
// because we stopped an owner node, if gossip is not updated a GET
// to subscriptions might fail because it was forward to a stale node
s = new ServiceSubscriptionState();
s.subscribers = new HashMap<>();
}
subStates.put(o.getUri(), s);
ctx.complete();
}));
}
ctx.await();
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged.set(false);
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged.set(false);
break;
}
}
}
if (isConverged.get() || !wait) {
return true;
}
return false;
});
return isConverged.get();
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3083_4 |
crossvul-java_data_good_3082_2 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UserService;
import com.vmware.xenon.services.common.authn.AuthenticationRequest;
import com.vmware.xenon.services.common.authn.BasicAuthenticationUtils;
public class TestExampleServiceHost extends BasicReusableHostTestCase {
private static final String adminUser = "admin@localhost";
private static final String exampleUser = "example@localhost";
/**
* Verify that the example service host creates users as expected.
*
* In theory we could test that authentication and authorization works correctly
* for these users. It's not critical to do here since we already test it in
* TestAuthSetupHelper.
*/
@Test
public void createUsers() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
TemporaryFolder tmpFolder = new TemporaryFolder();
tmpFolder.create();
try {
String bindAddress = "127.0.0.1";
String[] args = {
"--sandbox="
+ tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--adminUser=" + adminUser,
"--adminUserPassword=" + adminUser,
"--exampleUser=" + exampleUser,
"--exampleUserPassword=" + exampleUser,
};
h.initialize(args);
h.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
h.start();
URI hostUri = h.getUri();
String authToken = loginUser(hostUri);
waitForUsers(hostUri, authToken);
} finally {
h.stop();
tmpFolder.delete();
}
}
/**
* Supports createUsers() by logging in as the admin. The admin user
* isn't created immediately, so this polls.
*/
private String loginUser(URI hostUri) throws Throwable {
String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
AuthenticationRequest login = new AuthenticationRequest();
login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;
String[] authToken = new String[1];
authToken[0] = null;
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
Operation loginPost = Operation.createPost(loginUri)
.setBody(login)
.addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
.forceRemote()
.setCompletion((op, ex) -> {
if (ex != null) {
this.host.completeIteration();
return;
}
authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(loginPost);
this.host.testWait();
if (authToken[0] != null) {
break;
}
Thread.sleep(250);
}
if (new Date().after(exp)) {
throw new TimeoutException();
}
assertNotNull(authToken[0]);
return authToken[0];
}
/**
* Supports createUsers() by waiting for two users to be created. They aren't created immediately,
* so this polls.
*/
private void waitForUsers(URI hostUri, String authToken) throws Throwable {
URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
Integer[] numberUsers = new Integer[1];
for (int i = 0; i < 20; i++) {
Operation get = Operation.createGet(usersLink)
.forceRemote()
.addRequestHeader(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken)
.setCompletion((op, ex) -> {
if (ex != null) {
if (op.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(ex);
return;
} else {
numberUsers[0] = 0;
this.host.completeIteration();
return;
}
}
ServiceDocumentQueryResult response = op
.getBody(ServiceDocumentQueryResult.class);
assertTrue(response != null && response.documentLinks != null);
numberUsers[0] = response.documentLinks.size();
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(get);
this.host.testWait();
if (numberUsers[0] == 2) {
break;
}
Thread.sleep(250);
}
assertTrue(numberUsers[0] == 2);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3082_2 |
crossvul-java_data_good_3076_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleNonPersistedService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
// check that a description was replaced with contents from HTML file
assertTrue(desc.propertyDescriptions.get("keyValues").propertyDocumentation.startsWith("Key/Value"));
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
// some services are at 100ms maintenance and the host is at 30 seconds, verify the
// check maintenance interval is the minimum of the two
long currentMaintInterval = this.host.getMaintenanceIntervalMicros();
long currentCheckInterval = this.host.getMaintenanceCheckIntervalMicros();
assertTrue(currentMaintInterval > currentCheckInterval);
// create new set of services
services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// set the interval for a service to something smaller than the host interval, then confirm
// that only the maintenance *check* interval changed, not the host global maintenance interval, which
// can affect all services
for (Service s : services) {
s.setMaintenanceIntervalMicros(currentCheckInterval / 2);
break;
}
this.host.waitFor("check interval not updated", () -> {
// verify the check interval is now lower
if (currentCheckInterval / 2 != this.host.getMaintenanceCheckIntervalMicros()) {
return false;
}
if (currentMaintInterval != this.host.getMaintenanceIntervalMicros()) {
return false;
}
return true;
});
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountDaily));
return false;
}
ServiceStat http1PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1PendingCountHourly));
return false;
}
ServiceStat http2PendingCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2PendingCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountDaily));
return false;
}
ServiceStat http2PendingCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2PendingCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2PendingCountHourly));
return false;
}
ServiceStat http1AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountDaily));
return false;
}
ServiceStat http1AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http1AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http1AvailableConnectionCountHourly));
return false;
}
ServiceStat http2AvailableConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountDaily));
return false;
}
ServiceStat http2AvailableConnectionCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_AVAILABLE_CONNECTION_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(http2AvailableConnectionCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(http2AvailableConnectionCountHourly));
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void testCacheClearAndRefresh() throws Throwable {
setUp(false);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS.toMicros(1));
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = UUID.randomUUID().toString();
op.setBody(st);
}, factoryUri);
this.host.waitFor("Service state cache eviction failed to occur", () -> {
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
if (cacheMissStat != null && cacheMissStat.latestValue > 0) {
throw new IllegalStateException("Upexpected cache miss stat value "
+ cacheMissStat.latestValue);
}
ServiceStat cacheClearStat = stats.get(Service.STAT_NAME_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue == 0) {
return false;
} else if (cacheClearStat.latestValue > 1) {
throw new IllegalStateException("Unexpected cache clear stat value "
+ cacheClearStat.latestValue);
}
}
return true;
});
this.host.setServiceCacheClearDelayMicros(
ServiceHostState.DEFAULT_OPERATION_TIMEOUT_MICROS);
// Perform a GET on each service to repopulate the service state cache
TestContext ctx = this.host.testCreate(states.size());
for (URI serviceUri : states.keySet()) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
this.host.testWait(ctx);
// Now do many more overlapping gets -- since the operations above have returned, these
// should all hit the cache.
int requestCount = 10;
ctx = this.host.testCreate(requestCount * states.size());
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < requestCount; i++) {
Operation get = Operation.createGet(serviceUri).setCompletion(ctx.getCompletion());
this.host.send(get);
}
}
this.host.testWait(ctx);
for (URI serviceUri : states.keySet()) {
Map<String, ServiceStat> stats = this.host.getServiceStats(serviceUri);
ServiceStat cacheMissStat = stats.get(Service.STAT_NAME_CACHE_MISS_COUNT);
assertNotNull(cacheMissStat);
assertEquals(1, cacheMissStat.latestValue, 0.01);
}
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
@Test
public void serviceStopDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service stop
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
String factoryLink = OnDemandLoadFactoryService.create(this.host);
URI factoryURI = UriUtils.buildUri(this.host, factoryLink);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will stop all the services
// we just created since the memory limit was set so low.
long expectedStopTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedStopTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify stopped services get started.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting stop to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be started
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely stopped) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
}
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertEquals(ProcessingStage.AVAILABLE, this.host.getServiceStage(servicePath));
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void queryServiceUris() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
// use path prefix match
this.host.testStart(1);
this.host.queryServiceUris(ExampleService.FACTORY_LINK + "/*", get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
assertEquals((long) serviceCount, (long) results[0].documentCount);
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
assertEquals((long) results[0].documentLinks.size(), (long) results[0].documentCount);
}
@Test
public void queryServiceUrisWithAuth() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new ExampleNonPersistedService());
this.host.waitForServiceAvailable(ExampleNonPersistedService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
// create user foo@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserFoo = this.host.testCreate(1);
String userFoo = "foo@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userFoo)
.setUserSelfLink(userFoo)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "foo")
.build())
.setCompletion(createUserFoo.getCompletion())
.start();
createUserFoo.await();
// create user bar@example.com who has access to ExampleServiceState with name="foo"
TestContext createUserBar = this.host.testCreate(1);
String userBar = "bar@example.com";
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(userBar)
.setUserSelfLink(userBar)
.setUserPassword("password")
.setResourceQuery(Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class))
.addFieldClause(ExampleServiceState.FIELD_NAME_NAME, "bar")
.build())
.setCompletion(createUserBar.getCompletion())
.start();
createUserBar.await();
// create foo & bar documents
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
ExampleServiceState exampleBar = new ExampleServiceState();
exampleBar.name = "bar";
exampleBar.documentSelfLink = "bar";
List<Operation> posts = new ArrayList<>();
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleFoo));
posts.add(Operation.createPost(this.host, ExampleNonPersistedService.FACTORY_LINK).setBody(exampleBar));
sender.sendAndWait(posts);
AuthTestUtils.resetAuthorizationContext(this.host);
// login as foo
AuthTestUtils.loginAndSetToken(this.host, "foo@example.com", "password");
Operation factoryGetFoo = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultFoo = sender.sendAndWait(factoryGetFoo, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultFoo.documentLinks.size());
assertEquals("/core/nonpersist-examples/foo", factoryGetResultFoo.documentLinks.get(0));
// login as bar
AuthTestUtils.loginAndSetToken(this.host, "bar@example.com", "password");
Operation factoryGetBar = Operation.createGet(this.host, ExampleNonPersistedService.FACTORY_LINK);
ServiceDocumentQueryResult factoryGetResultBar = sender.sendAndWait(factoryGetBar, ServiceDocumentQueryResult.class);
assertEquals(1, factoryGetResultBar.documentLinks.size());
assertEquals("/core/nonpersist-examples/bar", factoryGetResultBar.documentLinks.get(0));
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
if (!this.host.isStopping()) {
AuthTestUtils.logout(this.host);
}
this.host.tearDown();
this.host = null;
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3076_3 |
crossvul-java_data_bad_3075_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.net.URI;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import org.junit.After;
import org.junit.Test;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.common.http.netty.NettyHttpServiceClient;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupConfig;
import com.vmware.xenon.services.common.ServiceUriPaths;
public class TestSubscriptions extends BasicTestCase {
private final int NODE_COUNT = 2;
public int serviceCount = 100;
public long updateCount = 10;
public long iterationCount = 0;
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
}
@After
public void tearDown() {
this.host.tearDown();
this.host.tearDownInProcessPeers();
}
private void setUpPeers() throws Throwable {
this.host.setUpPeerHosts(this.NODE_COUNT);
this.host.joinNodesAndVerifyConvergence(this.NODE_COUNT);
}
@Test
public void remoteAndReliableSubscriptionsLoop() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
this.host = createHost();
initializeHost(this.host);
beforeHostStart(this.host);
this.host.start();
remoteAndReliableSubscriptions();
}
}
@Test
public void remoteAndReliableSubscriptions() throws Throwable {
setUpPeers();
// pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
URI factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
// test host to receive notifications
VerificationHost localHost = this.host;
int serviceCount = 1;
List<URI> exampleURIs = new ArrayList<>();
// create example service documents across all nodes
serviceHost.createExampleServices(serviceHost, serviceCount, exampleURIs, null);
TestContext oneUseNotificationCtx = this.host.testCreate(1);
StatelessService notificationTarget = new StatelessService() {
@Override
public void handleRequest(Operation update) {
update.complete();
if (update.getAction().equals(Action.PATCH)) {
if (update.getUri().getHost() == null) {
oneUseNotificationCtx.fail(new IllegalStateException(
"Notification URI does not have host specified"));
return;
}
oneUseNotificationCtx.complete();
}
}
};
String[] ownerHostId = new String[1];
URI uri = exampleURIs.get(0);
URI subUri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
TestContext subscribeCtx = this.host.testCreate(1);
Operation subscribe = Operation.createPost(subUri)
.setCompletion(subscribeCtx.getCompletion());
subscribe.setReferer(localHost.getReferer());
subscribe.forceRemote();
// replay state
serviceHost.startSubscriptionService(subscribe, notificationTarget, ServiceSubscriber
.create(false).setUsePublicUri(true));
this.host.testWait(subscribeCtx);
// do an update to cause a notification
TestContext updateCtx = this.host.testCreate(1);
ExampleServiceState body = new ExampleServiceState();
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body).setCompletion((o, e) -> {
if (e != null) {
updateCtx.fail(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
ownerHostId[0] = rsp.documentOwner;
updateCtx.complete();
}));
this.host.testWait(updateCtx);
this.host.testWait(oneUseNotificationCtx);
// remove subscription
TestContext unSubscribeCtx = this.host.testCreate(1);
Operation unSubscribe = subscribe.clone()
.setCompletion(unSubscribeCtx.getCompletion())
.setAction(Action.DELETE);
serviceHost.stopSubscriptionService(unSubscribe,
notificationTarget.getUri());
this.host.testWait(unSubscribeCtx);
this.verifySubscriberCount(new URI[] { uri }, 0);
VerificationHost ownerHost = null;
// find the host that owns the example service and make sure we subscribe from the OTHER
// host (since we will stop the current owner)
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
if (!h.getId().equals(ownerHostId[0])) {
serviceHost = h;
} else {
ownerHost = h;
}
}
this.host.log("Owner node: %s, subscriber node: %s (%s)", ownerHostId[0],
serviceHost.getId(), serviceHost.getUri());
AtomicInteger reliableNotificationCount = new AtomicInteger();
TestContext subscribeCtxNonOwner = this.host.testCreate(1);
// subscribe using non owner host
subscribe.setCompletion(subscribeCtxNonOwner.getCompletion());
serviceHost.startReliableSubscriptionService(subscribe, (o) -> {
reliableNotificationCount.incrementAndGet();
o.complete();
});
localHost.testWait(subscribeCtxNonOwner);
// send explicit update to example service
body.name = UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
while (reliableNotificationCount.get() < 1) {
Thread.sleep(100);
}
reliableNotificationCount.set(0);
this.verifySubscriberCount(new URI[] { uri }, 1);
// Check reliability: determine what host is owner for the example service we subscribed to.
// Then stop that host which should cause the remaining host(s) to pick up ownership.
// Subscriptions will not survive on their own, but we expect the ReliableSubscriptionService
// to notice the subscription is gone on the new owner, and re subscribe.
List<URI> exampleSubUris = new ArrayList<>();
for (URI hostUri : this.host.getNodeGroupMap().keySet()) {
exampleSubUris.add(UriUtils.buildUri(hostUri, uri.getPath(),
ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS));
}
// stop host that has ownership of example service
NodeGroupConfig cfg = new NodeGroupConfig();
cfg.nodeRemovalDelayMicros = TimeUnit.SECONDS.toMicros(2);
this.host.setNodeGroupConfig(cfg);
// relax quorum
this.host.setNodeGroupQuorum(1);
// stop host with subscription
this.host.stopHost(ownerHost);
factoryUri = UriUtils.buildUri(serviceHost, ExampleService.FACTORY_LINK);
this.host.waitForReplicatedFactoryServiceAvailable(factoryUri);
uri = UriUtils.buildUri(serviceHost.getUri(), uri.getPath());
// verify that we still have 1 subscription on the remaining host, which can only happen if the
// reliable subscription service notices the current owner failure and re subscribed
this.verifySubscriberCount(new URI[] { uri }, 1);
// and test once again that notifications flow.
this.host.log("Sending PATCH requests to %s", uri);
long c = this.updateCount;
for (int i = 0; i < c; i++) {
body.name = "post-stop-" + UUID.randomUUID().toString();
this.host.send(Operation.createPatch(uri).setBody(body));
}
Date exp = this.host.getTestExpiration();
while (reliableNotificationCount.get() < c) {
Thread.sleep(250);
this.host.log("Received %d notifications, expecting %d",
reliableNotificationCount.get(), c);
if (new Date().after(exp)) {
throw new TimeoutException();
}
}
}
@Test
public void subscriptionsToFactoryAndChildren() throws Throwable {
this.host.stop();
this.host.setPort(0);
this.host.start();
this.host.setPublicUri(UriUtils.buildUri("localhost", this.host.getPort(), "", null));
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
URI factoryUri = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String prefix = "example-";
Long counterValue = Long.MAX_VALUE;
URI[] childUris = new URI[this.serviceCount];
doFactoryPostNotifications(factoryUri, this.serviceCount, prefix, counterValue, childUris);
doNotificationsWithReplayState(childUris);
doNotificationsWithFailure(childUris);
doNotificationsWithLimitAndPublicUri(childUris);
doNotificationsWithExpiration(childUris);
doDeleteNotifications(childUris, counterValue);
}
@Test
public void testSubscriptionsWithAuth() throws Throwable {
VerificationHost hostWithAuth = null;
try {
String testUserEmail = "foo@vmware.com";
hostWithAuth = VerificationHost.create(0);
hostWithAuth.setAuthorizationEnabled(true);
hostWithAuth.start();
hostWithAuth.setSystemAuthorizationContext();
TestContext waitContext = new TestContext(1, Duration.ofSeconds(5));
AuthorizationSetupHelper.create()
.setHost(hostWithAuth)
.setDocumentKind(Utils.buildKind(MinimalTestServiceState.class))
.setUserEmail(testUserEmail)
.setUserSelfLink(testUserEmail)
.setUserPassword(testUserEmail)
.setCompletion(waitContext.getCompletion())
.start();
hostWithAuth.testWait(waitContext);
hostWithAuth.resetSystemAuthorizationContext();
hostWithAuth.assumeIdentity(UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, testUserEmail));
MinimalTestService s = new MinimalTestService();
MinimalTestServiceState serviceState = new MinimalTestServiceState();
serviceState.id = UUID.randomUUID().toString();
String minimalServiceUUID = UUID.randomUUID().toString();
TestContext notifyContext = new TestContext(1, Duration.ofSeconds(5));
hostWithAuth.startServiceAndWait(s, minimalServiceUUID, serviceState);
Consumer<Operation> notifyC = (nOp) -> {
nOp.complete();
switch (nOp.getAction()) {
case PUT:
notifyContext.completeIteration();
break;
default:
break;
}
};
Operation subscribe = Operation.createPost(UriUtils.buildUri(hostWithAuth, minimalServiceUUID));
subscribe.setReferer(hostWithAuth.getReferer());
ServiceSubscriber subscriber = new ServiceSubscriber();
subscriber.replayState = true;
hostWithAuth.startSubscriptionService(subscribe, notifyC, subscriber);
hostWithAuth.testWait(notifyContext);
} finally {
if (hostWithAuth != null) {
hostWithAuth.tearDown();
}
}
}
@Test
public void subscribeAndWaitForServiceAvailability() throws Throwable {
// until HTTP2 support is we must only subscribe to less than max connections!
// otherwise we deadlock: the connection for the queued subscribe is used up,
// no more connections can be created, to that owner.
this.serviceCount = NettyHttpServiceClient.DEFAULT_CONNECTIONS_PER_HOST / 2;
// set the connection limit higher for the test host since it will be issuing parallel
// subscribes, POSTs
this.host.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
setUpPeers();
for (VerificationHost h : this.host.getInProcessHostMap().values()) {
h.getClient().setConnectionLimitPerHost(this.serviceCount * 4);
}
this.host.waitForReplicatedFactoryServiceAvailable(
this.host.getPeerServiceUri(ExampleService.FACTORY_LINK));
// Pick one host to post to
VerificationHost serviceHost = this.host.getPeerHost();
// Create example service states to subscribe to
List<ExampleServiceState> states = new ArrayList<>();
for (int i = 0; i < this.serviceCount; i++) {
ExampleServiceState state = new ExampleServiceState();
state.documentSelfLink = UriUtils.buildUriPath(
ExampleService.FACTORY_LINK,
UUID.randomUUID().toString());
state.name = UUID.randomUUID().toString();
states.add(state);
}
AtomicInteger notifications = new AtomicInteger();
// Subscription target
ServiceSubscriber sr = createAndStartNotificationTarget((update) -> {
if (update.getAction() != Action.PATCH) {
// because we start multiple nodes and we do not wait for factory start
// we will receive synchronization related PUT requests, on each service.
// Ignore everything but the PATCH we send from the test
return false;
}
this.host.completeIteration();
this.host.log("notification %d", notifications.incrementAndGet());
update.complete();
return true;
});
this.host.log("Subscribing to %d services", this.serviceCount);
// Subscribe to factory (will not complete until factory is started again)
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildUri(serviceHost, state.documentSelfLink);
subscribeToService(uri, sr);
}
// First the subscription requests will be sent and will be queued.
// So N completions come from the subscribe requests.
// After that, the services will be POSTed and started. This is the second set
// of N completions.
this.host.testStart(2 * this.serviceCount);
this.host.log("Sending parallel POST for %d services", this.serviceCount);
AtomicInteger postCount = new AtomicInteger();
// Create example services, triggering subscriptions to complete
for (ExampleServiceState state : states) {
URI uri = UriUtils.buildFactoryUri(serviceHost, ExampleService.class);
Operation op = Operation.createPost(uri)
.setBody(state)
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
this.host.log("POST count %d", postCount.incrementAndGet());
this.host.completeIteration();
});
this.host.send(op);
}
this.host.testWait();
this.host.testStart(2 * this.serviceCount);
// now send N PATCH ops so we get notifications
for (ExampleServiceState state : states) {
// send a PATCH, to trigger notification
URI u = UriUtils.buildUri(serviceHost, state.documentSelfLink);
state.counter = Utils.getNowMicrosUtc();
Operation patch = Operation.createPatch(u)
.setBody(state)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
this.host.testWait();
}
private void doFactoryPostNotifications(URI factoryUri, int childCount, String prefix,
Long counterValue,
URI[] childUris) throws Throwable {
this.host.log("starting subscription to factory");
this.host.testStart(1);
// let the service host update the URI from the factory to its subscriptions
Operation subscribeOp = Operation.createPost(factoryUri)
.setReferer(this.host.getReferer())
.setCompletion(this.host.getCompletion());
URI notificationTarget = host.startSubscriptionService(subscribeOp, (o) -> {
if (o.getAction() == Action.POST) {
this.host.completeIteration();
} else {
this.host.failIteration(new IllegalStateException("Unexpected notification: "
+ o.toString()));
}
});
this.host.testWait();
// expect a POST notification per child, a POST completion per child
this.host.testStart(childCount * 2);
for (int i = 0; i < childCount; i++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.name = initialState.documentSelfLink = prefix + i;
initialState.counter = counterValue;
final int finalI = i;
// create an example service
this.host.send(Operation
.createPost(factoryUri)
.setBody(initialState).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ServiceDocument rsp = o.getBody(ServiceDocument.class);
childUris[finalI] = UriUtils.buildUri(this.host, rsp.documentSelfLink);
this.host.completeIteration();
}));
}
this.host.testWait();
this.host.testStart(1);
Operation delete = subscribeOp.clone().setUri(factoryUri).setAction(Action.DELETE);
this.host.stopSubscriptionService(delete, notificationTarget);
this.host.testWait();
this.verifySubscriberCount(new URI[]{factoryUri}, 0);
}
private void doNotificationsWithReplayState(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with replay");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(
UUID.randomUUID().toString(),
deletesRemainingCount);
sr.replayState = true;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
patchChildren(childUris, false);
patchChildren(childUris, false);
// Finally un subscribe the notification handlers
unsubscribeFromChildren(childUris, sr.reference, false);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doNotificationsWithExpiration(URI[] childUris)
throws Throwable {
this.host.log("starting subscription with expiration");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
// start a notification target that will not complete test iterations since expirations race
// with notifications, allowing for notifications to be processed after the next test starts
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount, false, false);
sr.documentExpirationTimeMicros = Utils.getNowMicrosUtc()
+ this.host.getMaintenanceIntervalMicros() * 2;
// Subscribe to notifications from every example service; get notified with current state
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
Thread.sleep((this.host.getMaintenanceIntervalMicros() / 1000) * 2);
// do a patch which will cause the publisher to evaluate and expire subscriptions
patchChildren(childUris, true);
verifySubscriberCount(childUris, 0);
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void deleteNotificationTarget(AtomicInteger deletesRemainingCount,
ServiceSubscriber sr) throws Throwable {
deletesRemainingCount.set(1);
TestContext ctx = testCreate(1);
this.host.send(Operation.createDelete(sr.reference)
.setCompletion((o, e) -> ctx.completeIteration()));
testWait(ctx);
}
private void doNotificationsWithFailure(URI[] childUris) throws Throwable, InterruptedException {
this.host.log("starting subscription with failure, stopping notification target");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, but stop the notification target, causing automatic removal of the
// subscriptions
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
deleteNotificationTarget(deletesRemainingCount, sr);
// send updates and expect failure in delivering notifications
patchChildren(childUris, true);
// expect the publisher to note at least one failed notification attempt
verifySubscriberCount(true, childUris, 1, 1L);
// restart notification target service but expect a pragma in the notifications
// saying we missed some
boolean expectSkippedNotificationsPragma = true;
this.host.log("restarting notification target");
createAndStartNotificationTarget(sr.reference.getPath(),
deletesRemainingCount, expectSkippedNotificationsPragma, true);
// send some more updates, this time expect ZERO failures;
patchChildren(childUris, false);
verifySubscriberCount(true, childUris, 1, 0L);
this.host.log("stopping notification target, again");
deleteNotificationTarget(deletesRemainingCount, sr);
while (!verifySubscriberCount(false, childUris, 0, null)) {
Thread.sleep(VerificationHost.FAST_MAINT_INTERVAL_MILLIS);
patchChildren(childUris, true);
}
this.host.log("Verifying all subscriptions have been removed");
// because we sent more than K updates, causing K + 1 notification delivery failures,
// the subscriptions should all be automatically removed!
verifySubscriberCount(childUris, 0);
}
private void doNotificationsWithLimitAndPublicUri(URI[] childUris) throws Throwable,
InterruptedException, TimeoutException {
this.host.log("starting subscription with limit and public uri");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
// Re subscribe, use public URI and limit notifications to one.
// After these notifications are sent, we should see all subscriptions removed
deletesRemainingCount.set(childUris.length + 1);
sr.usePublicUri = true;
sr.notificationLimit = this.updateCount;
subscribeToServices(childUris, sr);
verifySubscriberCount(childUris, 1);
// Issue another patch request on every example service instance
patchChildren(childUris, false);
// because we set notificationLimit, all subscriptions should be removed
verifySubscriberCount(childUris, 0);
Date exp = this.host.getTestExpiration();
// verify we received DELETEs on the notification target when a subscription was removed
while (deletesRemainingCount.get() != 1) {
Thread.sleep(250);
if (new Date().after(exp)) {
throw new TimeoutException("DELETEs not received at notification target:"
+ deletesRemainingCount.get());
}
}
deleteNotificationTarget(deletesRemainingCount, sr);
}
private void doDeleteNotifications(URI[] childUris, Long counterValue) throws Throwable {
this.host.log("starting subscription for DELETEs");
final AtomicInteger deletesRemainingCount = new AtomicInteger();
ServiceSubscriber sr = createAndStartNotificationTarget(UUID.randomUUID()
.toString(), deletesRemainingCount);
subscribeToServices(childUris, sr);
// Issue DELETEs and verify the subscription was notified
this.host.testStart(childUris.length * 2);
for (URI child : childUris) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = counterValue;
Operation delete = Operation
.createDelete(child)
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(delete);
}
this.host.testWait();
deleteNotificationTarget(deletesRemainingCount, sr);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount) throws Throwable {
return createAndStartNotificationTarget(link, deletesRemainingCount, false, true);
}
private ServiceSubscriber createAndStartNotificationTarget(String link,
final AtomicInteger deletesRemainingCount,
boolean expectSkipNotificationsPragma,
boolean completeIterations) throws Throwable {
final AtomicBoolean seenSkippedNotificationPragma =
new AtomicBoolean(false);
return createAndStartNotificationTarget(link, (update) -> {
if (!update.isNotification()) {
if (update.getAction() == Action.DELETE) {
int r = deletesRemainingCount.decrementAndGet();
if (r != 0) {
update.complete();
return true;
}
}
return false;
}
if (update.getAction() != Action.PATCH &&
update.getAction() != Action.PUT &&
update.getAction() != Action.DELETE) {
update.complete();
return true;
}
if (expectSkipNotificationsPragma) {
String pragma = update.getRequestHeader(Operation.PRAGMA_HEADER);
if (!seenSkippedNotificationPragma.get() && (pragma == null
|| !pragma.contains(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS))) {
this.host.failIteration(new IllegalStateException(
"Missing skipped notification pragma"));
return true;
} else {
seenSkippedNotificationPragma.set(true);
}
}
if (completeIterations) {
this.host.completeIteration();
}
update.complete();
return true;
});
}
private ServiceSubscriber createAndStartNotificationTarget(
Function<Operation, Boolean> h) throws Throwable {
return createAndStartNotificationTarget(UUID.randomUUID().toString(), h);
}
private ServiceSubscriber createAndStartNotificationTarget(
String link,
Function<Operation, Boolean> h) throws Throwable {
StatelessService notificationTarget = createNotificationTargetService(h);
// Start notification target (shared between subscriptions)
Operation startOp = Operation
.createPost(UriUtils.buildUri(this.host, link))
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer());
this.host.testStart(1);
this.host.startService(startOp, notificationTarget);
this.host.testWait();
ServiceSubscriber sr = new ServiceSubscriber();
sr.reference = notificationTarget.getUri();
return sr;
}
private StatelessService createNotificationTargetService(Function<Operation, Boolean> h) {
return new StatelessService() {
@Override
public void handleRequest(Operation update) {
if (!h.apply(update)) {
super.handleRequest(update);
}
}
};
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr) throws Throwable {
int expectedCompletions = uris.length;
if (sr.replayState) {
expectedCompletions *= 2;
}
subscribeToServices(uris, sr, expectedCompletions);
}
private void subscribeToServices(URI[] uris, ServiceSubscriber sr, int expectedCompletions) throws Throwable {
this.host.testStart(expectedCompletions);
for (int i = 0; i < uris.length; i++) {
subscribeToService(uris[i], sr);
}
this.host.testWait();
}
private void subscribeToService(URI uri, ServiceSubscriber sr) {
if (sr.usePublicUri) {
sr = Utils.clone(sr);
sr.reference = UriUtils.buildPublicUri(this.host, sr.reference.getPath());
}
URI subUri = UriUtils.buildSubscriptionUri(uri);
this.host.send(Operation.createPost(subUri)
.setCompletion(this.host.getCompletion())
.setReferer(this.host.getReferer())
.setBody(sr)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY));
}
private void unsubscribeFromChildren(URI[] uris, URI targetUri,
boolean useServiceHostStopSubscription) throws Throwable {
int count = uris.length;
TestContext ctx = testCreate(count);
for (int i = 0; i < count; i++) {
if (useServiceHostStopSubscription) {
// stop the subscriptions using the service host API
host.stopSubscriptionService(
Operation.createDelete(uris[i])
.setCompletion(ctx.getCompletion()),
targetUri);
continue;
}
ServiceSubscriber unsubscribeBody = new ServiceSubscriber();
unsubscribeBody.reference = targetUri;
URI subUri = UriUtils.buildSubscriptionUri(uris[i]);
this.host.send(Operation.createDelete(subUri)
.setCompletion(ctx.getCompletion())
.setBody(unsubscribeBody));
}
testWait(ctx);
}
private boolean verifySubscriberCount(URI[] uris, int subscriberCount) throws Throwable {
return verifySubscriberCount(true, uris, subscriberCount, null);
}
private boolean verifySubscriberCount(boolean wait, URI[] uris, int subscriberCount,
Long failedNotificationCount)
throws Throwable {
URI[] subUris = new URI[uris.length];
int i = 0;
for (URI u : uris) {
URI subUri = UriUtils.buildSubscriptionUri(u);
subUris[i++] = subUri;
}
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
boolean isConverged = true;
Map<URI, ServiceSubscriptionState> subStates = this.host.getServiceState(null,
ServiceSubscriptionState.class, subUris);
for (ServiceSubscriptionState state : subStates.values()) {
int expected = subscriberCount;
int actual = state.subscribers.size();
if (actual != expected) {
isConverged = false;
break;
}
if (failedNotificationCount == null) {
continue;
}
for (ServiceSubscriber sr : state.subscribers.values()) {
if (sr.failedNotificationCount == null && failedNotificationCount == 0) {
continue;
}
if (sr.failedNotificationCount == null
|| 0 != sr.failedNotificationCount.compareTo(failedNotificationCount)) {
isConverged = false;
break;
}
}
}
if (isConverged) {
return true;
}
if (!wait) {
return false;
}
Thread.sleep(250);
}
throw new TimeoutException("Subscriber count did not converge to " + subscriberCount);
}
private void patchChildren(URI[] uris, boolean expectFailure) throws Throwable {
int count = expectFailure ? uris.length : uris.length * 2;
long c = this.updateCount;
if (!expectFailure) {
count *= this.updateCount;
} else {
c = 1;
}
this.host.testStart(count);
for (int i = 0; i < uris.length; i++) {
for (int k = 0; k < c; k++) {
ExampleServiceState initialState = new ExampleServiceState();
initialState.counter = Long.MAX_VALUE;
Operation patch = Operation
.createPatch(uris[i])
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.send(patch);
}
}
this.host.testWait();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_3 |
crossvul-java_data_bad_3075_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
if (op.hasBody()) {
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (op.getAction()) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceDocument rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_0 |
crossvul-java_data_bad_3075_4 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.TimeBin;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.MinimalTestService;
public class TestUtilityService extends BasicReusableHostTestCase {
private List<Service> createServices(int count) throws Throwable {
List<Service> services = this.host.doThroughputServiceStart(
count, MinimalTestService.class,
this.host.buildMinimalTestState(),
null, null);
return services;
}
@Before
public void setUp() {
// We tell the verification host that we re-use it across test methods. This enforces
// the use of TestContext, to isolate test methods from each other.
// In this test class we host.testCreate(count) to get an isolated test context and
// then either wait on the context itself, or ask the convenience method host.testWait(ctx)
// to do it for us.
this.host.setSingleton(true);
}
@Test
public void patchConfiguration() throws Throwable {
int count = 10;
host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
// try config patch on a factory
ServiceConfigUpdateRequest updateBody = ServiceConfigUpdateRequest.create();
updateBody.removeOptions = EnumSet.of(ServiceOption.IDEMPOTENT_POST);
TestContext ctx = this.testCreate(1);
URI configUri = UriUtils.buildConfigUri(host, ExampleService.FACTORY_LINK);
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
this.testWait(ctx);
TestContext ctx2 = this.testCreate(1);
// verify option removed
this.host.send(Operation.createGet(configUri).setCompletion((o, e) -> {
if (e != null) {
ctx2.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (!cfg.options.contains(ServiceOption.IDEMPOTENT_POST)) {
ctx2.completeIteration();
} else {
ctx2.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
this.testWait(ctx2);
List<Service> services = createServices(count);
// verify no stats exist before we enable that capability
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(stats.isEmpty());
}
updateBody = ServiceConfigUpdateRequest.create();
updateBody.addOptions = EnumSet.of(ServiceOption.INSTRUMENTATION);
ctx = this.testCreate(services.size());
for (Service s : services) {
configUri = UriUtils.buildConfigUri(s.getUri());
this.host.send(Operation.createPatch(configUri).setBody(updateBody)
.setCompletion(ctx.getCompletion()));
}
this.testWait(ctx);
// get configuration and verify options
TestContext ctx3 = testCreate(services.size());
for (Service s : services) {
URI u = UriUtils.buildConfigUri(s.getUri());
host.send(Operation.createGet(u).setCompletion((o, e) -> {
if (e != null) {
ctx3.failIteration(e);
return;
}
ServiceConfiguration cfg = o.getBody(ServiceConfiguration.class);
if (cfg.options.contains(ServiceOption.INSTRUMENTATION)) {
ctx3.completeIteration();
} else {
ctx3.failIteration(new IllegalStateException(Utils.toJsonHtml(cfg)));
}
}));
}
testWait(ctx3);
ctx = testCreate(services.size());
// issue some updates so stats get updated
for (Service s : services) {
this.host.send(Operation.createPatch(s.getUri())
.setBody(this.host.buildMinimalTestState())
.setCompletion(ctx.getCompletion()));
}
testWait(ctx);
for (Service s : services) {
Map<String, ServiceStat> stats = this.host.getServiceStats(s.getUri());
assertTrue(stats != null);
assertTrue(!stats.isEmpty());
}
}
@Test
public void redirectToUiServiceIndex() throws Throwable {
// create an example child service and also verify it has a default UI html page
ExampleServiceState s = new ExampleServiceState();
s.name = UUID.randomUUID().toString();
s.documentSelfLink = s.name;
Operation post = Operation
.createPost(UriUtils.buildFactoryUri(this.host, ExampleService.class))
.setBody(s);
this.host.sendAndWaitExpectSuccess(post);
// do a get on examples/ui and examples/<uuid>/ui, twice to test the code path that caches
// the resource file lookup
for (int i = 0; i < 2; i++) {
Operation htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
htmlResponse = this.host.sendUIHttpRequest(
UriUtils.buildUri(
this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, s.name,
ServiceHost.SERVICE_URI_SUFFIX_UI))
.toString(), null, 1);
validateServiceUiHtmlResponse(htmlResponse);
}
}
@Test
public void testUtilityStats() throws Throwable {
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 2;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
stat.unit = "unit";
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 3 - POST a stat with the same key again and verify that the
// version and accumulated value are updated
stat.latestValue = 50;
stat.unit = "unit1";
Long updatedMicrosUtc1 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc1;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
// Step 4 - POST a stat with a new key and verify that the
// previously posted stat is not updated
stat.name = "key2";
stat.latestValue = 50;
stat.unit = "unit2";
Long updatedMicrosUtc2 = Utils.getNowMicrosUtc();
stat.sourceTimeMicrosUtc = updatedMicrosUtc2;
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 150);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 2);
assertTrue(retStatEntry.unit.equals("unit1"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc1);
retStatEntry = allStats.entries.get("key2");
assertTrue(retStatEntry.accumulatedValue == 50);
assertTrue(retStatEntry.latestValue == 50);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit2"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == updatedMicrosUtc2);
// Step 5 - Issue a PUT for the first stat key and verify that the doc state is replaced
stat.name = "key1";
stat.latestValue = 75;
stat.unit = "replaceUnit";
stat.sourceTimeMicrosUtc = null;
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key1");
assertTrue(retStatEntry.accumulatedValue == 75);
assertTrue(retStatEntry.latestValue == 75);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("replaceUnit"));
assertTrue(retStatEntry.sourceTimeMicrosUtc == null);
// Step 6 - Issue a bulk PUT and verify that the complete set of stats is updated
ServiceStats stats = new ServiceStats();
stat.name = "key3";
stat.latestValue = 200;
stat.unit = "unit3";
stats.entries.put("key3", stat);
this.host.sendAndWaitExpectSuccess(Operation.createPut(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stats));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
if (allStats.entries.size() != 1) {
// there is a possibility of node group maintenance kicking in and adding a stat
ServiceStat nodeGroupStat = allStats.entries.get(
Service.STAT_NAME_NODE_GROUP_CHANGE_MAINTENANCE_COUNT);
if (nodeGroupStat == null) {
throw new IllegalStateException(
"Expected single stat, got: " + Utils.toJsonHtml(allStats));
}
}
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.accumulatedValue == 200);
assertTrue(retStatEntry.latestValue == 200);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.unit.equals("unit3"));
// Step 7 - Issue a PATCH and verify that the latestValue is updated
stat.latestValue = 25;
this.host.sendAndWaitExpectSuccess(Operation.createPatch(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
allStats = this.host.getServiceState(null, ServiceStats.class, UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
retStatEntry = allStats.entries.get("key3");
assertTrue(retStatEntry.latestValue == 225);
assertTrue(retStatEntry.version == 2);
}
@Test
public void testTimeSeriesStats() throws Throwable {
long startTime = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
int numBins = 4;
long interval = 1000;
double value = 100;
// set data to fill up the specified number of bins
TimeSeriesStats timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.allOf(AggregationType.class));
for (int i = 0; i < numBins; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
// insert additional unique datapoints; the earliest entries should be dropped
for (int i = 0; i < numBins / 2; i++) {
startTime += TimeUnit.MILLISECONDS.toMicros(interval);
value += 1;
timeSeriesStats.add(startTime, value);
}
assertTrue(timeSeriesStats.bins.size() == numBins);
long timeMicros = startTime - TimeUnit.MILLISECONDS.toMicros(interval * (numBins - 1));
long timeMillis = TimeUnit.MICROSECONDS.toMillis(timeMicros);
timeMillis -= (timeMillis % interval);
assertTrue(timeSeriesStats.bins.firstKey() == timeMillis);
// insert additional datapoints for an existing bin. The count should increase,
// min, max, average computed appropriately
double origValue = value;
double accumulatedValue = value;
double newValue = value;
double count = 1;
for (int i = 0; i < numBins / 2; i++) {
newValue++;
count++;
timeSeriesStats.add(startTime, newValue);
accumulatedValue += newValue;
}
TimeBin lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg.equals(accumulatedValue / count));
assertTrue(lastBin.sum.equals(accumulatedValue));
assertTrue(lastBin.count == count);
assertTrue(lastBin.max.equals(newValue));
assertTrue(lastBin.min.equals(origValue));
// test with a subset of the aggregation types specified
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.AVG));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg != null);
assertTrue(lastBin.count != 0);
assertTrue(lastBin.max == null);
assertTrue(lastBin.min == null);
timeSeriesStats = new TimeSeriesStats(numBins, interval, EnumSet.of(AggregationType.MIN, AggregationType.MAX));
timeSeriesStats.add(startTime, value);
lastBin = timeSeriesStats.bins.get(timeSeriesStats.bins.lastKey());
assertTrue(lastBin.avg == null);
assertTrue(lastBin.count == 0);
assertTrue(lastBin.max != null);
assertTrue(lastBin.min != null);
// Step 2 - POST a stat to the service instance and verify we can fetch the stat just posted
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, bodySetter, factoryURI);
ExampleServiceState exampleServiceState = states.values().iterator().next();
ServiceStats.ServiceStat stat = new ServiceStat();
stat.name = "key1";
stat.latestValue = 100;
// set bin size to 1ms
stat.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
for (int i = 0; i < numBins; i++) {
Thread.sleep(1);
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink)).setBody(stat));
}
ServiceStats allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, exampleServiceState.documentSelfLink));
ServiceStat retStatEntry = allStats.entries.get(stat.name);
assertTrue(retStatEntry.accumulatedValue == 100 * (numBins + 1));
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == numBins + 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == numBins);
// Step 3 - POST a stat to the service instance with sourceTimeMicrosUtc and verify we can fetch the stat just posted
String statName = UUID.randomUUID().toString();
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = statName;
Consumer<Operation> setter = (o) -> {
o.setBody(exampleState);
};
Map<URI, ExampleServiceState> stateMap = this.host.doFactoryChildServiceStart(null, 1,
ExampleServiceState.class, setter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
ExampleServiceState returnExampleState = stateMap.values().iterator().next();
ServiceStats.ServiceStat sourceStat1 = new ServiceStat();
sourceStat1.name = "sourceKey1";
sourceStat1.latestValue = 100;
// Timestamp 946713600000000 equals Jan 1, 2000
Long sourceTimeMicrosUtc1 = 946713600000000L;
sourceStat1.sourceTimeMicrosUtc = sourceTimeMicrosUtc1;
ServiceStats.ServiceStat sourceStat2 = new ServiceStat();
sourceStat2.name = "sourceKey2";
sourceStat2.latestValue = 100;
// Timestamp 946713600000000 equals Jan 2, 2000
Long sourceTimeMicrosUtc2 = 946800000000000L;
sourceStat2.sourceTimeMicrosUtc = sourceTimeMicrosUtc2;
// set bucket size to 1ms
sourceStat1.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
sourceStat2.timeSeriesStats = new TimeSeriesStats(numBins, 1, EnumSet.allOf(AggregationType.class));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat1));
this.host.sendAndWaitExpectSuccess(Operation.createPost(UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink)).setBody(sourceStat2));
allStats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(
this.host, returnExampleState.documentSelfLink));
retStatEntry = allStats.entries.get(sourceStat1.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc1)));
retStatEntry = allStats.entries.get(sourceStat2.name);
assertTrue(retStatEntry.accumulatedValue == 100);
assertTrue(retStatEntry.latestValue == 100);
assertTrue(retStatEntry.version == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.size() == 1);
assertTrue(retStatEntry.timeSeriesStats.bins.firstKey()
.equals(TimeUnit.MICROSECONDS.toMillis(sourceTimeMicrosUtc2)));
}
public static class SetAvailableValidationService extends StatefulService {
public SetAvailableValidationService() {
super(ExampleServiceState.class);
}
@Override
public void handleStart(Operation op) {
setAvailable(false);
// we will transition to available only when we receive a special PATCH.
// This simulates a service that starts, but then self patch itself sometime
// later to indicate its done with some complex init. It does not do it in handle
// start, since it wants to make POST quick.
op.complete();
}
@Override
public void handlePatch(Operation op) {
// regardless of body, just become available
setAvailable(true);
op.complete();
}
}
@Test
public void failureOnReservedSuffixServiceStart() throws Throwable {
TestContext ctx = this.testCreate(ServiceHost.RESERVED_SERVICE_URI_PATHS.length);
for (String reservedSuffix : ServiceHost.RESERVED_SERVICE_URI_PATHS) {
Operation post = Operation.createPost(this.host,
UUID.randomUUID().toString() + "/" + reservedSuffix)
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(post, new MinimalTestService());
}
this.testWait(ctx);
}
@Test
public void testIsAvailableStatAndSuffix() throws Throwable {
long c = 1;
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
// first verify that service that do not explicitly use the setAvailable method,
// appear available. Both a factory and a child service
this.host.waitForServiceAvailable(factoryURI);
// expect 200 from /factory/<child>/available
TestContext ctx = testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getCompletion());
this.host.send(get);
}
testWait(ctx);
// verify that PUT on /available can make it switch to unavailable (503)
ServiceStat body = new ServiceStat();
body.name = Service.STAT_NAME_AVAILABLE;
body.latestValue = 0.0;
Operation put = Operation.createPut(
UriUtils.buildAvailableUri(this.host, factoryURI.getPath()))
.setBody(body);
this.host.sendAndWaitExpectSuccess(put);
// verify factory now appears unavailable
Operation get = Operation.createGet(UriUtils.buildAvailableUri(factoryURI));
this.host.sendAndWaitExpectFailure(get);
// verify PUT on child services makes them unavailable
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
put = put.clone().setUri(UriUtils.buildAvailableUri(u))
.setBody(body)
.setCompletion(ctx.getCompletion());
this.host.send(put);
}
testWait(ctx);
// expect 503 from /factory/<child>/available
ctx = testCreate(states.size());
for (URI u : states.keySet()) {
get = get.clone().setUri(UriUtils.buildAvailableUri(u))
.setCompletion(ctx.getExpectedFailureCompletion());
this.host.send(get);
}
testWait(ctx);
// now validate a stateful service that is in memory, and explicitly calls setAvailable
// sometime after it starts
Service service = this.host.startServiceAndWait(new SetAvailableValidationService(),
UUID.randomUUID().toString(), new ExampleServiceState());
// verify service is NOT available, since we have not yet poked it, to become available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectFailure(get);
// send a PATCH to this special test service, to make it switch to available
Operation patch = Operation.createPatch(service.getUri())
.setBody(new ExampleServiceState());
this.host.sendAndWaitExpectSuccess(patch);
// verify service now appears available
get = Operation.createGet(UriUtils.buildAvailableUri(service.getUri()));
this.host.sendAndWaitExpectSuccess(get);
}
public void validateServiceUiHtmlResponse(Operation op) {
assertTrue(op.getStatusCode() == Operation.STATUS_CODE_MOVED_TEMP);
assertTrue(op.getResponseHeader("Location").contains(
"/core/ui/default/#"));
}
public static void validateTimeSeriesStat(ServiceStat stat, long expectedBinDurationMillis) {
assertTrue(stat != null);
assertTrue(stat.timeSeriesStats != null);
assertTrue(stat.version > 1);
assertEquals(expectedBinDurationMillis, stat.timeSeriesStats.binDurationMillis);
double maxAvg = 0;
double countPerMaxAvgBin = 0;
for (TimeBin bin : stat.timeSeriesStats.bins.values()) {
if (bin.avg != null && bin.avg > maxAvg) {
maxAvg = bin.avg;
countPerMaxAvgBin = bin.count;
}
}
assertTrue(maxAvg > 0);
assertTrue(countPerMaxAvgBin >= 1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3075_4 |
crossvul-java_data_bad_3079_1 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.test.AuthorizationHelper;
import com.vmware.xenon.common.test.QueryTestUtils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.TestRequestSender.FailureResponse;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.AuthorizationCacheUtils;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.GuestUserService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Builder;
import com.vmware.xenon.services.common.RoleService.RoleState;
import com.vmware.xenon.services.common.SystemUserService;
import com.vmware.xenon.services.common.UserGroupService;
import com.vmware.xenon.services.common.UserGroupService.UserGroupState;
import com.vmware.xenon.services.common.UserService.UserState;
public class TestAuthorization extends BasicTestCase {
public static class AuthzStatelessService extends StatelessService {
public void handleRequest(Operation op) {
if (op.getAction() == Action.PATCH) {
op.complete();
return;
}
super.handleRequest(op);
}
}
public int serviceCount = 10;
private String userServicePath;
private AuthorizationHelper authHelper;
@Override
public void beforeHostStart(VerificationHost host) {
// Enable authorization service; this is an end to end test
host.setAuthorizationService(new AuthorizationContextService());
host.setAuthorizationEnabled(true);
CommandLineArgumentParser.parseFromProperties(this);
}
@Before
public void enableTracing() throws Throwable {
// Enable operation tracing to verify tracing does not error out with auth enabled.
this.host.toggleOperationTracing(this.host.getUri(), true);
}
@After
public void disableTracing() throws Throwable {
this.host.toggleOperationTracing(this.host.getUri(), false);
}
@Before
public void setupRoles() throws Throwable {
this.host.setSystemAuthorizationContext();
this.authHelper = new AuthorizationHelper(this.host);
this.userServicePath = this.authHelper.createUserService(this.host, "jane@doe.com");
this.authHelper.createRoles(this.host, "jane@doe.com");
this.host.resetAuthorizationContext();
}
@Test
public void statelessServiceAuthorization() throws Throwable {
// assume system identity so we can create roles
this.host.setSystemAuthorizationContext();
String serviceLink = UUID.randomUUID().toString();
// create a specific role for a stateless service
String resourceGroupLink = this.authHelper.createResourceGroup(this.host,
"stateless-service-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
UriUtils.URI_PATH_CHAR + serviceLink)
.build());
this.authHelper.createRole(this.host, this.authHelper.getUserGroupLink(),
resourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH, Action.DELETE)));
this.host.resetAuthorizationContext();
CompletionHandler ch = (o, e) -> {
if (e == null || o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
this.host.failIteration(new IllegalStateException(
"Operation did not fail with proper status code"));
return;
}
this.host.completeIteration();
};
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// Verify startService
Operation post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// stop service so we can attempt restart
this.host.testStart(1);
Operation delete = Operation.createDelete(post.getUri())
.setCompletion(this.host.getCompletion());
this.host.send(delete);
this.host.testWait();
// Verify DENY startService
this.host.resetAuthorizationContext();
this.host.testStart(1);
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
post.setCompletion(ch);
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// assume authorized user identity
this.host.assumeIdentity(this.userServicePath);
// restart service
post = Operation.createPost(UriUtils.buildUri(this.host, serviceLink));
// do not supply a body, authorization should still be applied
this.host.testStart(1);
post.setCompletion(this.host.getCompletion());
this.host.startService(post, new AuthzStatelessService());
this.host.testWait();
// Verify PATCH
Operation patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(this.host.getCompletion());
this.host.send(patch);
this.host.testWait();
// Verify DENY PATCH
this.host.resetAuthorizationContext();
patch = Operation.createPatch(UriUtils.buildUri(this.host, serviceLink));
patch.setBody(new ServiceDocument());
this.host.testStart(1);
patch.setCompletion(ch);
this.host.send(patch);
this.host.testWait();
}
@Test
public void queryTasksDirectAndContinuous() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
createExampleServices("jane");
// do a direct, simple query first
this.host.createAndWaitSimpleDirectQuery(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath, this.serviceCount, this.serviceCount);
// now do a paginated query to verify we can get to paged results with authz enabled
QueryTask qt = QueryTask.Builder.create().setResultLimit(this.serviceCount / 2)
.build();
qt.querySpec.query = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_AUTH_PRINCIPAL_LINK,
this.userServicePath)
.build();
URI taskUri = this.host.createQueryTaskService(qt);
this.host.waitFor("task not finished in time", () -> {
QueryTask r = this.host.getServiceState(null, QueryTask.class, taskUri);
if (TaskState.isFailed(r.taskInfo)) {
throw new IllegalStateException("task failed");
}
if (TaskState.isFinished(r.taskInfo)) {
qt.taskInfo = r.taskInfo;
qt.results = r.results;
return true;
}
return false;
});
TestContext ctx = this.host.testCreate(1);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, qt.results.nextPageLink))
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
if (e != null && o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("expected a failure"));
});
this.host.send(patchOp);
kryoCtx.await();
int requestCount = this.serviceCount;
TestContext notifyCtx = this.testCreate(requestCount);
Consumer<Operation> notify = (o) -> {
o.complete();
String subject = o.getAuthorizationContext().getClaims().getSubject();
if (!this.userServicePath.equals(subject)) {
notifyCtx.fail(new IllegalStateException(
"Invalid aith subject in notification: " + subject));
return;
}
this.host.log("Received authorized notification for index patch: %s", o.toString());
notifyCtx.complete();
};
Query q = Query.Builder.create()
.addKindFieldClause(ExampleServiceState.class)
.build();
QueryTask cqt = QueryTask.Builder.create().setQuery(q).build();
// do a continuous query, verify we receive some notifications
URI notifyURI = QueryTestUtils.startAndSubscribeToContinuousQuery(
this.host.getTestRequestSender(), this.host, cqt,
notify);
// issue updates, create some services
createExampleServices("jane");
this.host.log("Waiting on continiuous query task notifications (%d)", requestCount);
notifyCtx.await();
QueryTestUtils.stopContinuousQuerySubscription(
this.host.getTestRequestSender(), this.host, notifyURI,
cqt);
}
@Test
public void validateKryoOctetStreamRequests() throws Throwable {
Consumer<Boolean> validate = (expectUnauthorizedResponse) -> {
TestContext kryoCtx = this.host.testCreate(1);
Operation patchOp = Operation.createPatch(this.host, ExampleService.FACTORY_LINK + "/foo")
.setBody(new ServiceDocument())
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.setCompletion((o, e) -> {
boolean isUnauthorizedResponse = o.getStatusCode() == Operation.STATUS_CODE_UNAUTHORIZED;
if (expectUnauthorizedResponse == isUnauthorizedResponse) {
kryoCtx.completeIteration();
return;
}
kryoCtx.failIteration(new IllegalStateException("Response did not match expectation"));
});
this.host.send(patchOp);
kryoCtx.await();
};
// Validate GUEST users are not authorized for sending kryo-octet-stream requests.
this.host.resetAuthorizationContext();
validate.accept(true);
// Validate non-Guest, non-System users are also not authorized.
this.host.assumeIdentity(this.userServicePath);
validate.accept(true);
// Validate System users are allowed.
this.host.assumeIdentity(SystemUserService.SELF_LINK);
validate.accept(false);
}
@Test
public void contextPropagationOnScheduleAndRunContext() throws Throwable {
this.host.assumeIdentity(this.userServicePath);
AuthorizationContext callerAuthContext = OperationContext.getAuthorizationContext();
Runnable task = () -> {
if (OperationContext.getAuthorizationContext().equals(callerAuthContext)) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException("Incorrect auth context obtained"));
};
this.host.testStart(1);
this.host.schedule(task, 1, TimeUnit.MILLISECONDS);
this.host.testWait();
this.host.testStart(1);
this.host.run(task);
this.host.testWait();
}
@Test
public void guestAuthorization() throws Throwable {
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
// Create user group for guest user
String userGroupLink =
this.authHelper.createUserGroup(this.host, "guest-user-group", Builder.create()
.addFieldClause(
ServiceDocument.FIELD_NAME_SELF_LINK,
GuestUserService.SELF_LINK)
.build());
// Create resource group for example service state
String exampleServiceResourceGroupLink =
this.authHelper.createResourceGroup(this.host, "guest-resource-group", Builder.create()
.addFieldClause(
ExampleServiceState.FIELD_NAME_KIND,
Utils.buildKind(ExampleServiceState.class))
.addFieldClause(
ExampleServiceState.FIELD_NAME_NAME,
"guest")
.build());
// Create roles tying these together
this.authHelper.createRole(this.host, userGroupLink, exampleServiceResourceGroupLink,
new HashSet<>(Arrays.asList(Action.GET, Action.POST, Action.PATCH)));
// Create some example services; some accessible, some not
Map<URI, ExampleServiceState> exampleServices = new HashMap<>();
exampleServices.putAll(createExampleServices("jane"));
exampleServices.putAll(createExampleServices("guest"));
OperationContext.setAuthorizationContext(null);
TestRequestSender sender = this.host.getTestRequestSender();
Operation responseOp = sender.sendAndWait(Operation.createGet(this.host, ExampleService.FACTORY_LINK));
// Make sure only the authorized services were returned
ServiceDocumentQueryResult getResult = responseOp.getBody(ServiceDocumentQueryResult.class);
assertAuthorizedServicesInResult("guest", exampleServices, getResult);
String guestLink = getResult.documentLinks.iterator().next();
// Make sure we are able to PATCH the example service.
ExampleServiceState state = new ExampleServiceState();
state.counter = 2L;
responseOp = sender.sendAndWait(Operation.createPatch(this.host, guestLink).setBody(state));
assertEquals(Operation.STATUS_CODE_OK, responseOp.getStatusCode());
// Let's try to do another PATCH using kryo-octet-stream
state.counter = 3L;
FailureResponse failureResponse = sender.sendAndWaitFailure(
Operation.createPatch(this.host, guestLink)
.setContentType(Operation.MEDIA_TYPE_APPLICATION_KRYO_OCTET_STREAM)
.forceRemote()
.setBody(state));
assertEquals(Operation.STATUS_CODE_UNAUTHORIZED, failureResponse.op.getStatusCode());
}
@Test
public void actionBasedAuthorization() throws Throwable {
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
Map<URI, ExampleServiceState> exampleServices = createExampleServices("jane");
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// DELETE operation should be denied
Set<String> selfLinks = new HashSet<>(factoryGetResult[0].documentLinks);
for (String selfLink : selfLinks) {
Operation deleteOperation =
Operation.createDelete(UriUtils.buildUri(this.host, selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(deleteOperation);
this.host.testWait();
}
// PATCH operation should be allowed
for (String selfLink : selfLinks) {
Operation patchOperation =
Operation.createPatch(UriUtils.buildUri(this.host, selfLink))
.setBody(exampleServices.get(selfLink))
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(patchOperation);
this.host.testWait();
}
}
@Test
public void statefulServiceAuthorization() throws Throwable {
// Create example services not accessible by jane (as the system user)
OperationContext.setAuthorizationContext(this.host.getSystemAuthorizationContext());
Map<URI, ExampleServiceState> exampleServices = createExampleServices("john");
// try to create services with no user context set; we should get a 403
OperationContext.setAuthorizationContext(null);
ExampleServiceState state = createExampleServiceState("jane", new Long("100"));
this.host.testStart(1);
this.host.send(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(state)
.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// issue a GET on a factory with no auth context, no documents should be returned
this.host.testStart(1);
this.host.send(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(new IllegalStateException(e));
return;
}
ServiceDocumentQueryResult res = o
.getBody(ServiceDocumentQueryResult.class);
if (!res.documentLinks.isEmpty()) {
String message = String.format("Expected 0 results; Got %d",
res.documentLinks.size());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
}));
this.host.testWait();
// Assume Jane's identity
this.host.assumeIdentity(this.userServicePath);
// add docs accessible by jane
exampleServices.putAll(createExampleServices("jane"));
verifyJaneAccess(exampleServices, null);
// Execute get on factory trying to get all example services
final ServiceDocumentQueryResult[] factoryGetResult = new ServiceDocumentQueryResult[1];
Operation getFactory = Operation.createGet(
UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
factoryGetResult[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.send(getFactory);
this.host.testWait();
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, factoryGetResult[0]);
// Execute query task trying to get all example services
QueryTask.QuerySpecification q = new QueryTask.QuerySpecification();
q.query.setTermPropertyName(ServiceDocument.FIELD_NAME_KIND)
.setTermMatchValue(Utils.buildKind(ExampleServiceState.class));
URI u = this.host.createQueryTaskService(QueryTask.create(q));
QueryTask task = this.host.waitForQueryTaskCompletion(q, 1, 1, u, false, true, false);
assertEquals(TaskState.TaskStage.FINISHED, task.taskInfo.stage);
// Make sure only the authorized services were returned
assertAuthorizedServicesInResult("jane", exampleServices, task.results);
// reset the auth context
OperationContext.setAuthorizationContext(null);
// Assume Jane's identity through header auth token
String authToken = generateAuthToken(this.userServicePath);
verifyJaneAccess(exampleServices, authToken);
}
private AuthorizationContext assumeIdentityAndGetContext(String userLink,
Service privilegedService, boolean populateCache) throws Throwable {
AuthorizationContext authContext = this.host.assumeIdentity(userLink);
if (populateCache) {
this.host.sendAndWaitExpectSuccess(
Operation.createGet(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK)));
}
return this.host.getAuthorizationContext(privilegedService, authContext.getToken());
}
@Test
public void authCacheClearToken() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
AuthorizationContext authContext1 = assumeIdentityAndGetContext(fooUserLink, s, true);
AuthorizationContext authContext2 = assumeIdentityAndGetContext(fooUserLink, s, true);
assertNotNull(authContext1);
assertNotNull(authContext2);
this.host.setSystemAuthorizationContext();
Operation clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(this.host.getAuthorizationContext(s, authContext1.getToken()));
assertNull(this.host.getAuthorizationContext(s, authContext2.getToken()));
}
@Test
public void updateAuthzCache() throws Throwable {
ExecutorService executor = null;
try {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authsetupHelper = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String userLink = authsetupHelper.createUserService(this.host, email);
Query userGroupQuery = Query.Builder.create().addFieldClause(UserState.FIELD_NAME_EMAIL, email).build();
String userGroupLink = authsetupHelper.createUserGroup(this.host, email, userGroupQuery);
UserState patchState = new UserState();
patchState.userGroupLinks = Collections.singleton(userGroupLink);
this.host.sendAndWaitExpectSuccess(
Operation.createPatch(UriUtils.buildUri(this.host, userLink))
.setBody(patchState));
TestContext ctx = this.host.testCreate(this.serviceCount);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
executor = this.host.allocateExecutor(s);
this.host.resetSystemAuthorizationContext();
for (int i = 0; i < this.serviceCount; i++) {
this.host.run(executor, () -> {
String serviceName = UUID.randomUUID().toString();
try {
this.host.setSystemAuthorizationContext();
Query resourceQuery = Query.Builder.create().addFieldClause(ExampleServiceState.FIELD_NAME_NAME,
serviceName).build();
String resourceGroupLink = authsetupHelper.createResourceGroup(this.host, serviceName, resourceQuery);
authsetupHelper.createRole(this.host, userGroupLink, resourceGroupLink, EnumSet.allOf(Action.class));
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userLink);
ExampleServiceState exampleState = new ExampleServiceState();
exampleState.name = serviceName;
exampleState.documentSelfLink = serviceName;
// Issue: https://www.pivotaltracker.com/story/show/131520613
// We have a potential race condition in the code where the role
// created above is not being reflected in the auth context for
// the user; We are retrying the operation to mitigate the issue
// till we have a fix for the issue
for (int retryCounter = 0; retryCounter < 3; retryCounter++) {
try {
this.host.sendAndWaitExpectSuccess(
Operation.createPost(UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK))
.setBody(exampleState));
break;
} catch (Throwable t) {
this.host.log(Level.WARNING, "Error creating example service: " + t.getMessage());
if (retryCounter == 2) {
ctx.fail(new IllegalStateException("Example service creation failed thrice"));
return;
}
}
}
this.host.sendAndWaitExpectSuccess(
Operation.createDelete(UriUtils.buildUri(this.host,
UriUtils.buildUriPath(ExampleService.FACTORY_LINK, serviceName))));
ctx.complete();
} catch (Throwable e) {
this.host.log(Level.WARNING, e.getMessage());
ctx.fail(e);
}
});
}
this.host.testWait(ctx);
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
@Test
public void testAuthzUtils() throws Throwable {
this.host.setSystemAuthorizationContext();
AuthorizationHelper authHelperForFoo = new AuthorizationHelper(this.host);
String email = "foo@foo.com";
String fooUserLink = authHelperForFoo.createUserService(this.host, email);
UserState patchState = new UserState();
patchState.userGroupLinks = new HashSet<String>();
patchState.userGroupLinks.add(UriUtils.buildUriPath(
UserGroupService.FACTORY_LINK, authHelperForFoo.getUserGroupName(email)));
authHelperForFoo.patchUserService(this.host, fooUserLink, patchState);
// create a user group based on a query for userGroupLink
authHelperForFoo.createRoles(this.host, email, true);
// spin up a privileged service to query for auth context
MinimalTestService s = new MinimalTestService();
this.host.addPrivilegedService(MinimalTestService.class);
this.host.startServiceAndWait(s, UUID.randomUUID().toString(), null);
this.host.resetSystemAuthorizationContext();
String userGroupLink = authHelperForFoo.getUserGroupLink();
String resourceGroupLink = authHelperForFoo.getResourceGroupLink();
String roleLink = authHelperForFoo.getRoleLink();
// get the user group service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getUserGroupStateOp =
Operation.createGet(UriUtils.buildUri(this.host, userGroupLink));
Operation resultOp = this.host.waitForResponse(getUserGroupStateOp);
UserGroupState userGroupState = resultOp.getBody(UserGroupState.class);
Operation clearAuthOp = new Operation();
TestContext ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUserGroup(s, clearAuthOp, userGroupState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the resource group and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
clearAuthOp.setUri(UriUtils.buildUri(this.host, resourceGroupLink));
AuthorizationCacheUtils.clearAuthzCacheForResourceGroup(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// get the role service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
Operation getRoleStateOp =
Operation.createGet(UriUtils.buildUri(this.host, roleLink));
resultOp = this.host.waitForResponse(getRoleStateOp);
RoleState roleState = resultOp.getBody(RoleState.class);
clearAuthOp = new Operation();
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForRole(s, clearAuthOp, roleState);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
// finally, get the user service and clear the authz cache
assertNotNull(assumeIdentityAndGetContext(fooUserLink, s, true));
this.host.setSystemAuthorizationContext();
clearAuthOp = new Operation();
clearAuthOp.setUri(UriUtils.buildUri(this.host, fooUserLink));
ctx = this.host.testCreate(1);
clearAuthOp.setCompletion(ctx.getCompletion());
AuthorizationCacheUtils.clearAuthzCacheForUser(s, clearAuthOp);
clearAuthOp.complete();
this.host.testWait(ctx);
this.host.resetSystemAuthorizationContext();
assertNull(assumeIdentityAndGetContext(fooUserLink, s, false));
}
private void verifyJaneAccess(Map<URI, ExampleServiceState> exampleServices, String authToken) throws Throwable {
// Try to GET all example services
this.host.testStart(exampleServices.size());
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
Operation get = Operation.createGet(entry.getKey());
// force to create a remote context
if (authToken != null) {
get.forceRemote();
get.getRequestHeaders().put(Operation.REQUEST_AUTH_TOKEN_HEADER, authToken);
}
if (entry.getValue().name.equals("jane")) {
// Expect 200 OK
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_OK) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_OK,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
ExampleServiceState body = o.getBody(ExampleServiceState.class);
if (!body.documentAuthPrincipalLink.equals(this.userServicePath)) {
String message = String.format("Expected %s, got %s",
this.userServicePath, body.documentAuthPrincipalLink);
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
} else {
// Expect 403 Forbidden
get.setCompletion((o, e) -> {
if (o.getStatusCode() != Operation.STATUS_CODE_FORBIDDEN) {
String message = String.format("Expected %d, got %s",
Operation.STATUS_CODE_FORBIDDEN,
o.getStatusCode());
this.host.failIteration(new IllegalStateException(message));
return;
}
this.host.completeIteration();
});
}
this.host.send(get);
}
this.host.testWait();
}
private void assertAuthorizedServicesInResult(String name,
Map<URI, ExampleServiceState> exampleServices,
ServiceDocumentQueryResult result) {
Set<String> selfLinks = new HashSet<>(result.documentLinks);
for (Entry<URI, ExampleServiceState> entry : exampleServices.entrySet()) {
String selfLink = entry.getKey().getPath();
if (entry.getValue().name.equals(name)) {
assertTrue(selfLinks.contains(selfLink));
} else {
assertFalse(selfLinks.contains(selfLink));
}
}
}
private String generateAuthToken(String userServicePath) throws GeneralSecurityException {
Claims.Builder builder = new Claims.Builder();
builder.setSubject(userServicePath);
Claims claims = builder.getResult();
return this.host.getTokenSigner().sign(claims);
}
private ExampleServiceState createExampleServiceState(String name, Long counter) {
ExampleServiceState state = new ExampleServiceState();
state.name = name;
state.counter = counter;
state.documentAuthPrincipalLink = "stringtooverwrite";
return state;
}
private Map<URI, ExampleServiceState> createExampleServices(String userName) throws Throwable {
Collection<ExampleServiceState> bodies = new LinkedList<>();
for (int i = 0; i < this.serviceCount; i++) {
bodies.add(createExampleServiceState(userName, 1L));
}
Iterator<ExampleServiceState> it = bodies.iterator();
Consumer<Operation> bodySetter = (o) -> {
o.setBody(it.next());
};
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
bodies.size(),
ExampleServiceState.class,
bodySetter,
UriUtils.buildFactoryUri(this.host, ExampleService.class));
return states;
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/bad_3079_1 |
crossvul-java_data_good_3080_0 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static com.vmware.xenon.common.Service.Action.DELETE;
import static com.vmware.xenon.common.Service.Action.POST;
import java.io.NotActiveException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import com.vmware.xenon.common.Operation.AuthorizationContext;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Operation.OperationOption;
import com.vmware.xenon.common.ServiceDocumentDescription.TypeName;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceSubscriptionState.ServiceSubscriber;
import com.vmware.xenon.services.common.QueryTask;
import com.vmware.xenon.services.common.QueryTask.NumericRange;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.QueryTask.Query.Occurance;
import com.vmware.xenon.services.common.QueryTask.QueryTerm;
import com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiContentService;
/**
* Utility service managing the various URI control REST APIs for each service instance. A single
* utility service instance manages operations on multiple URI suffixes (/stats, /subscriptions,
* etc) in order to reduce runtime overhead per service instance
*/
public class UtilityService implements Service {
private transient Service parent;
private ServiceStats stats;
private ServiceSubscriptionState subscriptions;
private UiContentService uiService;
public UtilityService() {
}
public UtilityService setParent(Service parent) {
this.parent = parent;
return this;
}
@Override
public void authorizeRequest(Operation op) {
String suffix = UriUtils.buildUriPath(UriUtils.URI_PATH_CHAR, UriUtils.getLastPathSegment(op.getUri()));
// allow access to ui endpoint
if (ServiceHost.SERVICE_URI_SUFFIX_UI.equals(suffix)) {
op.complete();
return;
}
ServiceDocument doc = new ServiceDocument();
if (this.parent.getOptions().contains(ServiceOption.FACTORY_ITEM)) {
doc.documentSelfLink = UriUtils.buildUriPath(UriUtils.getParentPath(this.parent.getSelfLink()), suffix);
} else {
doc.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(), suffix);
}
doc.documentKind = Utils.buildKind(this.parent.getStateType());
if (getHost().isAuthorized(this.parent, doc, op)) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_FORBIDDEN);
}
@Override
public void handleRequest(Operation op) {
String uriPrefix = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
if (op.getUri().getPath().startsWith(uriPrefix)) {
// startsWith catches all /factory/instance/ui/some-script.js
handleUiRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_STATS)) {
handleStatsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_SUBSCRIPTIONS)) {
handleSubscriptionsRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_TEMPLATE)) {
handleDocumentTemplateRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_CONFIG)) {
this.parent.handleConfigurationRequest(op);
} else if (op.getUri().getPath().endsWith(ServiceHost.SERVICE_URI_SUFFIX_AVAILABLE)) {
handleAvailableRequest(op);
} else {
op.fail(new UnknownHostException());
}
}
@Override
public void handleCreate(Operation post) {
post.complete();
}
@Override
public void handleStart(Operation startPost) {
startPost.complete();
}
@Override
public void handleStop(Operation op) {
op.complete();
}
@Override
public void handleRequest(Operation op, OperationProcessingStage opProcessingStage) {
handleRequest(op);
}
private void handleAvailableRequest(Operation op) {
if (op.getAction() == Action.GET) {
if (this.parent.getProcessingStage() != ProcessingStage.PAUSED
&& this.parent.getProcessingStage() != ProcessingStage.AVAILABLE) {
// processing stage takes precedence over isAvailable statistic
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
return;
}
if (this.stats == null) {
op.complete();
return;
}
ServiceStat st = this.getStat(STAT_NAME_AVAILABLE, false);
if (st == null || st.latestValue == 1.0) {
op.complete();
return;
}
op.fail(Operation.STATUS_CODE_UNAVAILABLE);
} else if (op.getAction() == Action.PATCH || op.getAction() == Action.PUT) {
if (!op.hasBody()) {
op.fail(new IllegalArgumentException("body is required"));
return;
}
ServiceStat st = op.getBody(ServiceStat.class);
if (!STAT_NAME_AVAILABLE.equals(st.name)) {
op.fail(new IllegalArgumentException(
"body must be of type ServiceStat and name must be "
+ STAT_NAME_AVAILABLE));
return;
}
handleStatsRequest(op);
} else {
getHost().failRequestActionNotSupported(op);
}
}
private void handleSubscriptionsRequest(Operation op) {
synchronized (this) {
if (this.subscriptions == null) {
this.subscriptions = new ServiceSubscriptionState();
this.subscriptions.subscribers = new ConcurrentSkipListMap<>();
}
}
ServiceSubscriber body = null;
// validate and populate body for POST & DELETE
Action action = op.getAction();
if (action == POST || action == DELETE) {
if (!op.hasBody()) {
op.fail(new IllegalStateException("body is required"));
return;
}
body = op.getBody(ServiceSubscriber.class);
if (body.reference == null) {
op.fail(new IllegalArgumentException("reference is required"));
return;
}
}
switch (action) {
case POST:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.put(body.reference, body);
}
if (!body.replayState) {
break;
}
// if replayState is set, replay the current state to the subscriber
URI notificationURI = body.reference;
this.parent.sendRequest(Operation.createGet(this, this.parent.getSelfLink())
.setCompletion(
(o, e) -> {
if (e != null) {
op.fail(new IllegalStateException(
"Unable to get current state"));
return;
}
Operation putOp = Operation
.createPut(notificationURI)
.setBodyNoCloning(o.getBody(this.parent.getStateType()))
.addPragmaDirective(
Operation.PRAGMA_DIRECTIVE_NOTIFICATION)
.setReferer(getUri());
this.parent.sendRequest(putOp);
}));
break;
case DELETE:
// synchronize to avoid concurrent modification during serialization for GET
synchronized (this.subscriptions) {
this.subscriptions.subscribers.remove(body.reference);
}
break;
case GET:
ServiceDocument rsp;
synchronized (this.subscriptions) {
rsp = Utils.clone(this.subscriptions);
}
op.setBody(rsp);
break;
default:
op.fail(new NotActiveException());
break;
}
op.complete();
}
public boolean hasSubscribers() {
ServiceSubscriptionState subscriptions = this.subscriptions;
return subscriptions != null
&& subscriptions.subscribers != null
&& !subscriptions.subscribers.isEmpty();
}
public boolean hasStats() {
ServiceStats stats = this.stats;
return stats != null && stats.entries != null && !stats.entries.isEmpty();
}
public void notifySubscribers(Operation op) {
try {
if (op.getAction() == Action.GET) {
return;
}
if (!this.hasSubscribers()) {
return;
}
long now = Utils.getNowMicrosUtc();
Operation clone = op.clone();
clone.toggleOption(OperationOption.REMOTE, false);
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NOTIFICATION);
for (Entry<URI, ServiceSubscriber> e : this.subscriptions.subscribers.entrySet()) {
ServiceSubscriber s = e.getValue();
notifySubscriber(now, clone, s);
}
if (!performSubscriptionsMaintenance(now)) {
return;
}
} catch (Throwable e) {
this.parent.getHost().log(Level.WARNING,
"Uncaught exception notifying subscribers for %s: %s",
this.parent.getSelfLink(), Utils.toString(e));
}
}
private void notifySubscriber(long now, Operation clone, ServiceSubscriber s) {
synchronized (s) {
if (s.failedNotificationCount != null) {
// indicate to the subscriber that they missed notifications and should retrieve latest state
clone.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_SKIPPED_NOTIFICATIONS);
}
}
CompletionHandler c = (o, ex) -> {
s.documentUpdateTimeMicros = Utils.getNowMicrosUtc();
synchronized (s) {
if (ex != null) {
if (s.failedNotificationCount == null) {
s.failedNotificationCount = 0L;
s.initialFailedNotificationTimeMicros = now;
}
s.failedNotificationCount++;
return;
}
if (s.failedNotificationCount != null) {
// the subscriber is available again.
s.failedNotificationCount = null;
s.initialFailedNotificationTimeMicros = null;
}
}
};
this.parent.sendRequest(clone.setUri(s.reference).setCompletion(c));
}
private boolean performSubscriptionsMaintenance(long now) {
List<URI> subscribersToDelete = null;
synchronized (this) {
if (this.subscriptions == null) {
return false;
}
Iterator<Entry<URI, ServiceSubscriber>> it = this.subscriptions.subscribers.entrySet()
.iterator();
while (it.hasNext()) {
Entry<URI, ServiceSubscriber> e = it.next();
ServiceSubscriber s = e.getValue();
boolean remove = false;
synchronized (s) {
if (s.documentExpirationTimeMicros != 0 && s.documentExpirationTimeMicros < now) {
remove = true;
} else if (s.notificationLimit != null) {
if (s.notificationCount == null) {
s.notificationCount = 0L;
}
if (++s.notificationCount >= s.notificationLimit) {
remove = true;
}
} else if (s.failedNotificationCount != null
&& s.failedNotificationCount > ServiceSubscriber.NOTIFICATION_FAILURE_LIMIT) {
if (now - s.initialFailedNotificationTimeMicros > getHost()
.getMaintenanceIntervalMicros()) {
getHost().log(Level.INFO,
"removing subscriber, failed notifications: %d",
s.failedNotificationCount);
remove = true;
}
}
}
if (!remove) {
continue;
}
it.remove();
if (subscribersToDelete == null) {
subscribersToDelete = new ArrayList<>();
}
subscribersToDelete.add(s.reference);
continue;
}
}
if (subscribersToDelete != null) {
for (URI subscriber : subscribersToDelete) {
this.parent.sendRequest(Operation.createDelete(subscriber));
}
}
return true;
}
private void handleUiRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new IllegalArgumentException("Action not supported"));
return;
}
if (!this.parent.hasOption(ServiceOption.HTML_USER_INTERFACE)) {
String servicePath = UriUtils.buildUriPath(ServiceUriPaths.UI_SERVICE_BASE_URL, op
.getUri().getPath());
String defaultHtmlPath = UriUtils.buildUriPath(servicePath.substring(0,
servicePath.length() - ServiceUriPaths.UI_PATH_SUFFIX.length()),
ServiceUriPaths.UI_SERVICE_HOME);
redirectGetToHtmlUiResource(op, defaultHtmlPath);
return;
}
if (this.uiService == null) {
this.uiService = new UiContentService() {
};
this.uiService.setHost(this.parent.getHost());
}
// simulate a full service deployed at the utility endpoint /service/ui
String selfLink = this.parent.getSelfLink() + ServiceHost.SERVICE_URI_SUFFIX_UI;
this.uiService.handleUiGet(selfLink, this.parent, op);
}
public void redirectGetToHtmlUiResource(Operation op, String htmlResourcePath) {
// redirect using relative url without host:port
// not so much optimization as handling the case of port forwarding/containers
try {
op.addResponseHeader(Operation.LOCATION_HEADER,
URLDecoder.decode(htmlResourcePath, Utils.CHARSET));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e);
}
op.setStatusCode(Operation.STATUS_CODE_MOVED_TEMP);
op.complete();
}
private void handleStatsRequest(Operation op) {
switch (op.getAction()) {
case PUT:
ServiceStats.ServiceStat stat = op
.getBody(ServiceStats.ServiceStat.class);
if (stat.kind == null) {
op.fail(new IllegalArgumentException("kind is required"));
return;
}
if (stat.kind.equals(ServiceStats.ServiceStat.KIND)) {
if (stat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
replaceSingleStat(stat);
} else if (stat.kind.equals(ServiceStats.KIND)) {
ServiceStats stats = op.getBody(ServiceStats.class);
if (stats.entries == null || stats.entries.isEmpty()) {
op.fail(new IllegalArgumentException("stats entries need to be defined"));
return;
}
replaceAllStats(stats);
} else {
op.fail(new IllegalArgumentException("operation not supported for kind"));
return;
}
op.complete();
break;
case POST:
ServiceStats.ServiceStat newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// create a stat object if one does not exist
ServiceStats.ServiceStat existingStat = this.getStat(newStat.name);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat does not exist"));
return;
}
initializeOrSetStat(existingStat, newStat);
op.complete();
break;
case DELETE:
// TODO support removing stats externally - do we need this?
op.fail(new NotActiveException());
break;
case PATCH:
newStat = op.getBody(ServiceStats.ServiceStat.class);
if (newStat.name == null) {
op.fail(new IllegalArgumentException("stat name is required"));
return;
}
// if an existing stat by this name exists, adjust the stat value, else this is a no-op
existingStat = this.getStat(newStat.name, false);
if (existingStat == null) {
op.fail(new IllegalArgumentException("stat to patch does not exist"));
return;
}
adjustStat(existingStat, newStat.latestValue);
op.complete();
break;
case GET:
if (this.stats == null) {
ServiceStats s = new ServiceStats();
populateDocumentProperties(s);
op.setBody(s).complete();
} else {
ServiceStats rsp;
synchronized (this.stats) {
rsp = populateDocumentProperties(this.stats);
rsp = Utils.clone(rsp);
}
if (handleStatsGetWithODataRequest(op, rsp)) {
return;
}
op.setBodyNoCloning(rsp);
op.complete();
}
break;
default:
op.fail(new NotActiveException());
break;
}
}
/**
* Selects statistics entries that satisfy a simple sub set of ODATA filter expressions
*/
private boolean handleStatsGetWithODataRequest(Operation op, ServiceStats rsp) {
if (UriUtils.getODataCountParamValue(op.getUri())) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_COUNT + " is not supported"));
return true;
}
if (UriUtils.getODataOrderByParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_ORDER_BY + " is not supported"));
return true;
}
if (UriUtils.getODataSkipToParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_SKIP_TO + " is not supported"));
return true;
}
if (UriUtils.getODataTopParamValue(op.getUri()) != null) {
op.fail(new IllegalArgumentException(
UriUtils.URI_PARAM_ODATA_TOP + " is not supported"));
return true;
}
if (UriUtils.getODataFilterParamValue(op.getUri()) == null) {
return false;
}
QueryTask task = ODataUtils.toQuery(op, false, null);
if (task == null || task.querySpec.query == null) {
return false;
}
List<Query> clauses = task.querySpec.query.booleanClauses;
if (clauses == null || clauses.size() == 0) {
clauses = new ArrayList<Query>();
if (task.querySpec.query.term == null) {
return false;
}
clauses.add(task.querySpec.query);
}
return processStatsODataQueryClauses(op, rsp, clauses);
}
private boolean processStatsODataQueryClauses(Operation op, ServiceStats rsp,
List<Query> clauses) {
for (Query q : clauses) {
if (!Occurance.MUST_OCCUR.equals(q.occurance)) {
op.fail(new IllegalArgumentException("only AND expressions are supported"));
return true;
}
QueryTerm term = q.term;
if (term == null) {
return processStatsODataQueryClauses(op, rsp, q.booleanClauses);
}
// prune entries using the filter match value and property
Iterator<Entry<String, ServiceStat>> statIt = rsp.entries.entrySet().iterator();
while (statIt.hasNext()) {
Entry<String, ServiceStat> e = statIt.next();
if (ServiceStat.FIELD_NAME_NAME.equals(term.propertyName)) {
// match against the name property which is the also the key for the
// entry table
if (term.matchType.equals(MatchType.TERM)
&& e.getKey().equals(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.PREFIX)
&& e.getKey().startsWith(term.matchValue)) {
continue;
}
if (term.matchType.equals(MatchType.WILDCARD)) {
// we only support two types of wild card queries:
// *something or something*
if (term.matchValue.endsWith(UriUtils.URI_WILDCARD_CHAR)) {
// prefix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().startsWith(mv)) {
continue;
}
} else if (term.matchValue.startsWith(UriUtils.URI_WILDCARD_CHAR)) {
// suffix match
String mv = term.matchValue.replace(UriUtils.URI_WILDCARD_CHAR, "");
if (e.getKey().endsWith(mv)) {
continue;
}
}
}
} else if (ServiceStat.FIELD_NAME_LATEST_VALUE.equals(term.propertyName)) {
// support numeric range queries on latest value
if (term.range == null || term.range.type != TypeName.DOUBLE) {
op.fail(new IllegalArgumentException(
ServiceStat.FIELD_NAME_LATEST_VALUE
+ "requires double numeric range"));
return true;
}
@SuppressWarnings("unchecked")
NumericRange<Double> nr = (NumericRange<Double>) term.range;
ServiceStat st = e.getValue();
boolean withinMax = nr.isMaxInclusive && st.latestValue <= nr.max ||
st.latestValue < nr.max;
boolean withinMin = nr.isMinInclusive && st.latestValue >= nr.min ||
st.latestValue > nr.min;
if (withinMin && withinMax) {
continue;
}
}
statIt.remove();
}
}
return false;
}
private ServiceStats populateDocumentProperties(ServiceStats stats) {
ServiceStats clone = new ServiceStats();
clone.entries = stats.entries;
clone.documentUpdateTimeMicros = stats.documentUpdateTimeMicros;
clone.documentSelfLink = UriUtils.buildUriPath(this.parent.getSelfLink(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
clone.documentOwner = getHost().getId();
clone.documentKind = Utils.buildKind(ServiceStats.class);
return clone;
}
private void handleDocumentTemplateRequest(Operation op) {
if (op.getAction() != Action.GET) {
op.fail(new NotActiveException());
return;
}
ServiceDocument template = this.parent.getDocumentTemplate();
String serializedTemplate = Utils.toJsonHtml(template);
op.setBody(serializedTemplate).complete();
}
@Override
public void handleConfigurationRequest(Operation op) {
this.parent.handleConfigurationRequest(op);
}
public void handlePatchConfiguration(Operation op, ServiceConfigUpdateRequest updateBody) {
if (updateBody == null) {
updateBody = op.getBody(ServiceConfigUpdateRequest.class);
}
if (!ServiceConfigUpdateRequest.KIND.equals(updateBody.kind)) {
op.fail(new IllegalArgumentException("Unrecognized kind: " + updateBody.kind));
return;
}
if (updateBody.maintenanceIntervalMicros == null
&& updateBody.operationQueueLimit == null
&& updateBody.epoch == null
&& (updateBody.addOptions == null || updateBody.addOptions.isEmpty())
&& (updateBody.removeOptions == null || updateBody.removeOptions
.isEmpty())
&& updateBody.versionRetentionLimit == null) {
op.fail(new IllegalArgumentException(
"At least one configuraton field must be specified"));
return;
}
if (updateBody.versionRetentionLimit != null) {
// Fail the request for immutable service as it is not allowed to change the version
// retention.
if (this.parent.getOptions().contains(ServiceOption.IMMUTABLE)) {
op.fail(new IllegalArgumentException(String.format(
"Service %s has option %s, retention limit cannot be modified",
this.parent.getSelfLink(), ServiceOption.IMMUTABLE)));
return;
}
ServiceDocumentDescription serviceDocumentDescription = this.parent
.getDocumentTemplate().documentDescription;
serviceDocumentDescription.versionRetentionLimit = updateBody.versionRetentionLimit;
if (updateBody.versionRetentionFloor != null) {
serviceDocumentDescription.versionRetentionFloor = updateBody.versionRetentionFloor;
} else {
serviceDocumentDescription.versionRetentionFloor =
updateBody.versionRetentionLimit / 2;
}
}
// service might fail a capability toggle if the capability can not be changed after start
if (updateBody.addOptions != null) {
for (ServiceOption c : updateBody.addOptions) {
this.parent.toggleOption(c, true);
}
}
if (updateBody.removeOptions != null) {
for (ServiceOption c : updateBody.removeOptions) {
this.parent.toggleOption(c, false);
}
}
if (updateBody.maintenanceIntervalMicros != null) {
this.parent.setMaintenanceIntervalMicros(updateBody.maintenanceIntervalMicros);
}
op.complete();
}
private void initializeOrSetStat(ServiceStat stat, ServiceStat newValue) {
synchronized (stat) {
if (stat.timeSeriesStats == null && newValue.timeSeriesStats != null) {
stat.timeSeriesStats = new TimeSeriesStats(newValue.timeSeriesStats.numBins,
newValue.timeSeriesStats.binDurationMillis, newValue.timeSeriesStats.aggregationType);
}
stat.unit = newValue.unit;
stat.sourceTimeMicrosUtc = newValue.sourceTimeMicrosUtc;
setStat(stat, newValue.latestValue);
}
}
@Override
public void setStat(ServiceStat stat, double newValue) {
allocateStats();
findStat(stat.name, true, stat);
synchronized (stat) {
stat.version++;
stat.accumulatedValue += newValue;
stat.latestValue = newValue;
if (stat.logHistogram != null) {
int binIndex = 0;
if (newValue > 0.0) {
binIndex = (int) Math.log10(newValue);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, newValue, newValue);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, newValue, newValue);
}
}
}
}
@Override
public void adjustStat(ServiceStat stat, double delta) {
allocateStats();
synchronized (stat) {
stat.latestValue += delta;
stat.version++;
if (stat.logHistogram != null) {
int binIndex = 0;
if (delta > 0.0) {
binIndex = (int) Math.log10(delta);
}
if (binIndex >= 0 && binIndex < stat.logHistogram.bins.length) {
stat.logHistogram.bins[binIndex]++;
}
}
stat.lastUpdateMicrosUtc = Utils.getNowMicrosUtc();
if (stat.timeSeriesStats != null) {
if (stat.sourceTimeMicrosUtc != null) {
stat.timeSeriesStats.add(stat.sourceTimeMicrosUtc, stat.latestValue, delta);
} else {
stat.timeSeriesStats.add(stat.lastUpdateMicrosUtc, stat.latestValue, delta);
}
}
}
}
@Override
public ServiceStat getStat(String name) {
return getStat(name, true);
}
private ServiceStat getStat(String name, boolean create) {
if (!allocateStats(true)) {
return null;
}
return findStat(name, create, null);
}
private void replaceSingleStat(ServiceStat stat) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// create a new stat with the default values
ServiceStat newStat = new ServiceStat();
newStat.name = stat.name;
initializeOrSetStat(newStat, stat);
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
// add it to the list of stats for this service
this.stats.entries.put(stat.name, newStat);
}
}
private void replaceAllStats(ServiceStats newStats) {
if (!allocateStats(true)) {
return;
}
synchronized (this.stats) {
// reset the current set of stats
this.stats.entries.clear();
for (ServiceStats.ServiceStat currentStat : newStats.entries.values()) {
replaceSingleStat(currentStat);
}
}
}
private ServiceStat findStat(String name, boolean create, ServiceStat initialStat) {
synchronized (this.stats) {
if (this.stats.entries == null) {
this.stats.entries = new HashMap<>();
}
ServiceStat st = this.stats.entries.get(name);
if (st == null && create) {
st = initialStat != null ? initialStat : new ServiceStat();
st.name = name;
this.stats.entries.put(name, st);
}
if (create && st != null && initialStat != null) {
// if the statistic already exists make sure it has the same features
// as the statistic we are trying to create
if (st.timeSeriesStats == null && initialStat.timeSeriesStats != null) {
st.timeSeriesStats = initialStat.timeSeriesStats;
}
if (st.logHistogram == null && initialStat.logHistogram != null) {
st.logHistogram = initialStat.logHistogram;
}
}
return st;
}
}
private void allocateStats() {
allocateStats(true);
}
private synchronized boolean allocateStats(boolean mustAllocate) {
if (!mustAllocate && this.stats == null) {
return false;
}
if (this.stats != null) {
return true;
}
this.stats = new ServiceStats();
return true;
}
@Override
public ServiceHost getHost() {
return this.parent.getHost();
}
@Override
public String getSelfLink() {
return null;
}
@Override
public URI getUri() {
return null;
}
@Override
public OperationProcessingChain getOperationProcessingChain() {
return null;
}
@Override
public ProcessingStage getProcessingStage() {
return ProcessingStage.AVAILABLE;
}
@Override
public EnumSet<ServiceOption> getOptions() {
return EnumSet.of(ServiceOption.UTILITY);
}
@Override
public boolean hasOption(ServiceOption cap) {
return false;
}
@Override
public void toggleOption(ServiceOption cap, boolean enable) {
throw new RuntimeException();
}
@Override
public void adjustStat(String name, double delta) {
return;
}
@Override
public void setStat(String name, double newValue) {
return;
}
@Override
public void handleMaintenance(Operation post) {
post.complete();
}
@Override
public void setHost(ServiceHost serviceHost) {
}
@Override
public void setSelfLink(String path) {
}
@Override
public void setOperationProcessingChain(OperationProcessingChain opProcessingChain) {
}
@Override
public ServiceRuntimeContext setProcessingStage(ProcessingStage initialized) {
return null;
}
@Override
public ServiceDocument setInitialState(Object state, Long initialVersion) {
return null;
}
@Override
public Service getUtilityService(String uriPath) {
return null;
}
@Override
public boolean queueRequest(Operation op) {
return false;
}
@Override
public void sendRequest(Operation op) {
throw new RuntimeException();
}
@Override
public ServiceDocument getDocumentTemplate() {
return null;
}
@Override
public void setPeerNodeSelectorPath(String uriPath) {
}
@Override
public String getPeerNodeSelectorPath() {
return null;
}
@Override
public void setState(Operation op, ServiceDocument newState) {
op.linkState(newState);
}
@SuppressWarnings("unchecked")
@Override
public <T extends ServiceDocument> T getState(Operation op) {
return (T) op.getLinkedState();
}
@Override
public void setMaintenanceIntervalMicros(long micros) {
throw new RuntimeException("not implemented");
}
@Override
public long getMaintenanceIntervalMicros() {
return 0;
}
@Override
public Operation dequeueRequest() {
return null;
}
@Override
public Class<? extends ServiceDocument> getStateType() {
return null;
}
@Override
public final void setAuthorizationContext(Operation op, AuthorizationContext ctx) {
throw new RuntimeException("Service not allowed to set authorization context");
}
@Override
public final AuthorizationContext getSystemAuthorizationContext() {
throw new RuntimeException("Service not allowed to get system authorization context");
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3080_0 |
crossvul-java_data_good_3081_3 | /*
* Copyright (c) 2014-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, without warranties or
* conditions of any kind, EITHER EXPRESS OR IMPLIED. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.vmware.xenon.common;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.logging.Level;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.vmware.xenon.common.Operation.CompletionHandler;
import com.vmware.xenon.common.Service.Action;
import com.vmware.xenon.common.Service.ProcessingStage;
import com.vmware.xenon.common.Service.ServiceOption;
import com.vmware.xenon.common.ServiceHost.RequestRateInfo;
import com.vmware.xenon.common.ServiceHost.ServiceAlreadyStartedException;
import com.vmware.xenon.common.ServiceHost.ServiceHostState;
import com.vmware.xenon.common.ServiceHost.ServiceHostState.MemoryLimitType;
import com.vmware.xenon.common.ServiceStats.ServiceStat;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats;
import com.vmware.xenon.common.ServiceStats.TimeSeriesStats.AggregationType;
import com.vmware.xenon.common.jwt.Rfc7519Claims;
import com.vmware.xenon.common.jwt.Signer;
import com.vmware.xenon.common.jwt.Verifier;
import com.vmware.xenon.common.test.AuthTestUtils;
import com.vmware.xenon.common.test.MinimalTestServiceState;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestProperty;
import com.vmware.xenon.common.test.TestRequestSender;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.common.test.VerificationHost.WaitHandler;
import com.vmware.xenon.services.common.AuthorizationContextService;
import com.vmware.xenon.services.common.ExampleService;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;
import com.vmware.xenon.services.common.ExampleServiceHost;
import com.vmware.xenon.services.common.FileContentService;
import com.vmware.xenon.services.common.LuceneDocumentIndexService;
import com.vmware.xenon.services.common.MinimalFactoryTestService;
import com.vmware.xenon.services.common.MinimalTestService;
import com.vmware.xenon.services.common.NodeGroupService.NodeGroupState;
import com.vmware.xenon.services.common.NodeState;
import com.vmware.xenon.services.common.OnDemandLoadFactoryService;
import com.vmware.xenon.services.common.QueryTask.Query;
import com.vmware.xenon.services.common.ServiceContextIndexService;
import com.vmware.xenon.services.common.ServiceHostLogService.LogServiceState;
import com.vmware.xenon.services.common.ServiceHostManagementService;
import com.vmware.xenon.services.common.ServiceUriPaths;
import com.vmware.xenon.services.common.UiFileContentService;
import com.vmware.xenon.services.common.UserService;
public class TestServiceHost {
public static class AuthCheckService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/auth-check-services";
static final String IS_AUTHORIZE_REQUEST_CALLED = "isAuthorizeRequestCalled";
public static FactoryService createFactory() {
return FactoryService.create(AuthCheckService.class);
}
public AuthCheckService() {
super();
// non persisted, owner selection service
toggleOption(ServiceOption.PERSISTENCE, false);
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public void authorizeRequest(Operation op) {
adjustStat(IS_AUTHORIZE_REQUEST_CALLED, 1);
op.complete();
}
}
private static final int MAINTENANCE_INTERVAL_MILLIS = 100;
private VerificationHost host;
public String testURI;
public int requestCount = 1000;
public int rateLimitedRequestCount = 10;
public int connectionCount = 32;
public long serviceCount = 10;
public int iterationCount = 1;
public long testDurationSeconds = 0;
public int indexFileThreshold = 100;
public long serviceCacheClearDelaySeconds = 2;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
public void beforeHostStart(VerificationHost host) {
host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS
.toMicros(MAINTENANCE_INTERVAL_MILLIS));
}
private void setUp(boolean initOnly) throws Exception {
CommandLineArgumentParser.parseFromProperties(this);
this.host = VerificationHost.create(0);
CommandLineArgumentParser.parseFromProperties(this.host);
if (initOnly) {
return;
}
try {
this.host.start();
} catch (Throwable e) {
throw new Exception(e);
}
}
@Test
public void allocateExecutor() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
ExecutorService exec = this.host.allocateExecutor(s);
this.host.testStart(1);
exec.execute(() -> {
this.host.completeIteration();
});
this.host.testWait();
}
@Test
public void operationTracingFineFiner() throws Throwable {
setUp(false);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, true);
// send some requests and confirm stats get populated
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
TestContext ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u)
.setContextId(this.host.nextUUID())
.setBody(state).setCompletion(ctx.getCompletion()));
}
ctx.await();
ServiceStats after = sender.sendStatsGetAndWait(this.host.getManagementServiceUri());
for (URI u : states.keySet()) {
String getStatName = u.getPath() + ":" + Action.GET;
String patchStatName = u.getPath() + ":" + Action.PATCH;
ServiceStat getStat = after.entries.get(getStatName);
assertTrue(getStat != null && getStat.latestValue > 0);
ServiceStat patchStat = after.entries.get(patchStatName);
assertTrue(patchStat != null && getStat.latestValue > 0);
}
this.host.toggleOperationTracing(this.host.getUri(), Level.FINE, false);
// toggle on again, to FINER, confirm we get some log output
this.host.toggleOperationTracing(this.host.getUri(), Level.FINER, true);
// send some operations
ctx = this.host.testCreate(states.size() * 2);
for (URI u : states.keySet()) {
ExampleServiceState state = new ExampleServiceState();
state.name = this.host.nextUUID();
sender.sendRequest(Operation.createGet(u).setCompletion(ctx.getCompletion()));
sender.sendRequest(
Operation.createPatch(u).setContextId(this.host.nextUUID()).setBody(state)
.setCompletion(ctx.getCompletion()));
}
ctx.await();
LogServiceState logsAfterFiner = sender.sendGetAndWait(
UriUtils.buildUri(this.host, ServiceUriPaths.PROCESS_LOG),
LogServiceState.class);
boolean foundTrace = false;
for (String line : logsAfterFiner.items) {
for (URI u : states.keySet()) {
if (line.contains(u.getPath())) {
foundTrace = true;
break;
}
}
}
assertTrue(foundTrace);
}
@Test
public void buildDocumentDescription() throws Throwable {
setUp(false);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = "foo";
op.setBody(st);
}, factoryUri);
// verify we have valid descriptions for all example services we created
// explicitly
validateDescriptions(states);
// verify we can recover a description, even for services that are stopped
TestContext ctx = this.host.testCreate(states.size());
for (URI childUri : states.keySet()) {
Operation delete = Operation.createDelete(childUri)
.setCompletion(ctx.getCompletion());
this.host.send(delete);
}
this.host.testWait(ctx);
// do the description lookup again, on stopped services
validateDescriptions(states);
}
private void validateDescriptions(Map<URI, ExampleServiceState> states) {
for (URI childUri : states.keySet()) {
ServiceDocumentDescription desc = this.host
.buildDocumentDescription(childUri.getPath());
// do simple verification of returned description, its not exhaustive
assertTrue(desc != null);
assertTrue(desc.serviceCapabilities.contains(ServiceOption.PERSISTENCE));
assertTrue(desc.serviceCapabilities.contains(ServiceOption.INSTRUMENTATION));
assertTrue(desc.propertyDescriptions.size() > 1);
}
}
@Test
public void requestRateLimits() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
doRequestRateLimits();
tearDown();
}
}
private void doRequestRateLimits() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
this.host.setSystemAuthorizationContext();
String userPath = UriUtils.buildUriPath(ServiceUriPaths.CORE_AUTHZ_USERS, "example-user");
String exampleUser = "example@localhost";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserSelfLink(userPath)
.setUserEmail(exampleUser)
.setUserPassword(exampleUser)
.setIsAdmin(false)
.setDocumentKind(Utils.buildKind(ExampleServiceState.class))
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
this.host.resetAuthorizationContext();
this.host.assumeIdentity(userPath);
URI factoryUri = UriUtils.buildUri(this.host, ExampleService.FACTORY_LINK);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, (op) -> {
ExampleServiceState st = new ExampleServiceState();
st.name = exampleUser;
op.setBody(st);
}, factoryUri);
try {
RequestRateInfo ri = new RequestRateInfo();
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, rate limit is zero");
} catch (IllegalArgumentException e) {
}
try {
RequestRateInfo ri = new RequestRateInfo();
// use a custom time series but of the wrong aggregation type
ri.timeSeries = new TimeSeriesStats(10,
TimeUnit.SECONDS.toMillis(1),
EnumSet.of(AggregationType.AVG));
this.host.setRequestRateLimit(userPath, ri);
throw new IllegalStateException("call should have failed, aggregation is not SUM");
} catch (IllegalArgumentException e) {
}
RequestRateInfo ri = new RequestRateInfo();
ri.limit = 1.1;
this.host.setRequestRateLimit(userPath, ri);
// verify no side effects on instance we supplied
assertTrue(ri.timeSeries == null);
double limit = (this.rateLimitedRequestCount * this.serviceCount) / 100;
// set limit for this user to 1 request / second, overwrite previous limit
this.host.setRequestRateLimit(userPath, limit);
ri = this.host.getRequestRateLimit(userPath);
assertTrue(Double.compare(ri.limit, limit) == 0);
assertTrue(!ri.options.isEmpty());
assertTrue(ri.options.contains(RequestRateInfo.Option.FAIL));
assertTrue(ri.timeSeries != null);
assertTrue(ri.timeSeries.numBins == 60);
assertTrue(ri.timeSeries.aggregationType.contains(AggregationType.SUM));
// set maintenance to default time to see how throttling behaves with default interval
this.host.setMaintenanceIntervalMicros(
ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS);
AtomicInteger failureCount = new AtomicInteger();
AtomicInteger successCount = new AtomicInteger();
// send N requests, at once, clearly violating the limit, and expect failures
int count = this.rateLimitedRequestCount;
TestContext ctx = this.host.testCreate(count * states.size());
ctx.setTestName("Rate limiting with failure").logBefore();
CompletionHandler c = (o, e) -> {
if (e != null) {
if (o.getStatusCode() != Operation.STATUS_CODE_UNAVAILABLE) {
ctx.failIteration(e);
return;
}
failureCount.incrementAndGet();
} else {
successCount.incrementAndGet();
}
ctx.completeIteration();
};
ExampleServiceState patchBody = new ExampleServiceState();
patchBody.name = Utils.getSystemNowMicrosUtc() + "";
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(c);
this.host.send(op);
}
}
this.host.testWait(ctx);
ctx.logAfter();
assertTrue(failureCount.get() > 0);
// now change the options, and instead of fail, request throttling. this will literally
// throttle the HTTP listener (does not work on local, in process calls)
ri = new RequestRateInfo();
ri.limit = limit;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatBefore = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
this.host.assumeIdentity(userPath);
if (rateLimitStatBefore == null) {
rateLimitStatBefore = new ServiceStat();
rateLimitStatBefore.latestValue = 0.0;
}
TestContext ctx2 = this.host.testCreate(count * states.size());
ctx2.setTestName("Rate limiting with auto-read pause of channels").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures, but rate limit applied stat should have hits
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx2.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx2);
ctx2.logAfter();
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatAfter = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue > rateLimitStatBefore.latestValue);
this.host.setMaintenanceIntervalMicros(
TimeUnit.MILLISECONDS.toMicros(VerificationHost.FAST_MAINT_INTERVAL_MILLIS));
// effectively remove limit, verify all requests complete
ri = new RequestRateInfo();
ri.limit = 1000000;
ri.options = EnumSet.of(RequestRateInfo.Option.PAUSE_PROCESSING);
this.host.setRequestRateLimit(userPath, ri);
this.host.assumeIdentity(userPath);
count = this.rateLimitedRequestCount;
TestContext ctx3 = this.host.testCreate(count * states.size());
ctx3.setTestName("No limit").logBefore();
for (URI serviceUri : states.keySet()) {
for (int i = 0; i < count; i++) {
// expect zero failures
Operation op = Operation.createPatch(serviceUri)
.setBody(patchBody)
.forceRemote()
.setCompletion(ctx3.getCompletion());
this.host.send(op);
}
}
this.host.testWait(ctx3);
ctx3.logAfter();
// verify rate limiting did not happen
this.host.setSystemAuthorizationContext();
ServiceStat rateLimitStatExpectSame = getRateLimitOpCountStat();
this.host.resetSystemAuthorizationContext();
assertTrue(rateLimitStatAfter.latestValue == rateLimitStatExpectSame.latestValue);
}
@Test
public void postFailureOnAlreadyStarted() throws Throwable {
setUp(false);
Service s = this.host.startServiceAndWait(MinimalTestService.class, UUID.randomUUID()
.toString());
this.host.testStart(1);
Operation post = Operation.createPost(s.getUri()).setCompletion(
(o, e) -> {
if (e == null) {
this.host.failIteration(new IllegalStateException(
"Request should have failed"));
return;
}
if (!(e instanceof ServiceAlreadyStartedException)) {
this.host.failIteration(new IllegalStateException(
"Request should have failed with different exception"));
return;
}
this.host.completeIteration();
});
this.host.startService(post, new MinimalTestService());
this.host.testWait();
}
@Test
public void startUpWithArgumentsAndHostConfigValidation() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
URI publicUri = new URI("http://somehost.com:1234");
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + publicUri.toString(),
"--id=" + hostId
};
h.initialize(args);
// set memory limits for some services
double queryTasksRelativeLimit = 0.1;
double hostLimit = 0.29;
h.setServiceMemoryLimit(ServiceHost.ROOT_PATH, hostLimit);
h.setServiceMemoryLimit(ServiceUriPaths.CORE_QUERY_TASKS, queryTasksRelativeLimit);
// attempt to set limit that brings total > 1.0
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.99);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
h.start();
assertTrue(UriUtils.isHostEqual(h, publicUri));
assertTrue(UriUtils.isHostEqual(h, new URI("http://127.0.0.1:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("https://somehost.com:" + h.getPort())));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost.com")));
assertFalse(UriUtils.isHostEqual(h, new URI("http://somehost2.com:1234")));
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(bindAddress, h.getUri().getHost());
assertEquals(hostId, h.getId());
assertEquals(publicUri, h.getPublicUri());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicUri.getHost(), selfEntry.groupReference.getHost());
assertEquals(publicUri.getPort(), selfEntry.groupReference.getPort());
// validate memory limits per service
long maxMemory = Runtime.getRuntime().maxMemory() / (1024 * 1024);
double hostRelativeLimit = hostLimit;
double indexRelativeLimit = ServiceHost.DEFAULT_PCT_MEMORY_LIMIT_DOCUMENT_INDEX;
long expectedHostLimitMB = (long) (maxMemory * hostRelativeLimit);
Long hostLimitMB = h.getServiceMemoryLimitMB(ServiceHost.ROOT_PATH,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedHostLimitMB - hostLimitMB) < 10);
long expectedIndexLimitMB = (long) (maxMemory * indexRelativeLimit);
Long indexLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_DOCUMENT_INDEX,
MemoryLimitType.EXACT);
assertTrue("Expected index service limit outside bounds",
Math.abs(expectedIndexLimitMB - indexLimitMB) < 10);
long expectedQueryTaskLimitMB = (long) (maxMemory * queryTasksRelativeLimit);
Long queryTaskLimitMB = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.EXACT);
assertTrue("Expected host limit outside bounds",
Math.abs(expectedQueryTaskLimitMB - queryTaskLimitMB) < 10);
// also check the water marks
long lowW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.LOW_WATERMARK);
assertTrue("Expected low watermark to be less than exact",
lowW < queryTaskLimitMB);
long highW = h.getServiceMemoryLimitMB(ServiceUriPaths.CORE_QUERY_TASKS,
MemoryLimitType.HIGH_WATERMARK);
assertTrue("Expected high watermark to be greater than low but less than exact",
highW > lowW && highW < queryTaskLimitMB);
// attempt to set the limit for a service after a host has started, it should fail
try {
h.setServiceMemoryLimit(ServiceUriPaths.CORE_OPERATION_INDEX, 0.2);
throw new IllegalStateException("Should have failed");
} catch (Throwable e) {
}
// verify service host configuration file reflects command line arguments
File s = new File(h.getStorageSandbox());
s = new File(s, ServiceHost.SERVICE_HOST_STATE_FILE);
this.host.testStart(1);
ServiceHostState [] state = new ServiceHostState[1];
Operation get = Operation.createGet(h.getUri()).setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
state[0] = o.getBody(ServiceHostState.class);
this.host.completeIteration();
});
FileUtils.readFileAndComplete(get, s);
this.host.testWait();
assertEquals(h.getStorageSandbox(), state[0].storageSandboxFileReference);
assertEquals(h.getOperationTimeoutMicros(), state[0].operationTimeoutMicros);
assertEquals(h.getMaintenanceIntervalMicros(), state[0].maintenanceIntervalMicros);
assertEquals(bindAddress, state[0].bindAddress);
assertEquals(h.getPort(), state[0].httpPort);
assertEquals(hostId, state[0].id);
// now stop the host, change some arguments, restart, verify arguments override config
h.stop();
bindAddress = "localhost";
hostId = UUID.randomUUID().toString();
String [] args2 = {
"--port=" + 0,
"--bindAddress=" + bindAddress,
"--sandbox=" + this.tmpFolder.getRoot().toURI(),
"--id=" + hostId
};
h.initialize(args2);
h.start();
assertEquals(bindAddress, h.getState().bindAddress);
assertEquals(hostId, h.getState().id);
verifyAuthorizedServiceMethods(h);
verifyCoreServiceOption(h);
} finally {
h.stop();
}
}
private void verifyCoreServiceOption(ExampleServiceHost h) {
List<URI> coreServices = new ArrayList<>();
URI defaultNodeGroup = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_GROUP);
URI defaultNodeSelector = UriUtils.buildUri(h, ServiceUriPaths.DEFAULT_NODE_SELECTOR);
coreServices.add(UriUtils.buildConfigUri(defaultNodeGroup));
coreServices.add(UriUtils.buildConfigUri(defaultNodeSelector));
coreServices.add(UriUtils.buildConfigUri(h.getDocumentIndexServiceUri()));
Map<URI, ServiceConfiguration> cfgs = this.host.getServiceState(null,
ServiceConfiguration.class, coreServices);
for (ServiceConfiguration c : cfgs.values()) {
assertTrue(c.options.contains(ServiceOption.CORE));
}
}
private void verifyAuthorizedServiceMethods(ServiceHost h) {
MinimalTestService s = new MinimalTestService();
try {
h.getAuthorizationContext(s, UUID.randomUUID().toString());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
try {
h.cacheAuthorizationContext(s,
this.host.getGuestAuthorizationContext());
throw new IllegalStateException("call should have failed");
} catch (IllegalStateException e) {
throw e;
} catch (RuntimeException e) {
}
}
@Test
public void setPublicUri() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
// try invalid arguments
ServiceHost.Arguments hostArgs = new ServiceHost.Arguments();
hostArgs.publicUri = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.bindAddress = "";
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
hostArgs = new ServiceHost.Arguments();
hostArgs.port = -2;
try {
h.initialize(hostArgs);
throw new IllegalStateException("should have failed");
} catch (IllegalArgumentException e) {
}
String bindAddress = "127.0.0.1";
String publicAddress = "10.1.1.19";
int publicPort = 1634;
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--publicUri=" + new URI("http://" + publicAddress + ":" + publicPort),
"--id=" + hostId
};
h.initialize(args);
h.start();
assertEquals(bindAddress, h.getPreferredAddress());
assertEquals(h.getPort(), h.getUri().getPort());
assertEquals(bindAddress, h.getUri().getHost());
// confirm that public URI takes precedence over bind address
assertEquals(publicAddress, h.getPublicUri().getHost());
assertEquals(publicPort, h.getPublicUri().getPort());
// confirm the node group self node entry uses the public URI for the bind address
NodeGroupState ngs = this.host.getServiceState(null, NodeGroupState.class,
UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP));
NodeState selfEntry = ngs.nodes.get(h.getId());
assertEquals(publicAddress, selfEntry.groupReference.getHost());
assertEquals(publicPort, selfEntry.groupReference.getPort());
} finally {
h.stop();
}
}
@Test
public void jwtSecret() throws Throwable {
setUp(false);
Claims claims = new Claims.Builder().setSubject("foo").getResult();
Signer bogusSigner = new Signer("bogus".getBytes());
Signer defaultSigner = this.host.getTokenSigner();
Verifier defaultVerifier = this.host.getTokenVerifier();
String signedByBogus = bogusSigner.sign(claims);
String signedByDefault = defaultSigner.sign(claims);
try {
defaultVerifier.verify(signedByBogus);
fail("Signed by bogusSigner should be invalid for defaultVerifier.");
} catch (Verifier.InvalidSignatureException ex) {
}
Rfc7519Claims verified = defaultVerifier.verify(signedByDefault);
assertEquals("foo", verified.getSubject());
this.host.stop();
// assign cert and private-key. private-key is used for JWT seed.
URI certFileUri = getClass().getResource("/ssl/server.crt").toURI();
URI keyFileUri = getClass().getResource("/ssl/server.pem").toURI();
this.host.setCertificateFileReference(certFileUri);
this.host.setPrivateKeyFileReference(keyFileUri);
// must assign port to zero, so we get a *new*, available port on restart.
this.host.setPort(0);
this.host.start();
Signer newSigner = this.host.getTokenSigner();
Verifier newVerifier = this.host.getTokenVerifier();
assertNotSame("new signer must be created", defaultSigner, newSigner);
assertNotSame("new verifier must be created", defaultVerifier, newVerifier);
try {
newVerifier.verify(signedByDefault);
fail("Signed by defaultSigner should be invalid for newVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
// sign by newSigner
String signedByNewSigner = newSigner.sign(claims);
verified = newVerifier.verify(signedByNewSigner);
assertEquals("foo", verified.getSubject());
try {
defaultVerifier.verify(signedByNewSigner);
fail("Signed by newSigner should be invalid for defaultVerifier");
} catch (Verifier.InvalidSignatureException ex) {
}
}
@Test
public void startWithNonEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with password for non-encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void startWithEncryptedPem() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server-with-pass.p8").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=password",
};
try {
h.initialize(args);
h.start();
} finally {
h.stop();
}
// with wrong password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
"--keyPassphrase=WRONG_PASSWORD",
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start with wrong password for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
// with no password
args = new String[] {
"--sandbox=" + tmpFolderPath,
"--port=0",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile,
};
try {
h.initialize(args);
h.start();
fail("Host should NOT start when no password is specified for encrypted pem key");
} catch (Exception ex) {
} finally {
h.stop();
}
}
@Test
public void httpsOnly() throws Throwable {
ExampleServiceHost h = new ExampleServiceHost();
String tmpFolderPath = this.tmpFolder.getRoot().getAbsolutePath();
// We run test from filesystem so far, thus expect files to be on file system.
// For example, if we run test from jar file, needs to copy the resource to tmp dir.
Path certFilePath = Paths.get(getClass().getResource("/ssl/server.crt").toURI());
Path keyFilePath = Paths.get(getClass().getResource("/ssl/server.pem").toURI());
String certFile = certFilePath.toFile().getAbsolutePath();
String keyFile = keyFilePath.toFile().getAbsolutePath();
// set -1 to disable http
String[] args = {
"--sandbox=" + tmpFolderPath,
"--port=-1",
"--securePort=0",
"--certificateFile=" + certFile,
"--keyFile=" + keyFile
};
try {
h.initialize(args);
h.start();
assertNull("http should be disabled", h.getListener());
assertNotNull("https should be enabled", h.getSecureListener());
} finally {
h.stop();
}
}
@Test
public void setAuthEnforcement() throws Throwable {
setUp(false);
ExampleServiceHost h = new ExampleServiceHost();
try {
String bindAddress = "127.0.0.1";
String hostId = UUID.randomUUID().toString();
String[] args = {
"--sandbox=" + this.tmpFolder.getRoot().getAbsolutePath(),
"--port=0",
"--bindAddress=" + bindAddress,
"--isAuthorizationEnabled=" + Boolean.TRUE.toString(),
"--id=" + hostId
};
h.initialize(args);
assertTrue(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(false);
assertFalse(h.isAuthorizationEnabled());
h.setAuthorizationEnabled(true);
h.start();
this.host.testStart(1);
h.sendRequest(Operation
.createGet(UriUtils.buildUri(h.getUri(), ServiceUriPaths.DEFAULT_NODE_GROUP))
.setReferer(this.host.getReferer())
.setCompletion((o, e) -> {
if (o.getStatusCode() == Operation.STATUS_CODE_FORBIDDEN) {
this.host.completeIteration();
return;
}
this.host.failIteration(new IllegalStateException(
"Op succeded when failure expected"));
}));
this.host.testWait();
} finally {
h.stop();
}
}
@Test
public void serviceStartExpiration() throws Throwable {
setUp(false);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// set a small period so its pretty much guaranteed to execute
// maintenance during this test
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = MinimalTestService.STRING_MARKER_TIMEOUT_REQUEST;
this.host.testStart(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setExpiration(Utils.fromNowMicrosUtc(maintenanceIntervalMicros))
.setBody(initialState)
.setCompletion(this.host.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait();
}
@Test
public void startServiceSelfLinkWithStar() throws Throwable {
setUp(false);
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = this.host.nextUUID();
TestContext ctx = this.host.testCreate(1);
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, this.host.nextUUID() + "*"))
.setBody(initialState).setCompletion(ctx.getExpectedFailureCompletion());
this.host.startService(startPost, new MinimalTestService());
this.host.testWait(ctx);
}
public static class StopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public StopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
public static class PrivilegedStopOrderTestService extends StatefulService {
public int stopOrder;
public AtomicInteger globalStopOrder;
public PrivilegedStopOrderTestService() {
super(MinimalTestServiceState.class);
}
@Override
public void handleStop(Operation delete) {
this.stopOrder = this.globalStopOrder.incrementAndGet();
delete.complete();
}
}
@Test
public void serviceStopOrder() throws Throwable {
setUp(false);
// start a service but tell it to not complete the start POST. This will induce a timeout
// failure from the host
int serviceCount = 10;
AtomicInteger order = new AtomicInteger(0);
this.host.testStart(serviceCount);
List<StopOrderTestService> normalServices = new ArrayList<>();
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
StopOrderTestService normalService = new StopOrderTestService();
normalServices.add(normalService);
normalService.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, normalService);
}
this.host.testWait();
this.host.addPrivilegedService(PrivilegedStopOrderTestService.class);
List<PrivilegedStopOrderTestService> pServices = new ArrayList<>();
this.host.testStart(serviceCount);
for (int i = 0; i < serviceCount; i++) {
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = UUID.randomUUID().toString();
PrivilegedStopOrderTestService ps = new PrivilegedStopOrderTestService();
pServices.add(ps);
ps.globalStopOrder = order;
Operation post = Operation.createPost(UriUtils.buildUri(this.host, initialState.id))
.setBody(initialState)
.setCompletion(this.host.getCompletion());
this.host.startService(post, ps);
}
this.host.testWait();
this.host.stop();
for (PrivilegedStopOrderTestService pService : pServices) {
for (StopOrderTestService normalService : normalServices) {
this.host.log("normal order: %d, privileged: %d", normalService.stopOrder,
pService.stopOrder);
assertTrue(normalService.stopOrder < pService.stopOrder);
}
}
}
@Test
public void maintenanceAndStatsReporting() throws Throwable {
CommandLineArgumentParser.parseFromProperties(this);
for (int i = 0; i < this.iterationCount; i++) {
this.tearDown();
doMaintenanceAndStatsReporting();
}
}
private void doMaintenanceAndStatsReporting() throws Throwable {
setUp(true);
// induce host to clear service state cache by setting mem limit low
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.0001);
this.host.setServiceMemoryLimit(LuceneDocumentIndexService.SELF_LINK, 0.0001);
long maintIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(maintIntervalMillis);
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(TimeUnit.MILLISECONDS
.toMicros(maintIntervalMillis / 2));
this.host.start();
verifyMaintenanceDelayStat(maintenanceIntervalMicros);
long opCount = 2;
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.PERIODIC_MAINTENANCE);
List<Service> services = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
long start = System.nanoTime() / 1000;
List<Service> slowMaintServices = this.host.doThroughputServiceStart(null,
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null, maintenanceIntervalMicros * 10);
List<URI> uris = new ArrayList<>();
for (Service s : services) {
uris.add(s.getUri());
}
this.host.doPutPerService(opCount, EnumSet.of(TestProperty.FORCE_REMOTE),
services);
long cacheMissCount = 0;
long cacheClearCount = 0;
ServiceStat cacheClearStat = null;
Map<URI, ServiceStats> servicesWithMaintenance = new HashMap<>();
double maintCount = getHostMaintenanceCount();
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 10;
});
Date exp = this.host.getTestExpiration();
while (new Date().before(exp)) {
// issue GET to actually make the cache miss occur (if the cache has been cleared)
this.host.getServiceState(null, MinimalTestServiceState.class, uris);
// verify each service show at least a couple of maintenance requests
URI[] statUris = buildStatsUris(this.serviceCount, services);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (Entry<URI, ServiceStats> e : stats.entrySet()) {
long maintFailureCount = 0;
ServiceStats s = e.getValue();
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_CACHE_MISS_COUNT)) {
cacheMissCount += (long) st.latestValue;
continue;
}
if (st.name.equals(Service.STAT_NAME_CACHE_CLEAR_COUNT)) {
cacheClearCount += (long) st.latestValue;
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_SUCCESS_COUNT)) {
servicesWithMaintenance.put(e.getKey(), e.getValue());
continue;
}
if (st.name.equals(MinimalTestService.STAT_NAME_MAINTENANCE_FAILURE_COUNT)) {
maintFailureCount++;
continue;
}
}
assertTrue("maintenance failed", maintFailureCount == 0);
}
// verify that every single service has seen at least one maintenance interval
if (servicesWithMaintenance.size() < this.serviceCount) {
this.host.log("Services with maintenance: %d, expected %d",
servicesWithMaintenance.size(), this.serviceCount);
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheMissCount < 1) {
this.host.log("No cache misses seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
if (cacheClearCount < 1) {
this.host.log("No cache clears seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
Map<String, ServiceStat> mgmtStats = this.host.getServiceStats(this.host.getManagementServiceUri());
cacheClearStat = mgmtStats.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
this.host.log("Cache clear stat on management service not seen");
Thread.sleep(maintIntervalMillis * 2);
continue;
}
break;
}
long end = System.nanoTime() / 1000;
if (cacheClearStat == null || cacheClearStat.latestValue < 1) {
throw new IllegalStateException(
"Cache clear stat on management service not observed");
}
this.host.log("State cache misses: %d, cache clears: %d", cacheMissCount, cacheClearCount);
double expectedMaintIntervals = Math.max(1,
(end - start) / this.host.getMaintenanceIntervalMicros());
// allow variance up to 2x of expected intervals. We have the interval set to 100ms
// and we are running tests on VMs, in over subscribed CI. So we expect significant
// scheduling variance. This test is extremely consistent on a local machine
expectedMaintIntervals *= 2;
for (Entry<URI, ServiceStats> e : servicesWithMaintenance.entrySet()) {
ServiceStat maintStat = e.getValue().entries.get(Service.STAT_NAME_MAINTENANCE_COUNT);
this.host.log("%s has %f intervals", e.getKey(), maintStat.latestValue);
if (maintStat.latestValue > expectedMaintIntervals + 2) {
String error = String.format("Expected %f, got %f. Too many stats for service %s",
expectedMaintIntervals + 2,
maintStat.latestValue,
e.getKey());
throw new IllegalStateException(error);
}
}
if (cacheMissCount < 1) {
throw new IllegalStateException(
"No cache misses observed through stats");
}
long slowMaintInterval = this.host.getMaintenanceIntervalMicros() * 10;
end = System.nanoTime() / 1000;
expectedMaintIntervals = Math.max(1, (end - start) / slowMaintInterval);
// verify that services with slow maintenance did not get more than one maint cycle
URI[] statUris = buildStatsUris(this.serviceCount, slowMaintServices);
Map<URI, ServiceStats> stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
// give a slop of 3 extra intervals:
// 1 due to rounding, 2 due to interval running before we do setMaintenance
// to a slower interval ( notice we start services, then set the interval)
if (st.latestValue > expectedMaintIntervals + 3) {
throw new IllegalStateException(
"too many maintenance runs for slow maint. service:"
+ st.latestValue);
}
}
}
}
this.host.testStart(services.size());
// delete all minimal service instances
for (Service s : services) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
this.host.testStart(slowMaintServices.size());
// delete all minimal service instances
for (Service s : slowMaintServices) {
this.host.send(Operation.createDelete(s.getUri()).setBody(new ServiceDocument())
.setCompletion(this.host.getCompletion()));
}
this.host.testWait();
// before we increase maintenance interval, verify stats reported by MGMT service
verifyMgmtServiceStats();
// now validate that service handleMaintenance does not get called right after start, but at least
// one interval later. We set the interval to 30 seconds so we can verify it did not get called within
// one second or so
long maintMicros = TimeUnit.SECONDS.toMicros(30);
this.host.setMaintenanceIntervalMicros(maintMicros);
// there is a small race: if the host scheduled a maintenance task already, using the default
// 1 second interval, its possible it executes maintenance on the newly added services using
// the 1 second schedule, instead of 30 seconds. So wait at least one maint. interval with the
// default interval
Thread.sleep(1000);
slowMaintServices = this.host.doThroughputServiceStart(
this.serviceCount, MinimalTestService.class, this.host.buildMinimalTestState(),
caps,
null);
// sleep again and check no maintenance run right after start
Thread.sleep(250);
statUris = buildStatsUris(this.serviceCount, slowMaintServices);
stats = this.host.getServiceState(null,
ServiceStats.class, statUris);
for (ServiceStats s : stats.values()) {
for (ServiceStat st : s.entries.values()) {
if (st.name.equals(Service.STAT_NAME_MAINTENANCE_COUNT)) {
throw new IllegalStateException("Maintenance run before first expiration:"
+ Utils.toJsonHtml(s));
}
}
}
}
private void verifyMgmtServiceStats() {
URI serviceHostMgmtURI = UriUtils.buildUri(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.waitFor("wait for http stat update.", () -> {
Operation get = Operation.createGet(this.host, ServiceHostManagementService.SELF_LINK);
this.host.send(get.forceRemote());
this.host.send(get.clone().forceRemote().setConnectionSharing(true));
Map<String, ServiceStat> hostMgmtStats = this.host
.getServiceStats(serviceHostMgmtURI);
ServiceStat http1ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_CONNECTION_COUNT_PER_DAY);
if (http1ConnectionCountDaily == null
|| http1ConnectionCountDaily.version < 3) {
return false;
}
ServiceStat http2ConnectionCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_CONNECTION_COUNT_PER_DAY);
if (http2ConnectionCountDaily == null
|| http2ConnectionCountDaily.version < 3) {
return false;
}
return true;
});
this.host.waitFor("stats never populated", () -> {
// confirm host global time series stats have been created / updated
Map<String, ServiceStat> hostMgmtStats = this.host.getServiceStats(serviceHostMgmtURI);
ServiceStat serviceCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_COUNT);
if (serviceCount == null || serviceCount.latestValue < 2) {
this.host.log("not ready: %s", Utils.toJson(serviceCount));
return false;
}
ServiceStat freeMemDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeMemDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeMemDaily));
return false;
}
ServiceStat freeMemHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_MEMORY_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeMemHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeMemHourly));
return false;
}
ServiceStat freeDiskDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_DAY);
if (!isTimeSeriesStatReady(freeDiskDaily)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskDaily));
return false;
}
ServiceStat freeDiskHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_AVAILABLE_DISK_BYTES_PER_HOUR);
if (!isTimeSeriesStatReady(freeDiskHourly)) {
this.host.log("not ready: %s", Utils.toJson(freeDiskHourly));
return false;
}
ServiceStat cpuUsageDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_DAY);
if (!isTimeSeriesStatReady(cpuUsageDaily)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageDaily));
return false;
}
ServiceStat cpuUsageHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_CPU_USAGE_PCT_PER_HOUR);
if (!isTimeSeriesStatReady(cpuUsageHourly)) {
this.host.log("not ready: %s", Utils.toJson(cpuUsageHourly));
return false;
}
ServiceStat threadCountDaily = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_DAY);
if (!isTimeSeriesStatReady(threadCountDaily)) {
this.host.log("not ready: %s", Utils.toJson(threadCountDaily));
return false;
}
ServiceStat threadCountHourly = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_JVM_THREAD_COUNT_PER_HOUR);
if (!isTimeSeriesStatReady(threadCountHourly)) {
this.host.log("not ready: %s", Utils.toJson(threadCountHourly));
return false;
}
ServiceStat http1PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP11_PENDING_OP_COUNT);
if (http1PendingCount == null) {
this.host.log("http1 pending op stats not present");
return false;
}
ServiceStat http2PendingCount = hostMgmtStats
.get(ServiceHostManagementService.STAT_NAME_HTTP2_PENDING_OP_COUNT);
if (http2PendingCount == null) {
this.host.log("http2 pending op stats not present");
return false;
}
TestUtilityService.validateTimeSeriesStat(freeMemDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeMemHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(freeDiskHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(cpuUsageHourly, TimeUnit.MINUTES.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountDaily, TimeUnit.HOURS.toMillis(1));
TestUtilityService.validateTimeSeriesStat(threadCountHourly,
TimeUnit.MINUTES.toMillis(1));
return true;
});
}
private boolean isTimeSeriesStatReady(ServiceStat st) {
return st != null && st.timeSeriesStats != null;
}
private void verifyMaintenanceDelayStat(long intervalMicros) throws Throwable {
// verify state on maintenance delay takes hold
this.host.setMaintenanceIntervalMicros(intervalMicros);
MinimalTestService ts = new MinimalTestService();
ts.delayMaintenance = true;
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, true);
ts.toggleOption(ServiceOption.INSTRUMENTATION, true);
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = UUID.randomUUID().toString();
ts = (MinimalTestService) this.host.startServiceAndWait(ts, UUID.randomUUID().toString(),
body);
MinimalTestService finalTs = ts;
this.host.waitFor("Maintenance delay stat never reported", () -> {
ServiceStats stats = this.host.getServiceState(null, ServiceStats.class,
UriUtils.buildStatsUri(finalTs.getUri()));
if (stats.entries == null || stats.entries.isEmpty()) {
Thread.sleep(intervalMicros / 1000);
return false;
}
ServiceStat delayStat = stats.entries
.get(Service.STAT_NAME_MAINTENANCE_COMPLETION_DELAYED_COUNT);
ServiceStat durationStat = stats.entries.get(Service.STAT_NAME_MAINTENANCE_DURATION);
if (delayStat == null) {
Thread.sleep(intervalMicros / 1000);
return false;
}
if (durationStat == null || (durationStat != null && durationStat.logHistogram == null)) {
return false;
}
return true;
});
ts.toggleOption(ServiceOption.PERIODIC_MAINTENANCE, false);
}
@Test
public void registerForServiceAvailabilityTimeout()
throws Throwable {
setUp(false);
int c = 10;
this.host.testStart(c);
// issue requests to service paths we know do not exist, but induce the automatic
// queuing behavior for service availability, by setting targetReplicated = true
for (int i = 0; i < c; i++) {
this.host.send(Operation
.createGet(UriUtils.buildUri(this.host, UUID.randomUUID().toString()))
.setTargetReplicated(true)
.setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(1)))
.setCompletion(this.host.getExpectedFailureCompletion()));
}
this.host.testWait();
}
@Test
public void registerForFactoryServiceAvailability()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(new TestFactoryService.SomeFactoryService(),
SomeExampleService.createFactory());
this.host.waitForServiceAvailable(SomeExampleService.FACTORY_LINK);
this.host.waitForServiceAvailable(TestFactoryService.SomeFactoryService.SELF_LINK);
try {
// not a factory so will fail
this.host.startFactoryServicesSynchronously(new ExampleService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
try {
// does not have SELF_LINK/FACTORY_LINK so will fail
this.host.startFactoryServicesSynchronously(new MinimalFactoryTestService());
throw new IllegalStateException("Should have failed");
} catch (IllegalArgumentException e) {
}
}
public static class SomeExampleService extends StatefulService {
public static final String FACTORY_LINK = UUID.randomUUID().toString();
public static Service createFactory() {
return FactoryService.create(SomeExampleService.class, SomeExampleServiceState.class);
}
public SomeExampleService() {
super(SomeExampleServiceState.class);
}
public static class SomeExampleServiceState extends ServiceDocument {
public String name ;
}
}
@Test
public void registerForServiceAvailabilityBeforeAndAfterMultiple()
throws Throwable {
setUp(false);
int serviceCount = 100;
this.host.testStart(serviceCount * 3);
String[] links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(this.host.getCompletion(),
u.getPath());
}
this.host.registerForServiceAvailability(this.host.getCompletion(),
links);
this.host.testWait();
}
@Test
public void registerForServiceAvailabilityWithReplicaBeforeAndAfterMultiple()
throws Throwable {
setUp(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
String[] links = new String[] {
ExampleService.FACTORY_LINK,
ServiceUriPaths.CORE_AUTHZ_RESOURCE_GROUPS,
ServiceUriPaths.CORE_AUTHZ_USERS,
ServiceUriPaths.CORE_AUTHZ_ROLES,
ServiceUriPaths.CORE_AUTHZ_USER_GROUPS };
// register multiple factories, before host start
TestContext ctx = this.host.testCreate(links.length * 10);
for (int i = 0; i < 10; i++) {
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
}
this.host.start();
this.host.testWait(ctx);
// register multiple factories, after host start
for (int i = 0; i < 10; i++) {
ctx = this.host.testCreate(links.length);
this.host.registerForServiceAvailability(ctx.getCompletion(), true, links);
this.host.testWait(ctx);
}
// verify that the new replica aware service available works with child services
int serviceCount = 10;
ctx = this.host.testCreate(serviceCount * 3);
links = new String[serviceCount];
for (int i = 0; i < serviceCount; i++) {
URI u = UriUtils.buildUri(this.host, UUID.randomUUID().toString());
links[i] = u.getPath();
this.host.registerForServiceAvailability(ctx.getCompletion(),
u.getPath());
this.host.startService(Operation.createPost(u),
ExampleService.createFactory());
this.host.registerForServiceAvailability(ctx.getCompletion(), true,
u.getPath());
}
this.host.registerForServiceAvailability(ctx.getCompletion(),
links);
this.host.testWait(ctx);
}
public static class ParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/parent";
public static Service createFactory() {
return FactoryService.create(ParentService.class);
}
public ParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
}
public static class ChildDependsOnParentService extends StatefulService {
public static final String FACTORY_LINK = "/test/child-of-parent";
public static Service createFactory() {
return FactoryService.create(ChildDependsOnParentService.class);
}
public ChildDependsOnParentService() {
super(ExampleServiceState.class);
super.toggleOption(ServiceOption.PERSISTENCE, true);
}
@Override
public void handleStart(Operation post) {
// do not complete post for start, until we see a instance of the parent
// being available. If there is an issue with factory start, this will
// deadlock
ExampleServiceState st = getBody(post);
String id = Service.getId(st.documentSelfLink);
String parentPath = UriUtils.buildUriPath(ParentService.FACTORY_LINK, id);
post.nestCompletion((o, e) -> {
if (e != null) {
post.fail(e);
return;
}
logInfo("Parent service started!");
post.complete();
});
getHost().registerForServiceAvailability(post, parentPath);
}
}
@Test
public void registerForServiceAvailabilityWithCrossDependencies()
throws Throwable {
setUp(false);
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
String id = UUID.randomUUID().toString();
TestContext ctx = this.host.testCreate(2);
// start a parent instance and a child instance.
ExampleServiceState st = new ExampleServiceState();
st.documentSelfLink = id;
st.name = id;
Operation post = Operation
.createPost(UriUtils.buildUri(this.host, ParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
post = Operation
.createPost(UriUtils.buildUri(this.host, ChildDependsOnParentService.FACTORY_LINK))
.setCompletion(ctx.getCompletion())
.setBody(st);
this.host.send(post);
ctx.await();
// we create the two persisted instances, and they started. Now stop the host and confirm restart occurs
this.host.stop();
this.host.setPort(0);
if (!VerificationHost.restartStatefulHost(this.host, true)) {
this.host.log("Failed restart of host, aborting");
return;
}
this.host.startFactoryServicesSynchronously(ParentService.createFactory(),
ChildDependsOnParentService.createFactory());
// verify instance services started
ctx = this.host.testCreate(1);
String childPath = UriUtils.buildUriPath(ChildDependsOnParentService.FACTORY_LINK, id);
Operation get = Operation.createGet(UriUtils.buildUri(this.host, childPath))
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_QUEUE_FOR_SERVICE_AVAILABILITY)
.setCompletion(ctx.getCompletion());
this.host.send(get);
ctx.await();
}
@Test
public void queueRequestForServiceWithNonFactoryParent() throws Throwable {
setUp(false);
class DelayedStartService extends StatelessService {
@Override
public void handleStart(Operation start) {
getHost().schedule(() -> {
start.complete();
}, 100, TimeUnit.MILLISECONDS);
}
@Override
public void handleGet(Operation get) {
get.complete();
}
}
Operation startOp = Operation.createPost(UriUtils.buildUri(this.host, "/delayed"));
this.host.startService(startOp, new DelayedStartService());
// Don't wait for the service to be started, because it intentionally takes a while.
// The GET operation below should be queued until the service's start completes.
Operation getOp = Operation
.createGet(UriUtils.buildUri(this.host, "/delayed"))
.setCompletion(this.host.getCompletion());
this.host.testStart(1);
this.host.send(getOp);
this.host.testWait();
}
//override setProcessingStage() of ExampleService to randomly
// fail some pause operations
static class PauseExampleService extends ExampleService {
public static final String FACTORY_LINK = ServiceUriPaths.CORE + "/pause-examples";
public static final String STAT_NAME_ABORT_COUNT = "abortCount";
public static FactoryService createFactory() {
return FactoryService.create(PauseExampleService.class);
}
public PauseExampleService() {
super();
// we only pause on demand load services
toggleOption(ServiceOption.ON_DEMAND_LOAD, true);
// ODL services will normally just stop, not pause. To make them pause
// we need to either add subscribers or stats. We toggle the INSTRUMENTATION
// option (even if ExampleService already sets it, we do it again in case it
// changes in the future)
toggleOption(ServiceOption.INSTRUMENTATION, true);
}
@Override
public ServiceRuntimeContext setProcessingStage(Service.ProcessingStage stage) {
if (stage == Service.ProcessingStage.PAUSED) {
if (new Random().nextBoolean()) {
this.adjustStat(STAT_NAME_ABORT_COUNT, 1);
throw new CancellationException("Cannot pause service.");
}
}
return super.setProcessingStage(stage);
}
}
@Test
public void servicePauseDueToMemoryPressure() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
if (this.serviceCount >= 1000) {
this.host.setStressTest(true);
}
// Set the threshold low to induce it during this test, several times. This will
// verify that refreshing the index writer does not break the index semantics
LuceneDocumentIndexService
.setIndexFileCountThresholdForWriterRefresh(this.indexFileThreshold);
// set memory limit low to force service pause
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
beforeHostStart(this.host);
this.host.setPort(0);
long delayMicros = TimeUnit.SECONDS
.toMicros(this.serviceCacheClearDelaySeconds);
this.host.setServiceCacheClearDelayMicros(delayMicros);
// disable auto sync since it might cause a false negative (skipped pauses) when
// it kicks in within a few milliseconds from host start, during induced pause
this.host.setPeerSynchronizationEnabled(false);
long delayMicrosAfter = this.host.getServiceCacheClearDelayMicros();
assertTrue(delayMicros == delayMicrosAfter);
this.host.start();
this.host.setSystemAuthorizationContext();
TestContext ctxQuery = this.host.testCreate(1);
String user = "foo@bar.com";
Query.Builder queryBuilder = Query.Builder.create()
.addFieldClause(ServiceDocument.FIELD_NAME_KIND, Utils.buildKind(ExampleServiceState.class));
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(user)
.setUserSelfLink(user)
.setUserPassword(user)
.setResourceQuery(queryBuilder.build())
.setCompletion((ex) -> {
if (ex != null) {
ctxQuery.failIteration(ex);
return;
}
ctxQuery.completeIteration();
}).start();
ctxQuery.await();
this.host.startFactory(PauseExampleService.class,
PauseExampleService::createFactory);
URI factoryURI = UriUtils.buildFactoryUri(this.host, PauseExampleService.class);
this.host.waitForServiceAvailable(PauseExampleService.FACTORY_LINK);
this.host.resetSystemAuthorizationContext();
AtomicLong selfLinkCounter = new AtomicLong();
String prefix = "instance-";
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
s.documentSelfLink = prefix + selfLinkCounter.incrementAndGet();
o.setBody(s);
};
// Create a number of child services.
this.host.assumeIdentity(UriUtils.buildUriPath(UserService.FACTORY_LINK, user));
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
// Wait for the next maintenance interval to trigger. This will pause all the services
// we just created since the memory limit was set so low.
long expectedPauseTime = Utils.fromNowMicrosUtc(this.host
.getMaintenanceIntervalMicros() * 5);
while (this.host.getState().lastMaintenanceTimeUtcMicros < expectedPauseTime) {
// memory limits are applied during maintenance, so wait for a few intervals.
Thread.sleep(this.host.getMaintenanceIntervalMicros() / 1000);
}
// Let's now issue some updates to verify paused services get resumed.
int updateCount = 100;
if (this.testDurationSeconds > 0 || this.host.isStressTest()) {
updateCount = 1;
}
patchExampleServices(states, updateCount);
TestContext ctxGet = this.host.testCreate(states.size());
for (ExampleServiceState st : states.values()) {
Operation get = Operation.createGet(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion(
(o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
ExampleServiceState rsp = o.getBody(ExampleServiceState.class);
if (!rsp.name.startsWith("updated")) {
ctxGet.fail(new IllegalStateException(Utils
.toJsonHtml(rsp)));
return;
}
ctxGet.complete();
});
this.host.send(get);
}
this.host.testWait(ctxGet);
if (this.testDurationSeconds == 0) {
verifyPauseResumeStats(states);
}
// Let's set the service memory limit back to normal and issue more updates to ensure
// that the services still continue to operate as expected.
this.host
.setServiceMemoryLimit(ServiceHost.ROOT_PATH, ServiceHost.DEFAULT_PCT_MEMORY_LIMIT);
patchExampleServices(states, updateCount);
states.clear();
// Long running test. Keep adding services, expecting pause to occur and free up memory so the
// number of service instances exceeds available memory.
Date exp = new Date(TimeUnit.MICROSECONDS.toMillis(
Utils.getSystemNowMicrosUtc())
+ TimeUnit.SECONDS.toMillis(this.testDurationSeconds));
this.host.setOperationTimeOutMicros(
TimeUnit.SECONDS.toMicros(this.host.getTimeoutSeconds()));
while (new Date().before(exp)) {
states = this.host.doFactoryChildServiceStart(null,
this.serviceCount,
ExampleServiceState.class, bodySetter, factoryURI);
Thread.sleep(500);
this.host.log("created %d services, created so far: %d, attached count: %d",
this.serviceCount,
selfLinkCounter.get(),
this.host.getState().serviceCount);
Runtime.getRuntime().gc();
this.host.logMemoryInfo();
File f = new File(this.host.getStorageSandbox());
this.host.log("Sandbox: %s, Disk: free %d, usable: %d, total: %d", f.toURI(),
f.getFreeSpace(),
f.getUsableSpace(),
f.getTotalSpace());
// let a couple of maintenance intervals run
Thread.sleep(TimeUnit.MICROSECONDS.toMillis(this.host.getMaintenanceIntervalMicros()) * 2);
// ping every service we created to see if they can be resumed
TestContext getCtx = this.host.testCreate(states.size());
for (URI u : states.keySet()) {
Operation get = Operation.createGet(u).setCompletion((o, e) -> {
if (e == null) {
getCtx.complete();
return;
}
if (o.getStatusCode() == Operation.STATUS_CODE_TIMEOUT) {
// check the document index, if we ever created this service
try {
this.host.createAndWaitSimpleDirectQuery(
ServiceDocument.FIELD_NAME_SELF_LINK, o.getUri().getPath(), 1, 1);
} catch (Throwable e1) {
getCtx.fail(e1);
return;
}
}
getCtx.fail(e);
});
this.host.send(get);
}
this.host.testWait(getCtx);
long limit = this.serviceCount * 30;
if (selfLinkCounter.get() <= limit) {
continue;
}
TestContext ctxDelete = this.host.testCreate(states.size());
// periodically, delete services we created (and likely paused) several passes ago
for (int i = 0; i < states.size(); i++) {
String childPath = UriUtils.buildUriPath(factoryURI.getPath(), prefix + ""
+ (selfLinkCounter.get() - limit + i));
Operation delete = Operation.createDelete(this.host, childPath);
delete.setCompletion((o, e) -> {
ctxDelete.complete();
});
this.host.send(delete);
}
ctxDelete.await();
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
long fileCount = Files.list(indexDir.toPath()).count();
this.host.log("Paused file count %d", fileCount);
}
}
private void deletePausedFiles() throws IOException {
File indexDir = new File(this.host.getStorageSandbox());
indexDir = new File(indexDir, ServiceContextIndexService.FILE_PATH);
if (!indexDir.exists()) {
return;
}
AtomicInteger count = new AtomicInteger();
Files.list(indexDir.toPath()).forEach((p) -> {
try {
Files.deleteIfExists(p);
count.incrementAndGet();
} catch (Exception e) {
}
});
this.host.log("Deleted %d files", count.get());
}
private void verifyPauseResumeStats(Map<URI, ExampleServiceState> states) throws Throwable {
// Let's now query stats for each service. We will use these stats to verify that the
// services did get paused and resumed.
WaitHandler wh = () -> {
int totalServicePauseResumeOrAbort = 0;
int pauseCount = 0;
List<URI> statsUris = new ArrayList<>();
// Verify the stats for each service show that the service was paused and resumed
for (ExampleServiceState st : states.values()) {
URI serviceUri = UriUtils.buildStatsUri(this.host, st.documentSelfLink);
statsUris.add(serviceUri);
}
Map<URI, ServiceStats> statsPerService = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats serviceStats : statsPerService.values()) {
ServiceStat pauseStat = serviceStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
ServiceStat resumeStat = serviceStats.entries.get(Service.STAT_NAME_RESUME_COUNT);
ServiceStat abortStat = serviceStats.entries
.get(PauseExampleService.STAT_NAME_ABORT_COUNT);
if (abortStat == null && pauseStat == null && resumeStat == null) {
return false;
}
if (pauseStat != null) {
pauseCount += pauseStat.latestValue;
}
totalServicePauseResumeOrAbort++;
}
if (totalServicePauseResumeOrAbort < states.size() || pauseCount == 0) {
this.host.log(
"ManagementSvc total pause + resume or abort was less than service count."
+ "Abort,Pause,Resume: %d, pause:%d (service count: %d)",
totalServicePauseResumeOrAbort, pauseCount, states.size());
return false;
}
this.host.log("Pause count: %d", pauseCount);
return true;
};
this.host.waitFor("Service stats did not get updated", wh);
}
@Test
public void maintenanceForOnDemandLoadServices() throws Throwable {
setUp(true);
long maintenanceIntervalMillis = 100;
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS
.toMicros(maintenanceIntervalMillis);
// induce host to clear service state cache by setting mem limit low
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.INSTRUMENTATION, ServiceOption.ON_DEMAND_LOAD, ServiceOption.FACTORY_ITEM);
// Start the factory service. it will be needed to start services on-demand
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "service", null);
// Start some test services with ServiceOption.ON_DEMAND_LOAD
List<Service> services = this.host.doThroughputServiceStart(this.serviceCount,
MinimalTestService.class, this.host.buildMinimalTestState(), caps, null);
List<URI> statsUris = new ArrayList<>();
for (Service s : services) {
statsUris.add(UriUtils.buildStatsUri(s.getUri()));
}
// guarantee at least a few maintenance intervals have passed.
Thread.sleep(maintenanceIntervalMillis * 10);
// Let's verify now that all of the services have stopped by now.
this.host.waitFor(
"Service stats did not get updated",
() -> {
int pausedCount = 0;
Map<URI, ServiceStats> allStats = this.host.getServiceState(null,
ServiceStats.class, statsUris);
for (ServiceStats sStats : allStats.values()) {
ServiceStat pauseStat = sStats.entries.get(Service.STAT_NAME_PAUSE_COUNT);
if (pauseStat != null && pauseStat.latestValue > 0) {
pausedCount++;
}
}
if (pausedCount < this.serviceCount) {
this.host.log("Paused Count %d is less than expected %d", pausedCount,
this.serviceCount);
return false;
}
Map<String, ServiceStat> stats = this.host.getServiceStats(this.host
.getManagementServiceUri());
ServiceStat odlCacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_ODL_CACHE_CLEAR_COUNT);
if (odlCacheClears == null || odlCacheClears.latestValue < this.serviceCount) {
this.host.log(
"ODL Service Cache Clears %s were less than expected %d",
odlCacheClears == null ? "null" : String
.valueOf(odlCacheClears.latestValue),
this.serviceCount);
return false;
}
ServiceStat cacheClears = stats
.get(ServiceHostManagementService.STAT_NAME_SERVICE_CACHE_CLEAR_COUNT);
if (cacheClears == null || cacheClears.latestValue < this.serviceCount) {
this.host.log(
"Service Cache Clears %s were less than expected %d",
cacheClears == null ? "null" : String
.valueOf(cacheClears.latestValue),
this.serviceCount);
return false;
}
return true;
});
}
private void patchExampleServices(Map<URI, ExampleServiceState> states, int count)
throws Throwable {
TestContext ctx = this.host.testCreate(states.size() * count);
for (ExampleServiceState st : states.values()) {
for (int i = 0; i < count; i++) {
st.name = "updated" + Utils.getNowMicrosUtc() + "";
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, st.documentSelfLink))
.setCompletion((o, e) -> {
if (e != null) {
logPausedFiles();
ctx.fail(e);
return;
}
ctx.complete();
}).setBody(st);
this.host.send(patch);
}
}
this.host.testWait(ctx);
}
private void logPausedFiles() {
File sandBox = new File(this.host.getStorageSandbox());
File serviceContextIndex = new File(sandBox, ServiceContextIndexService.FILE_PATH);
try {
Files.list(serviceContextIndex.toPath()).forEach((p) -> {
this.host.log("%s", p);
});
} catch (IOException e) {
this.host.log(Level.WARNING, "%s", Utils.toString(e));
}
}
@Test
public void onDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
for (int i = 0; i < this.iterationCount; i++) {
tearDown();
doOnDemandServiceStopCheckWithReadAndWriteAccess();
}
}
private void doOnDemandServiceStopCheckWithReadAndWriteAccess() throws Throwable {
setUp(true);
long maintenanceIntervalMicros = TimeUnit.MILLISECONDS.toMicros(100);
// induce host to stop ON_DEMAND_SERVICE more often by setting maintenance interval short
this.host.setMaintenanceIntervalMicros(maintenanceIntervalMicros);
this.host.setServiceCacheClearDelayMicros(maintenanceIntervalMicros / 2);
this.host.start();
// Start some test services with ServiceOption.ON_DEMAND_LOAD
EnumSet<ServiceOption> caps = EnumSet.of(ServiceOption.PERSISTENCE,
ServiceOption.ON_DEMAND_LOAD,
ServiceOption.FACTORY_ITEM);
MinimalFactoryTestService factoryService = new MinimalFactoryTestService();
factoryService.setChildServiceCaps(caps);
this.host.startServiceAndWait(factoryService, "/service", null);
final double stopCount = getODLStopCountStat() != null ? getODLStopCountStat().latestValue : 0;
// Test DELETE works on ODL service as it works on non-ODL service.
// Delete on non-existent service should fail, and should not leave any side effects behind.
Operation deleteOp = Operation.createDelete(this.host, "/service/foo")
.setBody(new ServiceDocument());
this.host.sendAndWaitExpectFailure(deleteOp);
// create a ON_DEMAND_LOAD service
MinimalTestServiceState initialState = new MinimalTestServiceState();
initialState.id = "foo";
initialState.documentSelfLink = "/foo";
Operation startPost = Operation
.createPost(UriUtils.buildUri(this.host, "/service"))
.setBody(initialState);
this.host.sendAndWaitExpectSuccess(startPost);
String servicePath = "/service/foo";
// wait for the service to be stopped and stat to be populated
// This also verifies that ON_DEMAND_LOAD service will stop while it is idle for some duration
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> this.host.getServiceStage(servicePath) == null
&& getODLStopCountStat() != null
&& getODLStopCountStat().latestValue > stopCount
);
long lastODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
int requestCount = 10;
int requestDelayMills = 40;
// Keep the time right before sending the last request.
// Use this time to check the service was not stopped at this moment. Since we keep
// sending the request with 40ms apart, when last request has sent, service should not
// be stopped(within maintenance window and cacheclear delay).
long beforeLastRequestSentTime = 0;
// send 10 GET request 40ms apart to make service receive GET request during a couple
// of maintenance windows
TestContext testContextForGet = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation get = Operation
.createGet(this.host, servicePath)
.setCompletion(testContextForGet.getCompletion());
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(get);
Thread.sleep(requestDelayMills);
}
testContextForGet.await();
// wait for the service to be stopped
final long beforeLastGetSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return lastODLStopTime < currentStopTime
&& beforeLastGetSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
long afterGetODLStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
// send 10 update request 40ms apart to make service receive PATCH request during a couple
// of maintenance windows
TestContext ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
Operation patch = createMinimalTestServicePatch(servicePath, ctx);
beforeLastRequestSentTime = Utils.getNowMicrosUtc();
this.host.send(patch);
Thread.sleep(requestDelayMills);
}
ctx.await();
// wait for the service to be stopped
final long beforeLastPatchSentTime = beforeLastRequestSentTime;
this.host.waitFor("Waiting ON_DEMAND_LOAD service to be stopped",
() -> {
long currentStopTime = getODLStopCountStat().lastUpdateMicrosUtc;
return afterGetODLStopTime < currentStopTime
&& beforeLastPatchSentTime < currentStopTime
&& this.host.getServiceStage(servicePath) == null;
}
);
double maintCount = getHostMaintenanceCount();
// issue multiple PATCHs while directly stopping a ODL service to induce collision
// of stop with active requests. First prevent automatic stop of ODL by extending
// cache clear time
this.host.setServiceCacheClearDelayMicros(TimeUnit.DAYS.toMicros(1));
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > maintCount + 1;
});
// first cause a on demand load (start)
Operation patch = createMinimalTestServicePatch(servicePath, null);
this.host.sendAndWaitExpectSuccess(patch);
assertTrue(this.host.getServiceStage(servicePath) == ProcessingStage.AVAILABLE);
requestCount = this.requestCount;
// service is started. issue updates in parallel and then stop service while requests are
// still being issued
ctx = this.host.testCreate(requestCount);
for (int i = 0; i < requestCount; i++) {
patch = createMinimalTestServicePatch(servicePath, ctx);
this.host.send(patch);
if (i == Math.min(10, requestCount / 2)) {
Operation deleteStop = Operation.createDelete(this.host, servicePath)
.addPragmaDirective(Operation.PRAGMA_DIRECTIVE_NO_INDEX_UPDATE);
this.host.send(deleteStop);
}
}
ctx.await();
verifyOnDemandLoadUpdateDeleteContention();
}
void verifyOnDemandLoadUpdateDeleteContention() throws Throwable {
Operation patch;
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
String factoryLink = OnDemandLoadFactoryService.create(this.host);
// before we start service attempt a GET on a ODL service we know does not
// exist. Make sure its handleStart is NOT called (we will fail the POST if handleStart
// is called, with no body)
Operation get = Operation.createGet(UriUtils.buildUri(
this.host, UriUtils.buildUriPath(factoryLink, "does-not-exist")));
this.host.sendAndWaitExpectFailure(get, Operation.STATUS_CODE_NOT_FOUND);
// create another set of services
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
// set aggressive cache clear again so ODL services stop
double nowCount = getHostMaintenanceCount();
this.host.setServiceCacheClearDelayMicros(this.host.getMaintenanceIntervalMicros() / 2);
this.host.waitFor("wait for main.", () -> {
double latestCount = getHostMaintenanceCount();
return latestCount > nowCount + 1;
});
// now patch these services, while we issue deletes. The PATCHs can fail, but not
// the DELETEs
TestContext patchAndDeleteCtx = this.host.testCreate(states.size() * 2);
patchAndDeleteCtx.setTestName("Concurrent PATCH / DELETE on ODL").logBefore();
for (Entry<URI, ExampleServiceState> e : states.entrySet()) {
patch = Operation.createPatch(e.getKey())
.setBody(e.getValue())
.setCompletion((o, ex) -> {
patchAndDeleteCtx.complete();
});
this.host.send(patch);
// in parallel send a DELETE
this.host.send(Operation.createDelete(e.getKey())
.setCompletion(patchAndDeleteCtx.getCompletion()));
}
patchAndDeleteCtx.await();
patchAndDeleteCtx.logAfter();
}
double getHostMaintenanceCount() {
Map<String, ServiceStat> hostStats = this.host.getServiceStats(
UriUtils.buildUri(this.host, ServiceHostManagementService.SELF_LINK));
ServiceStat stat = hostStats.get(Service.STAT_NAME_SERVICE_HOST_MAINTENANCE_COUNT);
if (stat == null) {
return 0.0;
}
return stat.latestValue;
}
Operation createMinimalTestServicePatch(String servicePath, TestContext ctx) {
MinimalTestServiceState body = new MinimalTestServiceState();
body.id = Utils.buildUUID("foo");
Operation patch = Operation
.createPatch(UriUtils.buildUri(this.host, servicePath))
.setBody(body);
if (ctx != null) {
patch.setCompletion(ctx.getCompletion());
}
return patch;
}
@Test
public void onDemandLoadServicePauseWithSubscribersAndStats() throws Throwable {
setUp(false);
// Set memory limit very low to induce service pause/stop.
this.host.setServiceMemoryLimit(ServiceHost.ROOT_PATH, 0.00001);
// Increase the maintenance interval to delay service pause/ stop.
this.host.setMaintenanceIntervalMicros(TimeUnit.SECONDS.toMicros(5));
Consumer<Operation> bodySetter = (o) -> {
ExampleServiceState body = new ExampleServiceState();
body.name = "prefix-" + UUID.randomUUID();
o.setBody(body);
};
// Create one OnDemandLoad Services
String factoryLink = OnDemandLoadFactoryService.create(this.host);
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(
null,
this.serviceCount,
ExampleServiceState.class,
bodySetter,
UriUtils.buildUri(this.host, factoryLink));
TestContext ctx = this.host.testCreate(this.serviceCount);
TestContext notifyCtx = this.host.testCreate(this.serviceCount * 2);
notifyCtx.setTestName("notifications");
// Subscribe to created services
ctx.setTestName("Subscriptions").logBefore();
for (URI serviceUri : states.keySet()) {
Operation subscribe = Operation.createPost(serviceUri)
.setCompletion(ctx.getCompletion())
.setReferer(this.host.getReferer());
this.host.startReliableSubscriptionService(subscribe, (notifyOp) -> {
notifyOp.complete();
notifyCtx.completeIteration();
});
}
this.host.testWait(ctx);
ctx.logAfter();
TestContext firstPatchCtx = this.host.testCreate(this.serviceCount);
firstPatchCtx.setTestName("Initial patch").logBefore();
// do a PATCH, to trigger a notification
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(firstPatchCtx.getCompletion());
this.host.send(patch);
}
this.host.testWait(firstPatchCtx);
firstPatchCtx.logAfter();
// Let's change the maintenance interval to low so that the service pauses.
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.log("Waiting for service pauses after reduced maint. interval");
// Wait for the service to get paused.
this.host.waitFor("Service failed to pause",
() -> {
for (URI uri : states.keySet()) {
if (this.host.getServiceStage(uri.getPath()) != null) {
return false;
}
}
return true;
});
// do a PATCH, after pause, to trigger a resume and another notification
TestContext patchCtx = this.host.testCreate(this.serviceCount);
patchCtx.setTestName("second patch, post pause").logBefore();
for (URI serviceUri : states.keySet()) {
ExampleServiceState st = new ExampleServiceState();
st.name = "firstPatch";
Operation patch = Operation
.createPatch(serviceUri)
.setBody(st)
.setCompletion(patchCtx.getCompletion());
this.host.send(patch);
}
// wait for PATCHs
this.host.testWait(patchCtx);
patchCtx.logAfter();
// Wait for all the patch notifications. This will exit only
// when both notifications have been received.
notifyCtx.logBefore();
this.host.testWait(notifyCtx);
}
private ServiceStat getODLStopCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
return this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_ODL_STOP_COUNT);
}
private ServiceStat getRateLimitOpCountStat() throws Throwable {
URI managementServiceUri = this.host.getManagementServiceUri();
ServiceStat stats = this.host.getServiceStats(managementServiceUri)
.get(ServiceHostManagementService.STAT_NAME_RATE_LIMITED_OP_COUNT);
return stats;
}
@Test
public void thirdPartyClientPost() throws Throwable {
setUp(false);
this.host.waitForServiceAvailable(ExampleService.FACTORY_LINK);
String name = UUID.randomUUID().toString();
ExampleServiceState s = new ExampleServiceState();
s.name = name;
Consumer<Operation> bodySetter = (o) -> {
o.setBody(s);
};
URI factoryURI = UriUtils.buildFactoryUri(this.host, ExampleService.class);
long c = 1;
Map<URI, ExampleServiceState> states = this.host.doFactoryChildServiceStart(null, c,
ExampleServiceState.class, bodySetter, factoryURI);
String contentType = Operation.MEDIA_TYPE_APPLICATION_JSON;
for (ExampleServiceState initialState : states.values()) {
String json = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, initialState.documentSelfLink), contentType, null);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(initialState.name));
}
// Now issue POST with third party client
s.name = UUID.randomUUID().toString();
String body = Utils.toJson(s);
// first use proper content type
String json = this.host.sendWithJavaClient(factoryURI,
Operation.MEDIA_TYPE_APPLICATION_JSON, body);
ExampleServiceState javaClientRsp = Utils.fromJson(json, ExampleServiceState.class);
assertTrue(javaClientRsp.name.equals(s.name));
// POST to a service we know does not exist and verify our request did not get implicitly
// queued, but failed instantly instead
json = this.host.sendWithJavaClient(
UriUtils.extendUri(factoryURI, UUID.randomUUID().toString()),
Operation.MEDIA_TYPE_APPLICATION_JSON, null);
ServiceErrorResponse r = Utils.fromJson(json, ServiceErrorResponse.class);
assertEquals(Operation.STATUS_CODE_NOT_FOUND, r.statusCode);
}
private URI[] buildStatsUris(long serviceCount, List<Service> services) {
URI[] statUris = new URI[(int) serviceCount];
int i = 0;
for (Service s : services) {
statUris[i++] = UriUtils.extendUri(s.getUri(),
ServiceHost.SERVICE_URI_SUFFIX_STATS);
}
return statUris;
}
@Test
public void getAvailableServicesWithOptions() throws Throwable {
setUp(false);
int serviceCount = 5;
this.host.createExampleServices(this.host, serviceCount, Utils.getNowMicrosUtc());
EnumSet<ServiceOption> options = EnumSet.of(ServiceOption.INSTRUMENTATION,
ServiceOption.OWNER_SELECTION, ServiceOption.FACTORY_ITEM);
Operation get = Operation.createGet(this.host.getUri());
final ServiceDocumentQueryResult[] results = new ServiceDocumentQueryResult[1];
get.setCompletion((o, e) -> {
if (e != null) {
this.host.failIteration(e);
return;
}
results[0] = o.getBody(ServiceDocumentQueryResult.class);
this.host.completeIteration();
});
this.host.testStart(1);
this.host.queryServiceUris(options, true, get.clone());
this.host.testWait();
assertEquals(serviceCount, results[0].documentLinks.size());
this.host.testStart(1);
this.host.queryServiceUris(options, false, get.clone());
this.host.testWait();
assertTrue(results[0].documentLinks.size() >= serviceCount);
}
/**
* This test verify the custom Ui path resource of service
**/
@Test
public void testServiceCustomUIPath() throws Throwable {
setUp(false);
String resourcePath = "customUiPath";
// Service with custom path
class CustomUiPathService extends StatelessService {
public static final String SELF_LINK = "/custom";
public CustomUiPathService() {
super();
toggleOption(ServiceOption.HTML_USER_INTERFACE, true);
}
@Override
public ServiceDocument getDocumentTemplate() {
ServiceDocument serviceDocument = new ServiceDocument();
serviceDocument.documentDescription = new ServiceDocumentDescription();
serviceDocument.documentDescription.userInterfaceResourcePath = resourcePath;
return serviceDocument;
}
}
// Starting the CustomUiPathService service
this.host.startServiceAndWait(new CustomUiPathService(), CustomUiPathService.SELF_LINK, null);
String htmlPath = "/user-interface/resources/" + resourcePath + "/custom.html";
// Sending get request for html
String htmlResponse = this.host.sendWithJavaClient(
UriUtils.buildUri(this.host, htmlPath),
Operation.MEDIA_TYPE_TEXT_HTML, null);
assertEquals("<html>customHtml</html>", htmlResponse);
}
@Test
public void testRootUiService() throws Throwable {
setUp(false);
// Stopping the RootNamespaceService
this.host.waitForResponse(Operation
.createDelete(UriUtils.buildUri(this.host, UriUtils.URI_PATH_CHAR)));
class RootUiService extends UiFileContentService {
public static final String SELF_LINK = UriUtils.URI_PATH_CHAR;
}
// Starting the CustomUiService service
this.host.startServiceAndWait(new RootUiService(), RootUiService.SELF_LINK, null);
// Loading the default page
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, RootUiService.SELF_LINK)));
assertEquals("<html><title>Root</title></html>", result.getBodyRaw());
}
@Test
public void testClientSideRouting() throws Throwable {
setUp(false);
class AppUiService extends UiFileContentService {
public static final String SELF_LINK = "/app";
}
// Starting the AppUiService service
AppUiService s = new AppUiService();
this.host.startServiceAndWait(s, AppUiService.SELF_LINK, null);
// Finding the default page file
Path baseResourcePath = Utils.getServiceUiResourcePath(s);
Path baseUriPath = Paths.get(AppUiService.SELF_LINK);
String prefix = baseResourcePath.toString().replace('\\', '/');
Map<Path, String> pathToURIPath = new HashMap<>();
this.host.discoverJarResources(baseResourcePath, s, pathToURIPath, baseUriPath, prefix);
File defaultFile = pathToURIPath.entrySet()
.stream()
.filter((entry) -> {
return entry.getValue().equals(AppUiService.SELF_LINK +
UriUtils.URI_PATH_CHAR + ServiceUriPaths.UI_RESOURCE_DEFAULT_FILE);
})
.map(Map.Entry::getKey)
.findFirst()
.get()
.toFile();
List<String> routes = Arrays.asList("/app/1", "/app/2");
// Starting all route services
for (String route : routes) {
this.host.startServiceAndWait(new FileContentService(defaultFile), route, null);
}
// Loading routes
for (String route : routes) {
Operation result = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, route)));
assertEquals("<html><title>App</title></html>", result.getBodyRaw());
}
// Loading the about page
Operation about = this.host.waitForResponse(Operation
.createGet(UriUtils.buildUri(this.host, AppUiService.SELF_LINK + "/about.html")));
assertEquals("<html><title>About</title></html>", about.getBodyRaw());
}
@Test
public void httpScheme() throws Throwable {
setUp(true);
// SSL config for https
SelfSignedCertificate ssc = new SelfSignedCertificate();
this.host.setCertificateFileReference(ssc.certificate().toURI());
this.host.setPrivateKeyFileReference(ssc.privateKey().toURI());
assertEquals("before starting, scheme is NONE", ServiceHost.HttpScheme.NONE,
this.host.getCurrentHttpScheme());
this.host.setPort(0);
this.host.setSecurePort(0);
this.host.start();
ServiceRequestListener httpListener = this.host.getListener();
ServiceRequestListener httpsListener = this.host.getSecureListener();
assertTrue("http listener should be on", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_AND_HTTPS, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpsListener.stop();
assertTrue("http listener should be on ", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTP_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTP",
this.host.getPublicUri().getScheme().equals("http"));
httpListener.stop();
assertFalse("http listener should be off", httpListener.isListening());
assertFalse("https listener should be off", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.NONE, this.host.getCurrentHttpScheme());
// re-start listener even host is stopped, verify getCurrentHttpScheme only
httpsListener.start(0, ServiceHost.LOOPBACK_ADDRESS);
assertFalse("http listener should be off", httpListener.isListening());
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
httpsListener.stop();
this.host.stop();
// set HTTP port to disabled, restart host. Verify scheme is HTTPS only. We must
// set both HTTP and secure port, to null out the listeners from the host instance.
this.host.setPort(ServiceHost.PORT_VALUE_LISTENER_DISABLED);
this.host.setSecurePort(0);
VerificationHost.createAndAttachSSLClient(this.host);
this.host.start();
httpListener = this.host.getListener();
httpsListener = this.host.getSecureListener();
assertTrue("http listener should be null, default port value set to disabled",
httpListener == null);
assertTrue("https listener should be on", httpsListener.isListening());
assertEquals(ServiceHost.HttpScheme.HTTPS_ONLY, this.host.getCurrentHttpScheme());
assertTrue("public uri scheme should be HTTPS",
this.host.getPublicUri().getScheme().equals("https"));
}
@Test
public void create() throws Throwable {
ServiceHost h = ServiceHost.create("--port=0");
try {
h.start();
h.startDefaultCoreServicesSynchronously();
// Start the example service factory
h.startFactory(ExampleService.class, ExampleService::createFactory);
boolean[] isReady = new boolean[1];
h.registerForServiceAvailability((o, e) -> {
isReady[0] = true;
}, ExampleService.FACTORY_LINK);
Duration timeout = Duration.of(ServiceHost.ServiceHostState.DEFAULT_MAINTENANCE_INTERVAL_MICROS * 5, ChronoUnit.MICROS);
TestContext.waitFor(timeout, () -> {
return isReady[0];
}, "ExampleService did not start");
// verify ExampleService exists
TestRequestSender sender = new TestRequestSender(h);
Operation get = Operation.createGet(h, ExampleService.FACTORY_LINK);
sender.sendAndWait(get);
} finally {
if (h != null) {
h.unregisterRuntimeShutdownHook();
h.stop();
}
}
}
@Test
public void restartAndVerifyManagementService() throws Throwable {
setUp(false);
// management service should be accessible
Operation get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
// restart
this.host.stop();
this.host.setPort(0);
this.host.start();
// verify management service is accessible.
get = Operation.createGet(this.host, ServiceUriPaths.CORE_MANAGEMENT);
this.host.getTestRequestSender().sendAndWait(get);
}
@After
public void tearDown() throws IOException {
LuceneDocumentIndexService.setIndexFileCountThresholdForWriterRefresh(
LuceneDocumentIndexService
.DEFAULT_INDEX_FILE_COUNT_THRESHOLD_FOR_WRITER_REFRESH);
if (this.host == null) {
return;
}
deletePausedFiles();
this.host.tearDown();
}
@Test
public void authorizeRequestOnOwnerSelectionService() throws Throwable {
setUp(true);
this.host.setAuthorizationService(new AuthorizationContextService());
this.host.setAuthorizationEnabled(true);
this.host.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS.toMicros(100));
this.host.start();
AuthTestUtils.setSystemAuthorizationContext(this.host);
// Start Statefull with Non-Persisted service
this.host.startFactory(new AuthCheckService());
this.host.waitForServiceAvailable(AuthCheckService.FACTORY_LINK);
TestRequestSender sender = this.host.getTestRequestSender();
this.host.setSystemAuthorizationContext();
String adminUser = "admin@vmware.com";
String adminPass = "password";
TestContext authCtx = this.host.testCreate(1);
AuthorizationSetupHelper.create()
.setHost(this.host)
.setUserEmail(adminUser)
.setUserPassword(adminPass)
.setIsAdmin(true)
.setCompletion(authCtx.getCompletion())
.start();
authCtx.await();
// create foo
ExampleServiceState exampleFoo = new ExampleServiceState();
exampleFoo.name = "foo";
exampleFoo.documentSelfLink = "foo";
Operation post = Operation.createPost(this.host, AuthCheckService.FACTORY_LINK).setBody(exampleFoo);
ExampleServiceState postResult = sender.sendAndWait(post, ExampleServiceState.class);
URI statsUri = UriUtils.buildUri(this.host, postResult.documentSelfLink);
ServiceStats stats = sender.sendStatsGetAndWait(statsUri);
assertFalse(stats.entries.containsKey(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED));
this.host.resetAuthorizationContext();
TestRequestSender.FailureResponse failureResponse = sender.sendAndWaitFailure(Operation.createGet(this.host, postResult.documentSelfLink));
assertEquals(Operation.STATUS_CODE_FORBIDDEN, failureResponse.op.getStatusCode());
this.host.setSystemAuthorizationContext();
stats = sender.sendStatsGetAndWait(statsUri);
ServiceStat stat = stats.entries.get(AuthCheckService.IS_AUTHORIZE_REQUEST_CALLED);
assertNotNull(stat);
assertEquals(1, stat.latestValue, 0);
this.host.resetAuthorizationContext();
}
}
| ./CrossVul/dataset_final_sorted/CWE-732/java/good_3081_3 |
crossvul-java_data_bad_5809_4 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-200/java/bad_5809_4 |
crossvul-java_data_good_5809_3 | package org.jboss.seam.remoting;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jboss.seam.contexts.Lifecycle;
import org.jboss.seam.contexts.ServletLifecycle;
import org.jboss.seam.core.Manager;
import org.jboss.seam.remoting.messaging.RemoteSubscriber;
import org.jboss.seam.remoting.messaging.SubscriptionRegistry;
import org.jboss.seam.remoting.messaging.SubscriptionRequest;
import org.jboss.seam.util.XML;
import org.jboss.seam.web.ServletContexts;
/**
*
* @author Shane Bryzak
*/
public class SubscriptionHandler extends BaseRequestHandler implements RequestHandler
{
/**
* The entry point for handling a request.
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws Exception
*/
public void handle(HttpServletRequest request, HttpServletResponse response)
throws Exception
{
// We're sending an XML response, so set the response content type to text/xml
response.setContentType("text/xml");
// Parse the incoming request as XML
SAXReader xmlReader = XML.getSafeSaxReader();
Document doc = xmlReader.read(request.getInputStream());
Element env = doc.getRootElement();
Element body = env.element("body");
// First handle any new subscriptions
List<SubscriptionRequest> requests = new ArrayList<SubscriptionRequest>();
List<Element> elements = body.elements("subscribe");
for (Element e : elements)
{
requests.add(new SubscriptionRequest(e.attributeValue("topic")));
}
ServletLifecycle.beginRequest(request);
try
{
ServletContexts.instance().setRequest(request);
Manager.instance().initializeTemporaryConversation();
ServletLifecycle.resumeConversation(request);
for (SubscriptionRequest req : requests)
{
req.subscribe();
}
// Then handle any unsubscriptions
List<String> unsubscribeTokens = new ArrayList<String>();
elements = body.elements("unsubscribe");
for (Element e : elements)
{
unsubscribeTokens.add(e.attributeValue("token"));
}
for (String token : unsubscribeTokens)
{
RemoteSubscriber subscriber = SubscriptionRegistry.instance().
getSubscription(token);
if (subscriber != null)
{
subscriber.unsubscribe();
}
}
}
finally
{
Lifecycle.endRequest();
}
// Package up the response
marshalResponse(requests, response.getOutputStream());
}
private void marshalResponse(List<SubscriptionRequest> requests, OutputStream out)
throws IOException
{
out.write(ENVELOPE_TAG_OPEN);
out.write(BODY_TAG_OPEN);
for (SubscriptionRequest req : requests)
{
req.marshal(out);
}
out.write(BODY_TAG_CLOSE);
out.write(ENVELOPE_TAG_CLOSE);
out.flush();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_5809_3 |
crossvul-java_data_good_4348_3 | /*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(value=RetentionPolicy.RUNTIME)
@Target(value={ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface ResponseRetention {
/**
* Environment property with response retention time, in milliseconds
*/
String time();
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_4348_3 |
crossvul-java_data_good_4188_1 | package org.junit.rules;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt");
assertTrue(createdFiles[0].exists());
}
@Test
public void testTempFolderLocation() throws IOException {
File folderRoot = folder.getRoot();
String tmpRoot = System.getProperty("java.io.tmpdir");
assertTrue(folderRoot.toString().startsWith(tmpRoot));
}
}
@Test
public void tempFolderIsDeleted() {
assertThat(testResult(HasTempFolder.class), isSuccessful());
assertFalse(createdFiles[0].exists());
}
public static class CreatesSubFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolderStringReflection() throws Exception {
String subfolder = "subfolder";
String filename = "a.txt";
// force usage of folder.newFolder(String),
// check is available and works, to avoid a potential NoSuchMethodError with non-recompiled code.
Method method = folder.getClass().getMethod("newFolder", new Class<?>[]{String.class});
createdFiles[0] = (File) method.invoke(folder, subfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, filename));
assertTrue(expectedFile.exists());
}
@Test
public void testUsingTempFolderString() throws IOException {
String subfolder = "subfolder";
String filename = "a.txt";
// this uses newFolder(String), ensure that a single String works
createdFiles[0] = folder.newFolder(subfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, filename));
assertTrue(expectedFile.exists());
}
@Test
public void testUsingTempTreeFolders() throws IOException {
String subfolder = "subfolder";
String anotherfolder = "anotherfolder";
String filename = "a.txt";
createdFiles[0] = folder.newFolder(subfolder, anotherfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, anotherfolder, filename));
assertTrue(expectedFile.exists());
}
private String join(String... folderNames) {
StringBuilder path = new StringBuilder();
for (String folderName : folderNames) {
path.append(File.separator).append(folderName);
}
return path.toString();
}
}
@Test
public void subFolderIsDeleted() {
assertThat(testResult(CreatesSubFolder.class), isSuccessful());
assertFalse(createdFiles[0].exists());
}
public static class CreatesRandomSubFolders {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingRandomTempFolders() throws IOException {
for (int i = 0; i < 20; i++) {
File newFolder = folder.newFolder();
assertThat(Arrays.asList(createdFiles), not(hasItem(newFolder)));
createdFiles[i] = newFolder;
new File(newFolder, "a.txt").createNewFile();
assertTrue(newFolder.exists());
}
}
}
@Test
public void randomSubFoldersAreDeleted() {
assertThat(testResult(CreatesRandomSubFolders.class), isSuccessful());
for (File f : createdFiles) {
assertFalse(f.exists());
}
}
public static class CreatesRandomFiles {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingRandomTempFiles() throws IOException {
for (int i = 0; i < 20; i++) {
File newFile = folder.newFile();
assertThat(Arrays.asList(createdFiles), not(hasItem(newFile)));
createdFiles[i] = newFile;
assertTrue(newFile.exists());
}
}
}
@Test
public void randomFilesAreDeleted() {
assertThat(testResult(CreatesRandomFiles.class), isSuccessful());
for (File f : createdFiles) {
assertFalse(f.exists());
}
}
@Test
public void recursiveDeleteFolderWithOneElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile("a");
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithOneRandomElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile();
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithZeroElements() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
folder.delete();
assertFalse(folder.getRoot().exists());
}
@Test
public void tempFolderIsOnlyAccessibleByOwner() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
Set<String> expectedPermissions = new TreeSet<String>(Arrays.asList("OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE"));
Set<String> actualPermissions = getPosixFilePermissions(folder.getRoot());
assertEquals(expectedPermissions, actualPermissions);
}
private Set<String> getPosixFilePermissions(File root) {
try {
Class<?> pathClass = Class.forName("java.nio.file.Path");
Object linkOptionArray = Array.newInstance(Class.forName("java.nio.file.LinkOption"), 0);
Class<?> filesClass = Class.forName("java.nio.file.Files");
Object path = File.class.getDeclaredMethod("toPath").invoke(root);
Method posixFilePermissionsMethod = filesClass.getDeclaredMethod("getPosixFilePermissions", pathClass, linkOptionArray.getClass());
Set<?> permissions = (Set<?>) posixFilePermissionsMethod.invoke(null, path, linkOptionArray);
SortedSet<String> convertedPermissions = new TreeSet<String>();
for (Object item : permissions) {
convertedPermissions.add(item.toString());
}
return convertedPermissions;
} catch (Exception e) {
throw new AssumptionViolatedException("Test requires at least Java 1.7", e);
}
}
public static class NameClashes {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void fileWithFileClash() throws IOException {
folder.newFile("something.txt");
folder.newFile("something.txt");
}
@Test
public void fileWithFolderTest() throws IOException {
folder.newFolder("dummy");
folder.newFile("dummy");
}
}
@Test
public void nameClashesResultInTestFailures() {
assertThat(testResult(NameClashes.class), failureCountIs(2));
}
private static final String GET_ROOT_DUMMY = "dummy-getRoot";
private static final String NEW_FILE_DUMMY = "dummy-newFile";
private static final String NEW_FOLDER_DUMMY = "dummy-newFolder";
public static class IncorrectUsage {
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testGetRoot() throws IOException {
new File(folder.getRoot(), GET_ROOT_DUMMY).createNewFile();
}
@Test
public void testNewFile() throws IOException {
folder.newFile(NEW_FILE_DUMMY);
}
@Test
public void testNewFolder() throws IOException {
folder.newFolder(NEW_FOLDER_DUMMY);
}
}
@Test
public void incorrectUsageWithoutApplyingTheRuleShouldNotPolluteTheCurrentWorkingDirectory() {
assertThat(testResult(IncorrectUsage.class), failureCountIs(3));
assertFalse("getRoot should have failed early", new File(GET_ROOT_DUMMY).exists());
assertFalse("newFile should have failed early", new File(NEW_FILE_DUMMY).exists());
assertFalse("newFolder should have failed early", new File(NEW_FOLDER_DUMMY).exists());
}
@After
public void cleanCurrentWorkingDirectory() {
new File(GET_ROOT_DUMMY).delete();
new File(NEW_FILE_DUMMY).delete();
new File(NEW_FOLDER_DUMMY).delete();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_4188_1 |
crossvul-java_data_good_5809_1 | package org.jboss.seam.remoting;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.seam.Component;
import org.jboss.seam.ComponentType;
import org.jboss.seam.Seam;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.remoting.WebRemote;
import org.jboss.seam.log.LogProvider;
import org.jboss.seam.log.Logging;
import org.jboss.seam.servlet.ContextualHttpServletRequest;
import org.jboss.seam.util.EJB;
import org.jboss.seam.util.Reflections;
import org.jboss.seam.web.ServletContexts;
/**
* Generates JavaScript interface code.
*
* @author Shane Bryzak
*/
public class InterfaceGenerator extends BaseRequestHandler implements RequestHandler
{
private static final LogProvider log = Logging.getLogProvider(InterfaceGenerator.class);
/**
* Maintain a cache of the accessible fields
*/
private static Map<Class,Set<String>> accessibleProperties = new HashMap<Class,Set<String>>();
/**
* A cache of component interfaces, keyed by component name.
*/
private Map<String,byte[]> interfaceCache = new HashMap<String,byte[]>();
/**
*
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws Exception
*/
public void handle(final HttpServletRequest request, final HttpServletResponse response)
throws Exception
{
new ContextualHttpServletRequest(request)
{
@Override
public void process() throws Exception
{
ServletContexts.instance().setRequest(request);
if (request.getQueryString() == null)
{
throw new ServletException("Invalid request - no component specified");
}
Set<Component> components = new HashSet<Component>();
Set<Type> types = new HashSet<Type>();
response.setContentType("text/javascript");
Enumeration e = request.getParameterNames();
while (e.hasMoreElements())
{
String componentName = ((String) e.nextElement()).trim();
Component component = Component.forName(componentName);
if (component == null)
{
log.error(String.format("Component not found: [%s]", componentName));
throw new ServletException("Invalid request - component not found.");
}
else
{
components.add(component);
}
}
generateComponentInterface(components, response.getOutputStream(), types);
}
}.run();
}
/**
* Generates the JavaScript code required to invoke the methods of a component/s.
*
* @param components Component[] The components to generate javascript for
* @param out OutputStream The OutputStream to write the generated javascript to
* @throws IOException Thrown if there is an error writing to the OutputStream
*/
public void generateComponentInterface(Set<Component> components, OutputStream out, Set<Type> types)
throws IOException
{
for (Component c : components)
{
if (c != null)
{
if (!interfaceCache.containsKey(c.getName()))
{
synchronized (interfaceCache)
{
if (!interfaceCache.containsKey(c.getName()))
{
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
appendComponentSource(bOut, c, types);
interfaceCache.put(c.getName(), bOut.toByteArray());
}
}
}
out.write(interfaceCache.get(c.getName()));
}
}
}
/**
* A helper method, used internally by InterfaceGenerator and also when
* serializing responses. Returns a list of the property names for the specified
* class which should be included in the generated interface for the type.
*
* @param cls Class
* @return List
*/
public static Set<String> getAccessibleProperties(Class cls)
{
/** @todo This is a hack to get the "real" class - find out if there is
an API method in CGLIB that can be used instead */
if (cls.getName().contains("EnhancerByCGLIB"))
cls = cls.getSuperclass();
if (!accessibleProperties.containsKey(cls))
{
synchronized(accessibleProperties)
{
if (!accessibleProperties.containsKey(cls))
{
Set<String> properties = new HashSet<String>();
Class c = cls;
while (c != null && !c.equals(Object.class))
{
for (Field f : c.getDeclaredFields())
{
if (!Modifier.isTransient(f.getModifiers()) &&
!Modifier.isStatic(f.getModifiers()))
{
String fieldName = f.getName().substring(0, 1).toUpperCase() +
f.getName().substring(1);
String getterName = String.format("get%s", fieldName);
String setterName = String.format("set%s", fieldName);
Method getMethod = null;
Method setMethod = null;
try
{
getMethod = c.getMethod(getterName);
}
catch (SecurityException ex)
{}
catch (NoSuchMethodException ex)
{
// it might be an "is" method...
getterName = String.format("is%s", fieldName);
try
{
getMethod = c.getMethod(getterName);
}
catch (NoSuchMethodException ex2)
{ /* don't care */}
}
try
{
setMethod = c.getMethod(setterName, new Class[] {f.getType()});
}
catch (SecurityException ex)
{}
catch (NoSuchMethodException ex)
{ /* don't care */}
if (Modifier.isPublic(f.getModifiers()) ||
(getMethod != null &&
Modifier.isPublic(getMethod.getModifiers()) ||
(setMethod != null &&
Modifier.isPublic(setMethod.getModifiers()))))
{
properties.add(f.getName());
}
}
}
//
for (Method m : c.getDeclaredMethods())
{
if (m.getName().startsWith("get") || m.getName().startsWith("is"))
{
int startIdx = m.getName().startsWith("get") ? 3 : 2;
try
{
c.getMethod(String.format("set%s",
m.getName().substring(startIdx)), m.getReturnType());
}
catch (NoSuchMethodException ex)
{
continue;
}
String propertyName = String.format("%s%s",
Character.toLowerCase(m.getName().charAt(startIdx)),
m.getName().substring(startIdx + 1));
if (!properties.contains(propertyName))
properties.add(propertyName);
}
}
c = c.getSuperclass();
}
accessibleProperties.put(cls, properties);
}
}
}
return accessibleProperties.get(cls);
}
/**
* Appends component interface code to an outputstream for a specified component.
*
* @param out OutputStream The OutputStream to write to
* @param component Component The component to generate an interface for
* @param types Set A list of types that have already been generated for this
* request. If this component has already been generated (i.e. it is in the list)
* then it won't be generated again
* @throws IOException If there is an error writing to the OutputStream.
*/
private void appendComponentSource(OutputStream out, Component component, Set<Type> types)
throws IOException
{
StringBuilder componentSrc = new StringBuilder();
Set<Class> componentTypes = new HashSet<Class>();
if (component.getType().isSessionBean() &&
component.getBusinessInterfaces().size() > 0)
{
for (Class c : component.getBusinessInterfaces())
{
// Use the Local interface
if (c.isAnnotationPresent(EJB.LOCAL))
{
componentTypes.add(c);
break;
}
}
if (componentTypes.isEmpty())
throw new RuntimeException(String.format(
"Type cannot be determined for component [%s]. Please ensure that it has a local interface.", component));
}
else if (component.getType().equals(ComponentType.ENTITY_BEAN))
{
appendTypeSource(out, component.getBeanClass(), types);
return;
}
else if (component.getType().equals(ComponentType.JAVA_BEAN))
{
// Check if any of the methods are annotated with @WebRemote, and if so
// treat it as an "action" component instead of a type component
for (Method m : component.getBeanClass().getDeclaredMethods())
{
if (m.getAnnotation(WebRemote.class) != null)
{
componentTypes.add(component.getBeanClass());
break;
}
}
if (componentTypes.isEmpty())
{
appendTypeSource(out, component.getBeanClass(), types);
return;
}
}
else
{
componentTypes.add(component.getBeanClass());
}
// If types already contains all the component types, then return
boolean foundNew = false;
for (Class type : componentTypes)
{
if (!types.contains(type))
{
foundNew = true;
break;
}
}
if (!foundNew) return;
if (component.getName().contains("."))
{
componentSrc.append("Seam.Remoting.createNamespace('");
componentSrc.append(component.getName().substring(0, component.getName().lastIndexOf('.')));
componentSrc.append("');\n");
}
componentSrc.append("Seam.Remoting.type.");
componentSrc.append(component.getName());
componentSrc.append(" = function() {\n");
componentSrc.append(" this.__callback = new Object();\n");
for (Class type : componentTypes)
{
if (types.contains(type))
{
break;
}
else
{
types.add(type);
for (Method m : type.getDeclaredMethods())
{
if (m.getAnnotation(WebRemote.class) == null) continue;
// Append the return type to the source block
appendTypeSource(out, m.getGenericReturnType(), types);
componentSrc.append(" Seam.Remoting.type.");
componentSrc.append(component.getName());
componentSrc.append(".prototype.");
componentSrc.append(m.getName());
componentSrc.append(" = function(");
// Insert parameters p0..pN
for (int i = 0; i < m.getGenericParameterTypes().length; i++)
{
appendTypeSource(out, m.getGenericParameterTypes()[i], types);
if (i > 0) componentSrc.append(", ");
componentSrc.append("p");
componentSrc.append(i);
}
if (m.getGenericParameterTypes().length > 0) componentSrc.append(", ");
componentSrc.append("callback, exceptionHandler) {\n");
componentSrc.append(" return Seam.Remoting.execute(this, \"");
componentSrc.append(m.getName());
componentSrc.append("\", [");
for (int i = 0; i < m.getParameterTypes().length; i++)
{
if (i > 0) componentSrc.append(", ");
componentSrc.append("p");
componentSrc.append(i);
}
componentSrc.append("], callback, exceptionHandler);\n");
componentSrc.append(" }\n");
}
}
componentSrc.append("}\n");
// Set the component name
componentSrc.append("Seam.Remoting.type.");
componentSrc.append(component.getName());
componentSrc.append(".__name = \"");
componentSrc.append(component.getName());
componentSrc.append("\";\n\n");
// Register the component
componentSrc.append("Seam.Component.register(Seam.Remoting.type.");
componentSrc.append(component.getName());
componentSrc.append(");\n\n");
out.write(componentSrc.toString().getBytes());
}
}
/**
* Append Javascript interface code for a specified class to a block of code.
*
* @param source StringBuilder The code block to append to
* @param type Class The type to generate a Javascript interface for
* @param types Set A list of the types already generated (only include each type once).
*/
private void appendTypeSource(OutputStream out, Type type, Set<Type> types)
throws IOException
{
if (type instanceof Class)
{
Class classType = (Class) type;
if (classType.isArray())
{
appendTypeSource(out, classType.getComponentType(), types);
return;
}
if (classType.getName().startsWith("java.") ||
types.contains(type) || classType.isPrimitive())
return;
// Keep track of which types we've already added
types.add(type);
appendClassSource(out, classType, types);
}
else if (type instanceof ParameterizedType)
{
for (Type t : ((ParameterizedType) type).getActualTypeArguments())
appendTypeSource(out, t, types);
}
}
/**
* Appends the interface code for a non-component class to an OutputStream.
*
* @param out OutputStream
* @param classType Class
* @param types Set
* @throws IOException
*/
private void appendClassSource(OutputStream out, Class classType, Set<Type> types)
throws IOException
{
// Don't generate interfaces for enums
if (classType.isEnum())
return;
StringBuilder typeSource = new StringBuilder();
// Determine whether this class is a component; if so, use its name
// otherwise use its class name.
String componentName = Seam.getComponentName(classType);
if (componentName == null)
componentName = classType.getName();
String typeName = componentName.replace('.', '$');
typeSource.append("Seam.Remoting.type.");
typeSource.append(typeName);
typeSource.append(" = function() {\n");
StringBuilder fields = new StringBuilder();
StringBuilder accessors = new StringBuilder();
StringBuilder mutators = new StringBuilder();
Map<String,String> metadata = new HashMap<String,String>();
String getMethodName = null;
String setMethodName = null;
for ( String propertyName : getAccessibleProperties(classType) )
{
Type propertyType = null;
Field f = null;
try
{
f = classType.getDeclaredField(propertyName);
propertyType = f.getGenericType();
}
catch (NoSuchFieldException ex)
{
setMethodName = String.format("set%s%s",
Character.toUpperCase(propertyName.charAt(0)),
propertyName.substring(1));
try
{
getMethodName = String.format("get%s%s",
Character.toUpperCase(propertyName.charAt(0)),
propertyName.substring(1));
propertyType = classType.getMethod(getMethodName).getGenericReturnType();
}
catch (NoSuchMethodException ex2)
{
try
{
getMethodName = String.format("is%s%s",
Character.toUpperCase(propertyName.charAt(0)),
propertyName.substring(1));
propertyType = classType.getMethod(getMethodName).getGenericReturnType();
}
catch (NoSuchMethodException ex3)
{
// ???
continue;
}
}
}
appendTypeSource(out, propertyType, types);
// Include types referenced by generic declarations
if (propertyType instanceof ParameterizedType)
{
for (Type t : ((ParameterizedType) propertyType).getActualTypeArguments())
{
if (t instanceof Class)
appendTypeSource(out, t, types);
}
}
if (f != null)
{
String fieldName = propertyName.substring(0, 1).toUpperCase() +
propertyName.substring(1);
String getterName = String.format("get%s", fieldName);
String setterName = String.format("set%s", fieldName);
try
{
classType.getMethod(getterName);
getMethodName = getterName;
}
catch (SecurityException ex){}
catch (NoSuchMethodException ex)
{
getterName = String.format("is%s", fieldName);
try
{
if (Modifier.isPublic(classType.getMethod(getterName).getModifiers()))
getMethodName = getterName;
}
catch (NoSuchMethodException ex2)
{ /* don't care */}
}
try
{
if (Modifier.isPublic(classType.getMethod(setterName, f.getType()).getModifiers()))
setMethodName = setterName;
}
catch (SecurityException ex) {}
catch (NoSuchMethodException ex) { /* don't care */}
}
// Construct the list of fields.
if (getMethodName != null || setMethodName != null)
{
metadata.put(propertyName, getFieldType(propertyType));
fields.append(" this.");
fields.append(propertyName);
fields.append(" = undefined;\n");
if (getMethodName != null)
{
accessors.append(" Seam.Remoting.type.");
accessors.append(typeName);
accessors.append(".prototype.");
accessors.append(getMethodName);
accessors.append(" = function() { return this.");
accessors.append(propertyName);
accessors.append("; }\n");
}
if (setMethodName != null)
{
mutators.append(" Seam.Remoting.type.");
mutators.append(typeName);
mutators.append(".prototype.");
mutators.append(setMethodName);
mutators.append(" = function(");
mutators.append(propertyName);
mutators.append(") { this.");
mutators.append(propertyName);
mutators.append(" = ");
mutators.append(propertyName);
mutators.append("; }\n");
}
}
}
typeSource.append(fields);
typeSource.append(accessors);
typeSource.append(mutators);
typeSource.append("}\n\n");
// Append the type name
typeSource.append("Seam.Remoting.type.");
typeSource.append(typeName);
typeSource.append(".__name = \"");
typeSource.append(componentName);
typeSource.append("\";\n");
// Append the metadata
typeSource.append("Seam.Remoting.type.");
typeSource.append(typeName);
typeSource.append(".__metadata = [\n");
boolean first = true;
for (String key : metadata.keySet())
{
if (!first)
typeSource.append(",\n");
typeSource.append(" {field: \"");
typeSource.append(key);
typeSource.append("\", type: \"");
typeSource.append(metadata.get(key));
typeSource.append("\"}");
first = false;
}
typeSource.append("];\n\n");
// Register the type under Seam.Component if it is a component, otherwise
// register it under Seam.Remoting
if (classType.isAnnotationPresent(Name.class))
typeSource.append("Seam.Component.register(Seam.Remoting.type.");
else
typeSource.append("Seam.Remoting.registerType(Seam.Remoting.type.");
typeSource.append(typeName);
typeSource.append(");\n\n");
out.write(typeSource.toString().getBytes());
}
/**
* Returns the remoting "type" for a specified class.
*
* @param type Class
* @return String
*/
protected String getFieldType(Type type)
{
if (type.equals(String.class) ||
(type instanceof Class && ( (Class) type).isEnum()) ||
type.equals(BigInteger.class) || type.equals(BigDecimal.class))
return "str";
else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
return "bool";
else if (type.equals(Short.class) || type.equals(Short.TYPE) ||
type.equals(Integer.class) || type.equals(Integer.TYPE) ||
type.equals(Long.class) || type.equals(Long.TYPE) ||
type.equals(Float.class) || type.equals(Float.TYPE) ||
type.equals(Double.class) || type.equals(Double.TYPE) ||
type.equals(Byte.class) || type.equals(Byte.TYPE))
return "number";
else if (type instanceof Class)
{
Class cls = (Class) type;
if (Date.class.isAssignableFrom(cls) || Calendar.class.isAssignableFrom(cls))
return "date";
else if (cls.isArray())
return "bag";
else if (cls.isAssignableFrom(Map.class))
return "map";
else if (cls.isAssignableFrom(Collection.class))
return "bag";
}
else if (type instanceof ParameterizedType)
{
ParameterizedType pt = (ParameterizedType) type;
if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class) pt.getRawType()))
return "map";
else if (pt.getRawType() instanceof Class && Collection.class.isAssignableFrom((Class) pt.getRawType()))
return "bag";
}
return "bean";
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_5809_1 |
crossvul-java_data_good_4348_5 | /*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.exception;
import org.springframework.http.HttpStatus;
public class RadarCovidServerException extends RuntimeException {
private final HttpStatus httpStatus;
/**
* The Constructor for the Exception class.
*
* @param httpStatus the state of the server
* @param message the message
*/
public RadarCovidServerException(HttpStatus httpStatus, String message) {
super(message);
this.httpStatus = httpStatus;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_4348_5 |
crossvul-java_data_bad_3051_0 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.slaves;
import jenkins.model.Jenkins;
import hudson.Functions;
import hudson.model.Computer;
import hudson.model.User;
import org.jvnet.localizer.Localizable;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
import javax.annotation.Nonnull;
import java.util.Date;
/**
* Represents a cause that puts a {@linkplain Computer#isOffline() computer offline}.
*
* <h2>Views</h2>
* <p>
* {@link OfflineCause} must have <tt>cause.jelly</tt> that renders a cause
* into HTML. This is used to tell users why the node is put offline.
* This view should render a block element like DIV.
*
* @author Kohsuke Kawaguchi
* @since 1.320
*/
@ExportedBean
public abstract class OfflineCause {
protected final long timestamp = System.currentTimeMillis();
/**
* Timestamp in which the event happened.
*
* @since 1.612
*/
@Exported
public long getTimestamp() {
return timestamp;
}
/**
* Same as {@link #getTimestamp()} but in a different type.
*
* @since 1.612
*/
public final @Nonnull Date getTime() {
return new Date(timestamp);
}
/**
* {@link OfflineCause} that renders a static text,
* but without any further UI.
*/
public static class SimpleOfflineCause extends OfflineCause {
public final Localizable description;
/**
* @since 1.571
*/
protected SimpleOfflineCause(Localizable description) {
this.description = description;
}
@Exported(name="description") @Override
public String toString() {
return description.toString();
}
}
public static OfflineCause create(Localizable d) {
if (d==null) return null;
return new SimpleOfflineCause(d);
}
/**
* Caused by unexpected channel termination.
*/
public static class ChannelTermination extends OfflineCause {
@Exported
public final Exception cause;
public ChannelTermination(Exception cause) {
this.cause = cause;
}
public String getShortDescription() {
return cause.toString();
}
@Override public String toString() {
return Messages.OfflineCause_connection_was_broken_(Functions.printThrowable(cause));
}
}
/**
* Caused by failure to launch.
*/
public static class LaunchFailed extends OfflineCause {
@Override
public String toString() {
return Messages.OfflineCause_LaunchFailed();
}
}
/**
* Taken offline by user.
* @since 1.551
*/
public static class UserCause extends SimpleOfflineCause {
private final User user;
public UserCause(User user, String message) {
super(hudson.slaves.Messages._SlaveComputer_DisconnectedBy(
user!=null ? user.getId() : Jenkins.ANONYMOUS.getName(),
message != null ? " : " + message : ""
));
this.user = user;
}
public User getUser() {
return user;
}
}
public static class ByCLI extends UserCause {
@Exported
public final String message;
public ByCLI(String message) {
super(User.current(), message);
this.message = message;
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/bad_3051_0 |
crossvul-java_data_bad_972_0 | package com.fasterxml.jackson.databind.jsontype.impl;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
/**
* Helper class used to encapsulate rules that determine subtypes that
* are invalid to use, even with default typing, mostly due to security
* concerns.
* Used by <code>BeanDeserializerFacotry</code>
*
* @since 2.8.11
*/
public class SubTypeValidator
{
protected final static String PREFIX_SPRING = "org.springframework.";
protected final static String PREFIX_C3P0 = "com.mchange.v2.c3p0.";
/**
* Set of well-known "nasty classes", deserialization of which is considered dangerous
* and should (and is) prevented by default.
*/
protected final static Set<String> DEFAULT_NO_DESER_CLASS_NAMES;
static {
Set<String> s = new HashSet<String>();
// Courtesy of [https://github.com/kantega/notsoserial]:
// (and wrt [databind#1599])
s.add("org.apache.commons.collections.functors.InvokerTransformer");
s.add("org.apache.commons.collections.functors.InstantiateTransformer");
s.add("org.apache.commons.collections4.functors.InvokerTransformer");
s.add("org.apache.commons.collections4.functors.InstantiateTransformer");
s.add("org.codehaus.groovy.runtime.ConvertedClosure");
s.add("org.codehaus.groovy.runtime.MethodClosure");
s.add("org.springframework.beans.factory.ObjectFactory");
s.add("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
s.add("org.apache.xalan.xsltc.trax.TemplatesImpl");
// [databind#1680]: may or may not be problem, take no chance
s.add("com.sun.rowset.JdbcRowSetImpl");
// [databind#1737]; JDK provided
s.add("java.util.logging.FileHandler");
s.add("java.rmi.server.UnicastRemoteObject");
// [databind#1737]; 3rd party
//s.add("org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor"); // deprecated by [databind#1855]
s.add("org.springframework.beans.factory.config.PropertyPathFactoryBean");
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource"); // deprecated by [databind#1931]
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource"); // - "" -
// [databind#1855]: more 3rd party
s.add("org.apache.tomcat.dbcp.dbcp2.BasicDataSource");
s.add("com.sun.org.apache.bcel.internal.util.ClassLoader");
// [databind#2032]: more 3rd party; data exfiltration via xml parsed ext entities
s.add("org.apache.ibatis.parsing.XPathParser");
// [databind#2052]: Jodd-db, with jndi/ldap lookup
s.add("jodd.db.connection.DataSourceConnectionProvider");
// [databind#2058]: Oracle JDBC driver, with jndi/ldap lookup
s.add("oracle.jdbc.connector.OracleManagedConnectionFactory");
s.add("oracle.jdbc.rowset.OracleJDBCRowSet");
// [databind#1899]: more 3rd party
s.add("org.hibernate.jmx.StatisticsService");
s.add("org.apache.ibatis.datasource.jndi.JndiDataSourceFactory");
// [databind#2097]: some 3rd party, one JDK-bundled
s.add("org.slf4j.ext.EventData");
s.add("flex.messaging.util.concurrent.AsynchBeansWorkManagerExecutor");
s.add("com.sun.deploy.security.ruleset.DRSHelper");
s.add("org.apache.axis2.jaxws.spi.handler.HandlerResolverImpl");
// [databind#2186]: yet more 3rd party gadgets
s.add("org.jboss.util.propertyeditor.DocumentEditor");
s.add("org.apache.openjpa.ee.RegistryManagedRuntime");
s.add("org.apache.openjpa.ee.JNDIManagedRuntime");
s.add("org.apache.axis2.transport.jms.JMSOutTransportInfo");
// [databind#2326] (2.7.9.6): one more 3rd party gadget
s.add("com.mysql.cj.jdbc.admin.MiniAdmin");
// [databind#2334]: logback-core
s.add("ch.qos.logback.core.db.DriverManagerConnectionSource");
// [databind#2341]: jdom/jdom2
s.add("org.jdom.transform.XSLTransformer");
s.add("org.jdom2.transform.XSLTransformer");
DEFAULT_NO_DESER_CLASS_NAMES = Collections.unmodifiableSet(s);
}
/**
* Set of class names of types that are never to be deserialized.
*/
protected Set<String> _cfgIllegalClassNames = DEFAULT_NO_DESER_CLASS_NAMES;
private final static SubTypeValidator instance = new SubTypeValidator();
protected SubTypeValidator() { }
public static SubTypeValidator instance() { return instance; }
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
} else if (full.startsWith(PREFIX_C3P0)) {
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
if (full.endsWith("DataSource")) {
break main_check;
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/bad_972_0 |
crossvul-java_data_bad_4347_6 | /*
* Copyright (c) 2020 Gobierno de España
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.radarcovid.config;
import java.util.Arrays;
import org.apache.commons.lang3.math.NumberUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention;
import org.dpppt.backend.sdk.ws.radarcovid.exception.RadarCovidServerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* Aspect in charge of controlling the minimum response time of a service.
*/
@Configuration
@ConditionalOnProperty(name = "application.response.retention.enabled", havingValue = "true", matchIfMissing = true)
public class ResponseRetentionAspectConfiguration {
private static final Logger log = LoggerFactory.getLogger("org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention");
@Autowired
private Environment environment;
@Aspect
@Component
public class ControllerTimeResponseControlAspect {
@Pointcut("@annotation(responseRetention)")
public void annotationPointCutDefinition(ResponseRetention responseRetention){
}
@Around("execution(@org.dpppt.backend.sdk.ws.radarcovid.annotation.ResponseRetention * *..controller..*(..)) && annotationPointCutDefinition(responseRetention)")
public Object logAround(ProceedingJoinPoint joinPoint, ResponseRetention responseRetention) throws Throwable {
log.debug("************************* INIT TIME RESPONSE CONTROL *********************************");
long start = System.currentTimeMillis();
try {
String className = joinPoint.getSignature().getDeclaringTypeName();
String methodName = joinPoint.getSignature().getName();
Object result = joinPoint.proceed();
long elapsedTime = System.currentTimeMillis() - start;
long responseRetentionTimeMillis = getTimeMillis(responseRetention.time());
log.debug("Controller : Controller {}.{} () execution time : {} ms", className, methodName, elapsedTime);
if (elapsedTime < responseRetentionTimeMillis) {
try {
Thread.sleep(responseRetentionTimeMillis - elapsedTime);
} catch (InterruptedException e) {
log.warn("Controller : Controller {}.{} () Thread sleep interrupted", className, methodName);
}
}
elapsedTime = System.currentTimeMillis() - start;
log.debug("Controller : Controller {}.{} () NEW execution time : {} ms", className, methodName, elapsedTime);
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
return result;
} catch (IllegalArgumentException e) {
log.error("Controller : Illegal argument {} in {} ()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getName());
log.debug("************************* END TIME RESPONSE CONTROL **********************************");
throw e;
}
}
private long getTimeMillis(String timeMillisString) {
String stringValue = environment.getProperty(timeMillisString);
if (NumberUtils.isCreatable(stringValue)) {
return Long.parseLong(stringValue);
} else {
throw new RadarCovidServerException(HttpStatus.INTERNAL_SERVER_ERROR,
"Invalid timeMillisString value \"" + timeMillisString + "\" - not found or cannot parse into long");
}
}
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/bad_4347_6 |
crossvul-java_data_bad_3051_1 | /*
* The MIT License
*
* Copyright (c) 2015 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import static org.junit.Assert.*;
import java.io.File;
import jenkins.model.Jenkins;
import hudson.slaves.DumbSlave;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
public class ComputerTest {
@Rule public JenkinsRule j = new JenkinsRule();
@Test
public void discardLogsAfterDeletion() throws Exception {
DumbSlave delete = j.createOnlineSlave(Jenkins.getInstance().getLabelAtom("delete"));
DumbSlave keep = j.createOnlineSlave(Jenkins.getInstance().getLabelAtom("keep"));
File logFile = delete.toComputer().getLogFile();
assertTrue(logFile.exists());
Jenkins.getInstance().removeNode(delete);
assertFalse("Slave log should be deleted", logFile.exists());
assertFalse("Slave log directory should be deleted", logFile.getParentFile().exists());
assertTrue("Slave log should be kept", keep.toComputer().getLogFile().exists());
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/bad_3051_1 |
crossvul-java_data_bad_4348_2 | /*
* Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.backend.sdk.ws.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.jsonwebtoken.Jwts;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.dpppt.backend.sdk.data.gaen.FakeKeyService;
import org.dpppt.backend.sdk.data.gaen.GAENDataService;
import org.dpppt.backend.sdk.model.gaen.*;
import org.dpppt.backend.sdk.ws.radarcovid.annotation.Loggable;
import org.dpppt.backend.sdk.ws.security.ValidateRequest;
import org.dpppt.backend.sdk.ws.security.ValidateRequest.InvalidDateException;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature;
import org.dpppt.backend.sdk.ws.security.signature.ProtoSignature.ProtoSignatureWrapper;
import org.dpppt.backend.sdk.ws.util.ValidationUtils;
import org.dpppt.backend.sdk.ws.util.ValidationUtils.BadBatchReleaseTimeException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.Callable;
@Controller
@RequestMapping("/v1/gaen")
@Tag(name = "GAEN", description = "The GAEN endpoint for the mobile clients")
/**
* The GaenController defines the API endpoints for the mobile clients to access the GAEN functionality of the
* red backend.
* Clients can send new Exposed Keys, or request the existing Exposed Keys.
*/
public class GaenController {
private static final Logger logger = LoggerFactory.getLogger(GaenController.class);
private static final String FAKE_CODE = "112358132134";
private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER =
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
.withZoneUTC().withLocale(Locale.ENGLISH);
// releaseBucketDuration is used to delay the publishing of Exposed Keys by splitting the database up into batches of keys
// in releaseBucketDuration duration. The current batch is never published, only previous batches are published.
private final Duration releaseBucketDuration;
private final Duration requestTime;
private final ValidateRequest validateRequest;
private final ValidationUtils validationUtils;
private final GAENDataService dataService;
private final FakeKeyService fakeKeyService;
private final Duration exposedListCacheControl;
private final PrivateKey secondDayKey;
private final ProtoSignature gaenSigner;
public GaenController(GAENDataService dataService, FakeKeyService fakeKeyService, ValidateRequest validateRequest,
ProtoSignature gaenSigner, ValidationUtils validationUtils, Duration releaseBucketDuration, Duration requestTime,
Duration exposedListCacheControl, PrivateKey secondDayKey) {
this.dataService = dataService;
this.fakeKeyService = fakeKeyService;
this.releaseBucketDuration = releaseBucketDuration;
this.validateRequest = validateRequest;
this.requestTime = requestTime;
this.validationUtils = validationUtils;
this.exposedListCacheControl = exposedListCacheControl;
this.secondDayKey = secondDayKey;
this.gaenSigner = gaenSigner;
}
@PostMapping(value = "/exposed")
@Loggable
@Transactional
@Operation(description = "Send exposed keys to server - includes a fix for the fact that GAEN doesn't give access to the current day's exposed key")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed keys have been stored in the database"),
@ApiResponse(responseCode = "400", description =
"- Invalid base64 encoding in GaenRequest" +
"- negative rolling period" +
"- fake claim with non-fake keys"),
@ApiResponse(responseCode = "403", description = "Authentication failed") })
public @ResponseBody Callable<ResponseEntity<String>> addExposed(
@Valid @RequestBody @Parameter(description = "The GaenRequest contains the SecretKey from the guessed infection date, the infection date itself, and some authentication data to verify the test result") GaenRequest gaenRequest,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server") Object principal) {
var now = Instant.now().toEpochMilli();
if (!this.validateRequest.isValid(principal)) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
List<GaenKey> nonFakeKeys = new ArrayList<>();
for (var key : gaenRequest.getGaenKeys()) {
if (!validationUtils.isValidBase64Key(key.getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (this.validateRequest.isFakeRequest(principal, key)
|| hasNegativeRollingPeriod(key)
|| hasInvalidKeyDate(principal, key)) {
continue;
}
if (key.getRollingPeriod().equals(0)) {
//currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
//default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
//this should not happen
key.setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if (userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
}
nonFakeKeys.add(key);
}
if (principal instanceof Jwt && ((Jwt) principal).containsClaim("fake")
&& ((Jwt) principal).getClaimAsString("fake").equals("1")) {
Jwt token = (Jwt) principal;
if (FAKE_CODE.equals(token.getSubject())) {
logger.info("Claim is fake - subject: {}", token.getSubject());
} else if (!nonFakeKeys.isEmpty()) {
return () -> ResponseEntity.badRequest().body("Claim is fake but list contains non fake keys");
}
}
if (!nonFakeKeys.isEmpty()) {
dataService.upsertExposees(nonFakeKeys);
}
var delayedKeyDateDuration = Duration.of(gaenRequest.getDelayedKeyDate(), GaenUnit.TenMinutes);
var delayedKeyDate = LocalDate.ofInstant(Instant.ofEpochMilli(delayedKeyDateDuration.toMillis()),
ZoneOffset.UTC);
var nowDay = LocalDate.now(ZoneOffset.UTC);
if (delayedKeyDate.isBefore(nowDay.minusDays(1)) || delayedKeyDate.isAfter(nowDay.plusDays(1))) {
return () -> ResponseEntity.badRequest().body("delayedKeyDate date must be between yesterday and tomorrow");
}
var responseBuilder = ResponseEntity.ok();
if (principal instanceof Jwt) {
var originalJWT = (Jwt) principal;
var jwtBuilder = Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(Date.from(Instant.now()))
.setIssuer("dpppt-sdk-backend").setSubject(originalJWT.getSubject())
.setExpiration(Date
.from(delayedKeyDate.atStartOfDay().toInstant(ZoneOffset.UTC).plus(Duration.ofHours(48))))
.claim("scope", "currentDayExposed").claim("delayedKeyDate", gaenRequest.getDelayedKeyDate());
if (originalJWT.containsClaim("fake")) {
jwtBuilder.claim("fake", originalJWT.getClaim("fake"));
}
String jwt = jwtBuilder.signWith(secondDayKey).compact();
responseBuilder.header("Authorization", "Bearer " + jwt);
responseBuilder.header("X-Exposed-Token", "Bearer " + jwt);
}
Callable<ResponseEntity<String>> cb = () -> {
normalizeRequestTime(now);
return responseBuilder.body("OK");
};
return cb;
}
@PostMapping(value = "/exposednextday")
@Loggable
@Transactional
@Operation(description = "Allows the client to send the last exposed key of the infection to the backend server. The JWT must come from a previous call to /exposed")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "The exposed key has been stored in the backend"),
@ApiResponse(responseCode = "400", description =
"- Ivnalid base64 encoded Temporary Exposure Key" +
"- TEK-date does not match delayedKeyDAte claim in Jwt" +
"- TEK has negative rolling period"),
@ApiResponse(responseCode = "403", description = "No delayedKeyDate claim in authentication") })
public @ResponseBody Callable<ResponseEntity<String>> addExposedSecond(
@Valid @RequestBody @Parameter(description = "The last exposed key of the user") GaenSecondDay gaenSecondDay,
@RequestHeader(value = "User-Agent") @Parameter(description = "App Identifier (PackageName/BundleIdentifier) + App-Version + OS (Android/iOS) + OS-Version", example = "ch.ubique.android.starsdk;1.0;iOS;13.3") String userAgent,
@AuthenticationPrincipal @Parameter(description = "JWT token that can be verified by the backend server, must have been created by /v1/gaen/exposed and contain the delayedKeyDate") Object principal) {
var now = Instant.now().toEpochMilli();
if (!validationUtils.isValidBase64Key(gaenSecondDay.getDelayedKey().getKeyData())) {
return () -> new ResponseEntity<>("No valid base64 key", HttpStatus.BAD_REQUEST);
}
if (principal instanceof Jwt && !((Jwt) principal).containsClaim("delayedKeyDate")) {
return () -> ResponseEntity.status(HttpStatus.FORBIDDEN).body("claim does not contain delayedKeyDate");
}
if (principal instanceof Jwt) {
var jwt = (Jwt) principal;
var claimKeyDate = Integer.parseInt(jwt.getClaimAsString("delayedKeyDate"));
if (!gaenSecondDay.getDelayedKey().getRollingStartNumber().equals(claimKeyDate)) {
return () -> ResponseEntity.badRequest().body("keyDate does not match claim keyDate");
}
}
if (!this.validateRequest.isFakeRequest(principal, gaenSecondDay.getDelayedKey())) {
if (gaenSecondDay.getDelayedKey().getRollingPeriod().equals(0)) {
// currently only android seems to send 0 which can never be valid, since a non used key should not be submitted
// default value according to EN is 144, so just set it to that. If we ever get 0 from iOS we should log it, since
// this should not happen
gaenSecondDay.getDelayedKey().setRollingPeriod(GaenKey.GaenKeyDefaultRollingPeriod);
if(userAgent.toLowerCase().contains("ios")) {
logger.error("Received a rolling period of 0 for an iOS User-Agent");
}
} else if(gaenSecondDay.getDelayedKey().getRollingPeriod() < 0) {
return () -> ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Rolling Period MUST NOT be negative.");
}
List<GaenKey> keys = new ArrayList<>();
keys.add(gaenSecondDay.getDelayedKey());
dataService.upsertExposees(keys);
}
return () -> {
normalizeRequestTime(now);
return ResponseEntity.ok().body("OK");
};
}
@GetMapping(value = "/exposed/{keyDate}", produces = "application/zip")
@Loggable
@Operation(description = "Request the exposed key from a given date")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description =
"- invalid starting key date, doesn't point to midnight UTC" +
"- _publishedAfter_ is not at the beginning of a batch release time, currently 2h")})
public @ResponseBody ResponseEntity<byte[]> getExposedKeys(
@PathVariable @Parameter(description = "Requested date for Exposed Keys retrieval, in milliseconds since Unix epoch (1970-01-01). It must indicate the beginning of a TEKRollingPeriod, currently midnight UTC.", example = "1593043200000") long keyDate,
@RequestParam(required = false) @Parameter(description = "Restrict returned Exposed Keys to dates after this parameter. Given in milliseconds since Unix epoch (1970-01-01).", example = "1593043200000") Long publishedafter)
throws BadBatchReleaseTimeException, IOException, InvalidKeyException, SignatureException,
NoSuchAlgorithmException {
if (!validationUtils.isValidKeyDate(keyDate)) {
return ResponseEntity.notFound().build();
}
if (publishedafter != null && !validationUtils.isValidBatchReleaseTime(publishedafter)) {
return ResponseEntity.notFound().build();
}
long now = System.currentTimeMillis();
// calculate exposed until bucket
long publishedUntil = now - (now % releaseBucketDuration.toMillis());
DateTime dateTime = new DateTime(publishedUntil + releaseBucketDuration.toMillis() - 1, DateTimeZone.UTC);
var exposedKeys = dataService.getSortedExposedForKeyDate(keyDate, publishedafter, publishedUntil);
exposedKeys = fakeKeyService.fillUpKeys(exposedKeys, publishedafter, keyDate);
if (exposedKeys.isEmpty()) {
return ResponseEntity.noContent()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.build();
}
ProtoSignatureWrapper payload = gaenSigner.getPayload(exposedKeys);
return ResponseEntity.ok()//.cacheControl(CacheControl.maxAge(exposedListCacheControl))
.header("X-PUBLISHED-UNTIL", Long.toString(publishedUntil))
.header("Expires", RFC1123_DATE_TIME_FORMATTER.print(dateTime))
.body(payload.getZip());
}
@GetMapping(value = "/buckets/{dayDateStr}")
@Loggable
@Operation(description = "Request the available release batch times for a given day")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "zipped export.bin and export.sig of all keys in that interval"),
@ApiResponse(responseCode = "400", description = "invalid starting key date, points outside of the retention range")})
public @ResponseBody ResponseEntity<DayBuckets> getBuckets(
@PathVariable @Parameter(description = "Starting date for exposed key retrieval, as ISO-8601 format", example = "2020-06-27") String dayDateStr) {
var atStartOfDay = LocalDate.parse(dayDateStr).atStartOfDay().toInstant(ZoneOffset.UTC)
.atOffset(ZoneOffset.UTC);
var end = atStartOfDay.plusDays(1);
var now = Instant.now().atOffset(ZoneOffset.UTC);
if (!validationUtils.isDateInRange(atStartOfDay)) {
return ResponseEntity.notFound().build();
}
var relativeUrls = new ArrayList<String>();
var dayBuckets = new DayBuckets();
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
dayBuckets.setDay(dayDateStr).setRelativeUrls(relativeUrls).setDayTimestamp(atStartOfDay.toInstant().toEpochMilli());
while (atStartOfDay.toInstant().toEpochMilli() < Math.min(now.toInstant().toEpochMilli(),
end.toInstant().toEpochMilli())) {
relativeUrls.add(controllerMapping + "/exposed" + "/" + atStartOfDay.toInstant().toEpochMilli());
atStartOfDay = atStartOfDay.plus(this.releaseBucketDuration);
}
return ResponseEntity.ok(dayBuckets);
}
private void normalizeRequestTime(long now) {
long after = Instant.now().toEpochMilli();
long duration = after - now;
try {
Thread.sleep(Math.max(requestTime.minusMillis(duration).toMillis(), 0));
} catch (Exception ex) {
logger.error("Couldn't equalize request time: {}", ex.toString());
}
}
private boolean hasNegativeRollingPeriod(GaenKey key) {
Integer rollingPeriod = key.getRollingPeriod();
if (key.getRollingPeriod() < 0) {
logger.error("Detected key with negative rolling period {}", rollingPeriod);
return true;
} else {
return false;
}
}
private boolean hasInvalidKeyDate(Object principal, GaenKey key) {
try {
this.validateRequest.getKeyDate(principal, key);
}
catch (InvalidDateException invalidDate) {
logger.error(invalidDate.getLocalizedMessage());
return true;
}
return false;
}
@ExceptionHandler({IllegalArgumentException.class, InvalidDateException.class, JsonProcessingException.class,
MethodArgumentNotValidException.class, BadBatchReleaseTimeException.class, DateTimeParseException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> invalidArguments(Exception ex) {
logger.error("Exception ({}): {}", ex.getClass().getSimpleName(), ex.getMessage(), ex);
return ResponseEntity.badRequest().build();
}
} | ./CrossVul/dataset_final_sorted/CWE-200/java/bad_4348_2 |
crossvul-java_data_bad_4188_1 | package org.junit.rules;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt");
assertTrue(createdFiles[0].exists());
}
@Test
public void testTempFolderLocation() throws IOException {
File folderRoot = folder.getRoot();
String tmpRoot = System.getProperty("java.io.tmpdir");
assertTrue(folderRoot.toString().startsWith(tmpRoot));
}
}
@Test
public void tempFolderIsDeleted() {
assertThat(testResult(HasTempFolder.class), isSuccessful());
assertFalse(createdFiles[0].exists());
}
public static class CreatesSubFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolderStringReflection() throws Exception {
String subfolder = "subfolder";
String filename = "a.txt";
// force usage of folder.newFolder(String),
// check is available and works, to avoid a potential NoSuchMethodError with non-recompiled code.
Method method = folder.getClass().getMethod("newFolder", new Class<?>[]{String.class});
createdFiles[0] = (File) method.invoke(folder, subfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, filename));
assertTrue(expectedFile.exists());
}
@Test
public void testUsingTempFolderString() throws IOException {
String subfolder = "subfolder";
String filename = "a.txt";
// this uses newFolder(String), ensure that a single String works
createdFiles[0] = folder.newFolder(subfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, filename));
assertTrue(expectedFile.exists());
}
@Test
public void testUsingTempTreeFolders() throws IOException {
String subfolder = "subfolder";
String anotherfolder = "anotherfolder";
String filename = "a.txt";
createdFiles[0] = folder.newFolder(subfolder, anotherfolder);
new File(createdFiles[0], filename).createNewFile();
File expectedFile = new File(folder.getRoot(), join(subfolder, anotherfolder, filename));
assertTrue(expectedFile.exists());
}
private String join(String... folderNames) {
StringBuilder path = new StringBuilder();
for (String folderName : folderNames) {
path.append(File.separator).append(folderName);
}
return path.toString();
}
}
@Test
public void subFolderIsDeleted() {
assertThat(testResult(CreatesSubFolder.class), isSuccessful());
assertFalse(createdFiles[0].exists());
}
public static class CreatesRandomSubFolders {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingRandomTempFolders() throws IOException {
for (int i = 0; i < 20; i++) {
File newFolder = folder.newFolder();
assertThat(Arrays.asList(createdFiles), not(hasItem(newFolder)));
createdFiles[i] = newFolder;
new File(newFolder, "a.txt").createNewFile();
assertTrue(newFolder.exists());
}
}
}
@Test
public void randomSubFoldersAreDeleted() {
assertThat(testResult(CreatesRandomSubFolders.class), isSuccessful());
for (File f : createdFiles) {
assertFalse(f.exists());
}
}
public static class CreatesRandomFiles {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingRandomTempFiles() throws IOException {
for (int i = 0; i < 20; i++) {
File newFile = folder.newFile();
assertThat(Arrays.asList(createdFiles), not(hasItem(newFile)));
createdFiles[i] = newFile;
assertTrue(newFile.exists());
}
}
}
@Test
public void randomFilesAreDeleted() {
assertThat(testResult(CreatesRandomFiles.class), isSuccessful());
for (File f : createdFiles) {
assertFalse(f.exists());
}
}
@Test
public void recursiveDeleteFolderWithOneElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile("a");
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithOneRandomElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile();
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithZeroElements() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
folder.delete();
assertFalse(folder.getRoot().exists());
}
public static class NameClashes {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void fileWithFileClash() throws IOException {
folder.newFile("something.txt");
folder.newFile("something.txt");
}
@Test
public void fileWithFolderTest() throws IOException {
folder.newFolder("dummy");
folder.newFile("dummy");
}
}
@Test
public void nameClashesResultInTestFailures() {
assertThat(testResult(NameClashes.class), failureCountIs(2));
}
private static final String GET_ROOT_DUMMY = "dummy-getRoot";
private static final String NEW_FILE_DUMMY = "dummy-newFile";
private static final String NEW_FOLDER_DUMMY = "dummy-newFolder";
public static class IncorrectUsage {
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testGetRoot() throws IOException {
new File(folder.getRoot(), GET_ROOT_DUMMY).createNewFile();
}
@Test
public void testNewFile() throws IOException {
folder.newFile(NEW_FILE_DUMMY);
}
@Test
public void testNewFolder() throws IOException {
folder.newFolder(NEW_FOLDER_DUMMY);
}
}
@Test
public void incorrectUsageWithoutApplyingTheRuleShouldNotPolluteTheCurrentWorkingDirectory() {
assertThat(testResult(IncorrectUsage.class), failureCountIs(3));
assertFalse("getRoot should have failed early", new File(GET_ROOT_DUMMY).exists());
assertFalse("newFile should have failed early", new File(NEW_FILE_DUMMY).exists());
assertFalse("newFolder should have failed early", new File(NEW_FOLDER_DUMMY).exists());
}
@After
public void cleanCurrentWorkingDirectory() {
new File(GET_ROOT_DUMMY).delete();
new File(NEW_FILE_DUMMY).delete();
new File(NEW_FOLDER_DUMMY).delete();
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/bad_4188_1 |
crossvul-java_data_good_3043_0 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.saml.common.util;
import org.keycloak.saml.common.ErrorCodes;
import org.keycloak.saml.common.PicketLinkLogger;
import org.keycloak.saml.common.PicketLinkLoggerFactory;
import org.keycloak.saml.common.constants.GeneralConstants;
import org.keycloak.saml.common.constants.JBossSAMLConstants;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
import org.keycloak.saml.common.exceptions.ConfigurationException;
import org.keycloak.saml.common.exceptions.ParsingException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.InputStream;
/**
* Utility for the stax based parser
*
* @author Anil.Saldhana@redhat.com
* @since Feb 8, 2010
*/
public class StaxParserUtil {
private static final PicketLinkLogger logger = PicketLinkLoggerFactory.getLogger();
public static void validate(InputStream doc, InputStream sch) throws ParsingException {
try {
XMLEventReader xmlEventReader = StaxParserUtil.getXMLEventReader(doc);
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(sch));
Validator validator = schema.newValidator();
validator.validate(new StAXSource(xmlEventReader));
} catch (Exception e) {
throw logger.parserException(e);
}
}
/**
* Bypass an entire XML element block from startElement to endElement
*
* @param xmlEventReader
* @param tag Tag of the XML element that we need to bypass
*
* @throws org.keycloak.saml.common.exceptions.ParsingException
*/
public static void bypassElementBlock(XMLEventReader xmlEventReader, String tag) throws ParsingException {
while (xmlEventReader.hasNext()) {
EndElement endElement = getNextEndElement(xmlEventReader);
if (endElement == null)
return;
if (StaxParserUtil.matches(endElement, tag))
return;
}
}
/**
* Advances reader if character whitespace encountered
*
* @param xmlEventReader
* @param xmlEvent
* @return
*/
public static boolean wasWhitespacePeeked(XMLEventReader xmlEventReader, XMLEvent xmlEvent) {
if (xmlEvent.isCharacters()) {
Characters chars = xmlEvent.asCharacters();
String data = chars.getData();
if (data == null || data.trim().equals("")) {
try {
xmlEventReader.nextEvent();
return true;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
return false;
}
/**
* Given an {@code Attribute}, get its trimmed value
*
* @param attribute
*
* @return
*/
public static String getAttributeValue(Attribute attribute) {
String str = trim(attribute.getValue());
return str;
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return
*/
public static String getAttributeValue(StartElement startElement, String tag) {
String result = null;
Attribute attr = startElement.getAttributeByName(new QName(tag));
if (attr != null)
result = getAttributeValue(attr);
return result;
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return false if attribute not set
*/
public static boolean getBooleanAttributeValue(StartElement startElement, String tag) {
return getBooleanAttributeValue(startElement, tag, false);
}
/**
* Get the Attribute value
*
* @param startElement
* @param tag localpart of the qname of the attribute
*
* @return false if attribute not set
*/
public static boolean getBooleanAttributeValue(StartElement startElement, String tag, boolean defaultValue) {
String result = null;
Attribute attr = startElement.getAttributeByName(new QName(tag));
if (attr != null)
result = getAttributeValue(attr);
if (result == null) return defaultValue;
return Boolean.valueOf(result);
}
/**
* Given that the {@code XMLEventReader} is in {@code XMLStreamConstants.START_ELEMENT} mode, we parse into a DOM
* Element
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static Element getDOMElement(XMLEventReader xmlEventReader) throws ParsingException {
Transformer transformer = null;
final String JDK_TRANSFORMER_PROPERTY = "picketlink.jdk.transformer";
boolean useJDKTransformer = Boolean.parseBoolean(SecurityActions.getSystemProperty(JDK_TRANSFORMER_PROPERTY, "false"));
try {
if (useJDKTransformer) {
transformer = TransformerUtil.getTransformer();
} else {
transformer = TransformerUtil.getStaxSourceToDomResultTransformer();
}
Document resultDocument = DocumentUtil.createDocument();
DOMResult domResult = new DOMResult(resultDocument);
Source source = new StAXSource(xmlEventReader);
TransformerUtil.transform(transformer, source, domResult);
Document doc = (Document) domResult.getNode();
return doc.getDocumentElement();
} catch (ConfigurationException e) {
throw logger.parserException(e);
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Get the element text.
*
* @param xmlEventReader
*
* @return A <b>trimmed</b> string value
*
* @throws ParsingException
*/
public static String getElementText(XMLEventReader xmlEventReader) throws ParsingException {
String str = null;
try {
str = xmlEventReader.getElementText().trim();
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return str;
}
/**
* Get the XML event reader
*
* @param is
*
* @return
*/
public static XMLEventReader getXMLEventReader(InputStream is) {
XMLInputFactory xmlInputFactory;
XMLEventReader xmlEventReader = null;
try {
xmlInputFactory = XML_INPUT_FACTORY.get();
xmlEventReader = xmlInputFactory.createXMLEventReader(is);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return xmlEventReader;
}
/**
* Given a {@code Location}, return a formatted string [lineNum,colNum]
*
* @param location
*
* @return
*/
public static String getLineColumnNumber(Location location) {
StringBuilder builder = new StringBuilder("[");
builder.append(location.getLineNumber()).append(",").append(location.getColumnNumber()).append("]");
return builder.toString();
}
/**
* Get the next xml event
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static XMLEvent getNextEvent(XMLEventReader xmlEventReader) throws ParsingException {
try {
return xmlEventReader.nextEvent();
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Get the next {@code StartElement }
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static StartElement getNextStartElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent == null || xmlEvent.isStartElement())
return (StartElement) xmlEvent;
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return null;
}
/**
* Get the next {@code EndElement}
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static EndElement getNextEndElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent == null || xmlEvent.isEndElement())
return (EndElement) xmlEvent;
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
return null;
}
/**
* Return the name of the start element
*
* @param startElement
*
* @return
*/
public static String getStartElementName(StartElement startElement) {
return trim(startElement.getName().getLocalPart());
}
/**
* Return the name of the end element
*
* @param endElement
*
* @return
*/
public static String getEndElementName(EndElement endElement) {
return trim(endElement.getName().getLocalPart());
}
/**
* Given a start element, obtain the xsi:type defined
*
* @param startElement
*
* @return
*
* @throws RuntimeException if xsi:type is missing
*/
public static String getXSITypeValue(StartElement startElement) {
Attribute xsiType = startElement.getAttributeByName(new QName(JBossSAMLURIConstants.XSI_NSURI.get(),
JBossSAMLConstants.TYPE.get()));
if (xsiType == null)
throw logger.parserExpectedXSI(ErrorCodes.EXPECTED_XSI);
return StaxParserUtil.getAttributeValue(xsiType);
}
/**
* Return whether the next event is going to be text
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static boolean hasTextAhead(XMLEventReader xmlEventReader) throws ParsingException {
XMLEvent event = peek(xmlEventReader);
return event.getEventType() == XMLEvent.CHARACTERS;
}
/**
* Match that the start element with the expected tag
*
* @param startElement
* @param tag
*
* @return boolean if the tags match
*/
public static boolean matches(StartElement startElement, String tag) {
String elementTag = getStartElementName(startElement);
return tag.equals(elementTag);
}
/**
* Match that the end element with the expected tag
*
* @param endElement
* @param tag
*
* @return boolean if the tags match
*/
public static boolean matches(EndElement endElement, String tag) {
String elementTag = getEndElementName(endElement);
return tag.equals(elementTag);
}
/**
* Peek at the next event
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static XMLEvent peek(XMLEventReader xmlEventReader) throws ParsingException {
try {
return xmlEventReader.peek();
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Peek the next {@code StartElement }
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static StartElement peekNextStartElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (true) {
XMLEvent xmlEvent = xmlEventReader.peek();
if (xmlEvent == null || xmlEvent.isStartElement())
return (StartElement) xmlEvent;
else
xmlEvent = xmlEventReader.nextEvent();
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Peek the next {@code EndElement}
*
* @param xmlEventReader
*
* @return
*
* @throws ParsingException
*/
public static EndElement peekNextEndElement(XMLEventReader xmlEventReader) throws ParsingException {
try {
while (true) {
XMLEvent xmlEvent = xmlEventReader.peek();
if (xmlEvent == null || xmlEvent.isEndElement())
return (EndElement) xmlEvent;
else
xmlEvent = xmlEventReader.nextEvent();
}
} catch (XMLStreamException e) {
throw logger.parserException(e);
}
}
/**
* Given a string, trim it
*
* @param str
*
* @return
*
* @throws {@code IllegalArgumentException} if the passed str is null
*/
public static final String trim(String str) {
if (str == null)
throw logger.nullArgumentError("String to trim");
return str.trim();
}
/**
* Validate that the start element has the expected tag
*
* @param startElement
* @param tag
*
* @throws RuntimeException mismatch
*/
public static void validate(StartElement startElement, String tag) {
String foundElementTag = getStartElementName(startElement);
if (!tag.equals(foundElementTag))
throw logger.parserExpectedTag(tag, foundElementTag);
}
/**
* Validate that the end element has the expected tag
*
* @param endElement
* @param tag
*
* @throws RuntimeException mismatch
*/
public static void validate(EndElement endElement, String tag) {
String elementTag = getEndElementName(endElement);
if (!tag.equals(elementTag))
throw new RuntimeException(logger.parserExpectedEndTag("</" + tag + ">. Found </" + elementTag + ">"));
}
private static final ThreadLocal<XMLInputFactory> XML_INPUT_FACTORY = new ThreadLocal<XMLInputFactory>() {
@Override
protected XMLInputFactory initialValue() {
return getXMLInputFactory();
}
};
private static XMLInputFactory getXMLInputFactory() {
boolean tccl_jaxp = SystemPropertiesUtil.getSystemProperty(GeneralConstants.TCCL_JAXP, "false")
.equalsIgnoreCase("true");
ClassLoader prevTCCL = SecurityActions.getTCCL();
try {
if (tccl_jaxp) {
SecurityActions.setTCCL(StaxParserUtil.class.getClassLoader());
}
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
return xmlInputFactory;
} finally {
if (tccl_jaxp) {
SecurityActions.setTCCL(prevTCCL);
}
}
}
} | ./CrossVul/dataset_final_sorted/CWE-200/java/good_3043_0 |
crossvul-java_data_good_3051_1 | /*
* The MIT License
*
* Copyright (c) 2015 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.*;
import java.io.File;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import hudson.slaves.OfflineCause;
import jenkins.model.Jenkins;
import hudson.slaves.DumbSlave;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.recipes.LocalData;
public class ComputerTest {
@Rule public JenkinsRule j = new JenkinsRule();
@Test
public void discardLogsAfterDeletion() throws Exception {
DumbSlave delete = j.createOnlineSlave(Jenkins.getInstance().getLabelAtom("delete"));
DumbSlave keep = j.createOnlineSlave(Jenkins.getInstance().getLabelAtom("keep"));
File logFile = delete.toComputer().getLogFile();
assertTrue(logFile.exists());
Jenkins.getInstance().removeNode(delete);
assertFalse("Slave log should be deleted", logFile.exists());
assertFalse("Slave log directory should be deleted", logFile.getParentFile().exists());
assertTrue("Slave log should be kept", keep.toComputer().getLogFile().exists());
}
@Test
public void doNotShowUserDetailsInOfflineCause() throws Exception {
DumbSlave slave = j.createOnlineSlave();
final Computer computer = slave.toComputer();
computer.setTemporarilyOffline(true, new OfflineCause.UserCause(User.get("username"), "msg"));
verifyOfflineCause(computer);
}
@Test @LocalData
public void removeUserDetailsFromOfflineCause() throws Exception {
Computer computer = j.jenkins.getComputer("deserialized");
verifyOfflineCause(computer);
}
private void verifyOfflineCause(Computer computer) throws Exception {
XmlPage page = j.createWebClient().goToXml("computer/" + computer.getName() + "/config.xml");
String content = page.getWebResponse().getContentAsString("UTF-8");
assertThat(content, containsString("temporaryOfflineCause"));
assertThat(content, containsString("<userId>username</userId>"));
assertThat(content, not(containsString("ApiTokenProperty")));
assertThat(content, not(containsString("apiToken")));
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_3051_1 |
crossvul-java_data_good_1545_0 | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.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.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.server.network.protocol.http;
import com.orientechnologies.common.concur.resource.OSharedResourceAbstract;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TimerTask;
/**
* Handles the HTTP sessions such as a real HTTP Server.
*
* @author Luca Garulli
*/
public class OHttpSessionManager extends OSharedResourceAbstract {
private static final OHttpSessionManager instance = new OHttpSessionManager();
private Map<String, OHttpSession> sessions = new HashMap<String, OHttpSession>();
private int expirationTime;
private Random random = new SecureRandom();
protected OHttpSessionManager() {
expirationTime = OGlobalConfiguration.NETWORK_HTTP_SESSION_EXPIRE_TIMEOUT.getValueAsInteger() * 1000;
Orient.instance().scheduleTask(new TimerTask() {
@Override
public void run() {
final int expired = checkSessionsValidity();
if (expired > 0)
OLogManager.instance().debug(this, "Removed %d session because expired", expired);
}
}, expirationTime, expirationTime);
}
public int checkSessionsValidity() {
int expired = 0;
acquireExclusiveLock();
try {
final long now = System.currentTimeMillis();
Entry<String, OHttpSession> s;
for (Iterator<Map.Entry<String, OHttpSession>> it = sessions.entrySet().iterator(); it.hasNext();) {
s = it.next();
if (now - s.getValue().getUpdatedOn() > expirationTime) {
// REMOVE THE SESSION
it.remove();
expired++;
}
}
} finally {
releaseExclusiveLock();
}
return expired;
}
public OHttpSession[] getSessions() {
acquireSharedLock();
try {
return (OHttpSession[]) sessions.values().toArray(new OHttpSession[sessions.size()]);
} finally {
releaseSharedLock();
}
}
public OHttpSession getSession(final String iId) {
acquireSharedLock();
try {
final OHttpSession sess = sessions.get(iId);
if (sess != null)
sess.updateLastUpdatedOn();
return sess;
} finally {
releaseSharedLock();
}
}
public String createSession(final String iDatabaseName, final String iUserName, final String iUserPassword) {
acquireExclusiveLock();
try {
final String id = "OS" + System.currentTimeMillis() + random.nextLong();
sessions.put(id, new OHttpSession(id, iDatabaseName, iUserName, iUserPassword));
return id;
} finally {
releaseExclusiveLock();
}
}
public OHttpSession removeSession(final String iSessionId) {
acquireExclusiveLock();
try {
return sessions.remove(iSessionId);
} finally {
releaseExclusiveLock();
}
}
public int getExpirationTime() {
return expirationTime;
}
public void setExpirationTime(int expirationTime) {
this.expirationTime = expirationTime;
}
public static OHttpSessionManager getInstance() {
return instance;
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_1545_0 |
crossvul-java_data_good_5809_4 | package org.jboss.seam.util;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XML
{
public static Element getRootElement(InputStream stream) throws DocumentException
{
try {
SAXReader saxReader = new SAXReader();
saxReader.setEntityResolver(new DTDEntityResolver());
saxReader.setMergeAdjacentText(true);
return saxReader.read(stream).getRootElement();
} catch (DocumentException e) {
Throwable nested = e.getNestedException();
if (nested!= null) {
if (nested instanceof FileNotFoundException) {
throw new RuntimeException("Can't find schema/DTD reference: " +
nested.getMessage(), e);
} else if (nested instanceof UnknownHostException) {
throw new RuntimeException("Cannot connect to host from schema/DTD reference: " +
nested.getMessage() +
" - check that your schema/DTD reference is current", e);
}
}
throw e;
}
}
/**
* Parses an XML document safely, as to not resolve any external DTDs
*/
public static Element getRootElementSafely(InputStream stream)
throws DocumentException
{
SAXReader saxReader = new SAXReader();
saxReader.setEntityResolver(new NullEntityResolver());
saxReader.setMergeAdjacentText(true);
return saxReader.read(stream).getRootElement();
}
public static class NullEntityResolver
implements EntityResolver
{
private static final byte[] empty = new byte[0];
public InputSource resolveEntity(String systemId, String publicId)
throws SAXException,
IOException
{
return new InputSource(new ByteArrayInputStream(empty));
}
}
/**
* Get safe SaxReader with doctype feature disabled
* @see http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
* @return
* @throws Exception
*/
public static SAXReader getSafeSaxReader() throws Exception
{
SAXReader xmlReader = new SAXReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
return xmlReader;
}
}
| ./CrossVul/dataset_final_sorted/CWE-200/java/good_5809_4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.