id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27,900 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerRunner.java | RuntimeManagerRunner.cleanState | protected void cleanState(
String topologyName,
SchedulerStateManagerAdaptor statemgr) throws TopologyRuntimeManagementException {
LOG.fine("Cleaning up topology state");
Boolean result;
result = statemgr.deleteTMasterLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear TMaster location. Check whether TMaster set it correctly.");
}
result = statemgr.deleteMetricsCacheLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear MetricsCache location. Check whether MetricsCache set it correctly.");
}
result = statemgr.deletePackingPlan(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear packing plan. Check whether Launcher set it correctly.");
}
result = statemgr.deletePhysicalPlan(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear physical plan. Check whether TMaster set it correctly.");
}
result = statemgr.deleteSchedulerLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear scheduler location. Check whether Scheduler set it correctly.");
}
result = statemgr.deleteLocks(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to delete locks. It's possible that the topology never created any.");
}
result = statemgr.deleteExecutionState(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear execution state");
}
// Set topology def at last since we determine whether a topology is running
// by checking the existence of topology def
result = statemgr.deleteTopology(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear topology definition");
}
LOG.fine("Cleaned up topology state");
} | java | protected void cleanState(
String topologyName,
SchedulerStateManagerAdaptor statemgr) throws TopologyRuntimeManagementException {
LOG.fine("Cleaning up topology state");
Boolean result;
result = statemgr.deleteTMasterLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear TMaster location. Check whether TMaster set it correctly.");
}
result = statemgr.deleteMetricsCacheLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear MetricsCache location. Check whether MetricsCache set it correctly.");
}
result = statemgr.deletePackingPlan(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear packing plan. Check whether Launcher set it correctly.");
}
result = statemgr.deletePhysicalPlan(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear physical plan. Check whether TMaster set it correctly.");
}
result = statemgr.deleteSchedulerLocation(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear scheduler location. Check whether Scheduler set it correctly.");
}
result = statemgr.deleteLocks(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to delete locks. It's possible that the topology never created any.");
}
result = statemgr.deleteExecutionState(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear execution state");
}
// Set topology def at last since we determine whether a topology is running
// by checking the existence of topology def
result = statemgr.deleteTopology(topologyName);
if (result == null || !result) {
throw new TopologyRuntimeManagementException(
"Failed to clear topology definition");
}
LOG.fine("Cleaned up topology state");
} | [
"protected",
"void",
"cleanState",
"(",
"String",
"topologyName",
",",
"SchedulerStateManagerAdaptor",
"statemgr",
")",
"throws",
"TopologyRuntimeManagementException",
"{",
"LOG",
".",
"fine",
"(",
"\"Cleaning up topology state\"",
")",
";",
"Boolean",
"result",
";",
"result",
"=",
"statemgr",
".",
"deleteTMasterLocation",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear TMaster location. Check whether TMaster set it correctly.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deleteMetricsCacheLocation",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear MetricsCache location. Check whether MetricsCache set it correctly.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deletePackingPlan",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear packing plan. Check whether Launcher set it correctly.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deletePhysicalPlan",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear physical plan. Check whether TMaster set it correctly.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deleteSchedulerLocation",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear scheduler location. Check whether Scheduler set it correctly.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deleteLocks",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to delete locks. It's possible that the topology never created any.\"",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"deleteExecutionState",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear execution state\"",
")",
";",
"}",
"// Set topology def at last since we determine whether a topology is running",
"// by checking the existence of topology def",
"result",
"=",
"statemgr",
".",
"deleteTopology",
"(",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"TopologyRuntimeManagementException",
"(",
"\"Failed to clear topology definition\"",
")",
";",
"}",
"LOG",
".",
"fine",
"(",
"\"Cleaned up topology state\"",
")",
";",
"}"
] | Clean all states of a heron topology
1. Topology def and ExecutionState are required to exist to delete
2. TMasterLocation, SchedulerLocation and PhysicalPlan may not exist to delete | [
"Clean",
"all",
"states",
"of",
"a",
"heron",
"topology",
"1",
".",
"Topology",
"def",
"and",
"ExecutionState",
"are",
"required",
"to",
"exist",
"to",
"delete",
"2",
".",
"TMasterLocation",
"SchedulerLocation",
"and",
"PhysicalPlan",
"may",
"not",
"exist",
"to",
"delete"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/RuntimeManagerRunner.java#L338-L396 |
27,901 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java | FirstFitDecreasingPacking.pack | @Override
public PackingPlan pack() {
PackingPlanBuilder planBuilder = newPackingPlanBuilder(null);
// Get the instances using FFD allocation
try {
planBuilder = getFFDAllocation(planBuilder);
} catch (ConstraintViolationException e) {
throw new PackingException("Could not allocate all instances to packing plan", e);
}
return planBuilder.build();
} | java | @Override
public PackingPlan pack() {
PackingPlanBuilder planBuilder = newPackingPlanBuilder(null);
// Get the instances using FFD allocation
try {
planBuilder = getFFDAllocation(planBuilder);
} catch (ConstraintViolationException e) {
throw new PackingException("Could not allocate all instances to packing plan", e);
}
return planBuilder.build();
} | [
"@",
"Override",
"public",
"PackingPlan",
"pack",
"(",
")",
"{",
"PackingPlanBuilder",
"planBuilder",
"=",
"newPackingPlanBuilder",
"(",
"null",
")",
";",
"// Get the instances using FFD allocation",
"try",
"{",
"planBuilder",
"=",
"getFFDAllocation",
"(",
"planBuilder",
")",
";",
"}",
"catch",
"(",
"ConstraintViolationException",
"e",
")",
"{",
"throw",
"new",
"PackingException",
"(",
"\"Could not allocate all instances to packing plan\"",
",",
"e",
")",
";",
"}",
"return",
"planBuilder",
".",
"build",
"(",
")",
";",
"}"
] | Get a packing plan using First Fit Decreasing
@return packing plan | [
"Get",
"a",
"packing",
"plan",
"using",
"First",
"Fit",
"Decreasing"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java#L135-L147 |
27,902 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java | FirstFitDecreasingPacking.assignInstancesToContainers | private void assignInstancesToContainers(PackingPlanBuilder planBuilder,
Map<String, Integer> parallelismMap)
throws ConstraintViolationException {
List<ResourceRequirement> resourceRequirements
= getSortedInstances(parallelismMap.keySet());
for (ResourceRequirement resourceRequirement : resourceRequirements) {
String componentName = resourceRequirement.getComponentName();
int numInstance = parallelismMap.get(componentName);
for (int j = 0; j < numInstance; j++) {
placeFFDInstance(planBuilder, componentName);
}
}
} | java | private void assignInstancesToContainers(PackingPlanBuilder planBuilder,
Map<String, Integer> parallelismMap)
throws ConstraintViolationException {
List<ResourceRequirement> resourceRequirements
= getSortedInstances(parallelismMap.keySet());
for (ResourceRequirement resourceRequirement : resourceRequirements) {
String componentName = resourceRequirement.getComponentName();
int numInstance = parallelismMap.get(componentName);
for (int j = 0; j < numInstance; j++) {
placeFFDInstance(planBuilder, componentName);
}
}
} | [
"private",
"void",
"assignInstancesToContainers",
"(",
"PackingPlanBuilder",
"planBuilder",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"parallelismMap",
")",
"throws",
"ConstraintViolationException",
"{",
"List",
"<",
"ResourceRequirement",
">",
"resourceRequirements",
"=",
"getSortedInstances",
"(",
"parallelismMap",
".",
"keySet",
"(",
")",
")",
";",
"for",
"(",
"ResourceRequirement",
"resourceRequirement",
":",
"resourceRequirements",
")",
"{",
"String",
"componentName",
"=",
"resourceRequirement",
".",
"getComponentName",
"(",
")",
";",
"int",
"numInstance",
"=",
"parallelismMap",
".",
"get",
"(",
"componentName",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"numInstance",
";",
"j",
"++",
")",
"{",
"placeFFDInstance",
"(",
"planBuilder",
",",
"componentName",
")",
";",
"}",
"}",
"}"
] | Assigns instances to containers
@param planBuilder existing packing plan
@param parallelismMap component parallelism | [
"Assigns",
"instances",
"to",
"containers"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java#L237-L249 |
27,903 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java | FirstFitDecreasingPacking.placeFFDInstance | private void placeFFDInstance(PackingPlanBuilder planBuilder, String componentName)
throws ConstraintViolationException {
if (this.numContainers == 0) {
planBuilder.updateNumContainers(++numContainers);
}
try {
planBuilder.addInstance(new ContainerIdScorer(), componentName);
} catch (ResourceExceededException e) {
planBuilder.updateNumContainers(++numContainers);
planBuilder.addInstance(numContainers, componentName);
}
} | java | private void placeFFDInstance(PackingPlanBuilder planBuilder, String componentName)
throws ConstraintViolationException {
if (this.numContainers == 0) {
planBuilder.updateNumContainers(++numContainers);
}
try {
planBuilder.addInstance(new ContainerIdScorer(), componentName);
} catch (ResourceExceededException e) {
planBuilder.updateNumContainers(++numContainers);
planBuilder.addInstance(numContainers, componentName);
}
} | [
"private",
"void",
"placeFFDInstance",
"(",
"PackingPlanBuilder",
"planBuilder",
",",
"String",
"componentName",
")",
"throws",
"ConstraintViolationException",
"{",
"if",
"(",
"this",
".",
"numContainers",
"==",
"0",
")",
"{",
"planBuilder",
".",
"updateNumContainers",
"(",
"++",
"numContainers",
")",
";",
"}",
"try",
"{",
"planBuilder",
".",
"addInstance",
"(",
"new",
"ContainerIdScorer",
"(",
")",
",",
"componentName",
")",
";",
"}",
"catch",
"(",
"ResourceExceededException",
"e",
")",
"{",
"planBuilder",
".",
"updateNumContainers",
"(",
"++",
"numContainers",
")",
";",
"planBuilder",
".",
"addInstance",
"(",
"numContainers",
",",
"componentName",
")",
";",
"}",
"}"
] | Assign a particular instance to an existing container or to a new container | [
"Assign",
"a",
"particular",
"instance",
"to",
"an",
"existing",
"container",
"or",
"to",
"a",
"new",
"container"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/binpacking/FirstFitDecreasingPacking.java#L286-L298 |
27,904 | apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/utils/TupleCache.java | TupleCache.getCache | public Map<Integer, List<HeronTuples.HeronTupleSet>> getCache() {
Map<Integer, List<HeronTuples.HeronTupleSet>> res =
new HashMap<>();
for (Map.Entry<Integer, TupleList> entry : cache.entrySet()) {
res.put(entry.getKey(), entry.getValue().getTuplesList());
}
return res;
} | java | public Map<Integer, List<HeronTuples.HeronTupleSet>> getCache() {
Map<Integer, List<HeronTuples.HeronTupleSet>> res =
new HashMap<>();
for (Map.Entry<Integer, TupleList> entry : cache.entrySet()) {
res.put(entry.getKey(), entry.getValue().getTuplesList());
}
return res;
} | [
"public",
"Map",
"<",
"Integer",
",",
"List",
"<",
"HeronTuples",
".",
"HeronTupleSet",
">",
">",
"getCache",
"(",
")",
"{",
"Map",
"<",
"Integer",
",",
"List",
"<",
"HeronTuples",
".",
"HeronTupleSet",
">",
">",
"res",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Integer",
",",
"TupleList",
">",
"entry",
":",
"cache",
".",
"entrySet",
"(",
")",
")",
"{",
"res",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"getTuplesList",
"(",
")",
")",
";",
"}",
"return",
"res",
";",
"}"
] | Modification on Map would not cahnge values in cache | [
"Modification",
"on",
"Map",
"would",
"not",
"cahnge",
"values",
"in",
"cache"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/TupleCache.java#L66-L74 |
27,905 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java | NetworkUtils.readHttpRequestBody | public static byte[] readHttpRequestBody(HttpExchange exchange) {
// Get the length of request body
int contentLength = Integer.parseInt(exchange.getRequestHeaders().getFirst(CONTENT_LENGTH));
if (contentLength <= 0) {
LOG.log(Level.SEVERE, "Failed to read content length http request body: " + contentLength);
return new byte[0];
}
byte[] requestBody = new byte[contentLength];
InputStream is = exchange.getRequestBody();
try {
int off = 0;
int bRead = 0;
while (off != (contentLength - 1)
&& (bRead = is.read(requestBody, off, contentLength - off)) != -1) {
off += bRead;
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read http request body: ", e);
return new byte[0];
} finally {
try {
is.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close InputStream: ", e);
return new byte[0];
}
}
return requestBody;
} | java | public static byte[] readHttpRequestBody(HttpExchange exchange) {
// Get the length of request body
int contentLength = Integer.parseInt(exchange.getRequestHeaders().getFirst(CONTENT_LENGTH));
if (contentLength <= 0) {
LOG.log(Level.SEVERE, "Failed to read content length http request body: " + contentLength);
return new byte[0];
}
byte[] requestBody = new byte[contentLength];
InputStream is = exchange.getRequestBody();
try {
int off = 0;
int bRead = 0;
while (off != (contentLength - 1)
&& (bRead = is.read(requestBody, off, contentLength - off)) != -1) {
off += bRead;
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read http request body: ", e);
return new byte[0];
} finally {
try {
is.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close InputStream: ", e);
return new byte[0];
}
}
return requestBody;
} | [
"public",
"static",
"byte",
"[",
"]",
"readHttpRequestBody",
"(",
"HttpExchange",
"exchange",
")",
"{",
"// Get the length of request body",
"int",
"contentLength",
"=",
"Integer",
".",
"parseInt",
"(",
"exchange",
".",
"getRequestHeaders",
"(",
")",
".",
"getFirst",
"(",
"CONTENT_LENGTH",
")",
")",
";",
"if",
"(",
"contentLength",
"<=",
"0",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to read content length http request body: \"",
"+",
"contentLength",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"byte",
"[",
"]",
"requestBody",
"=",
"new",
"byte",
"[",
"contentLength",
"]",
";",
"InputStream",
"is",
"=",
"exchange",
".",
"getRequestBody",
"(",
")",
";",
"try",
"{",
"int",
"off",
"=",
"0",
";",
"int",
"bRead",
"=",
"0",
";",
"while",
"(",
"off",
"!=",
"(",
"contentLength",
"-",
"1",
")",
"&&",
"(",
"bRead",
"=",
"is",
".",
"read",
"(",
"requestBody",
",",
"off",
",",
"contentLength",
"-",
"off",
")",
")",
"!=",
"-",
"1",
")",
"{",
"off",
"+=",
"bRead",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to read http request body: \"",
",",
"e",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"finally",
"{",
"try",
"{",
"is",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to close InputStream: \"",
",",
"e",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"}",
"return",
"requestBody",
";",
"}"
] | Read the request body of HTTP request from a given HttpExchange
@param exchange the HttpExchange to read from
@return the byte[] in request body, or new byte[0] if failed to read | [
"Read",
"the",
"request",
"body",
"of",
"HTTP",
"request",
"from",
"a",
"given",
"HttpExchange"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L156-L187 |
27,906 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java | NetworkUtils.sendHttpResponse | public static boolean sendHttpResponse(
boolean isSuccess,
HttpExchange exchange,
byte[] response) {
int returnCode = isSuccess ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_UNAVAILABLE;
try {
exchange.sendResponseHeaders(returnCode, response.length);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send response headers: ", e);
return false;
}
OutputStream os = exchange.getResponseBody();
try {
os.write(response);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send http response: ", e);
return false;
} finally {
try {
os.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e);
return false;
}
}
return true;
} | java | public static boolean sendHttpResponse(
boolean isSuccess,
HttpExchange exchange,
byte[] response) {
int returnCode = isSuccess ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_UNAVAILABLE;
try {
exchange.sendResponseHeaders(returnCode, response.length);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send response headers: ", e);
return false;
}
OutputStream os = exchange.getResponseBody();
try {
os.write(response);
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send http response: ", e);
return false;
} finally {
try {
os.close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e);
return false;
}
}
return true;
} | [
"public",
"static",
"boolean",
"sendHttpResponse",
"(",
"boolean",
"isSuccess",
",",
"HttpExchange",
"exchange",
",",
"byte",
"[",
"]",
"response",
")",
"{",
"int",
"returnCode",
"=",
"isSuccess",
"?",
"HttpURLConnection",
".",
"HTTP_OK",
":",
"HttpURLConnection",
".",
"HTTP_UNAVAILABLE",
";",
"try",
"{",
"exchange",
".",
"sendResponseHeaders",
"(",
"returnCode",
",",
"response",
".",
"length",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to send response headers: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"OutputStream",
"os",
"=",
"exchange",
".",
"getResponseBody",
"(",
")",
";",
"try",
"{",
"os",
".",
"write",
"(",
"response",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to send http response: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"try",
"{",
"os",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to close OutputStream: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Send a http response with HTTP_OK return code and response body
@param isSuccess send back HTTP_OK if it is true, otherwise send back HTTP_UNAVAILABLE
@param exchange the HttpExchange to send response
@param response the response the sent back in response body
@return true if we send the response successfully | [
"Send",
"a",
"http",
"response",
"with",
"HTTP_OK",
"return",
"code",
"and",
"response",
"body"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L197-L225 |
27,907 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java | NetworkUtils.sendHttpPostRequest | public static boolean sendHttpPostRequest(HttpURLConnection connection,
String contentType,
byte[] data) {
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
LOG.log(Level.SEVERE, "Failed to set post request: ", e);
return false;
}
if (data.length > 0) {
connection.setRequestProperty(CONTENT_TYPE, contentType);
connection.setRequestProperty(CONTENT_LENGTH, Integer.toString(data.length));
connection.setUseCaches(false);
connection.setDoOutput(true);
OutputStream os = null;
try {
os = connection.getOutputStream();
os.write(data);
os.flush();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send request: ", e);
return false;
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e);
return false;
}
}
}
return true;
} | java | public static boolean sendHttpPostRequest(HttpURLConnection connection,
String contentType,
byte[] data) {
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
LOG.log(Level.SEVERE, "Failed to set post request: ", e);
return false;
}
if (data.length > 0) {
connection.setRequestProperty(CONTENT_TYPE, contentType);
connection.setRequestProperty(CONTENT_LENGTH, Integer.toString(data.length));
connection.setUseCaches(false);
connection.setDoOutput(true);
OutputStream os = null;
try {
os = connection.getOutputStream();
os.write(data);
os.flush();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to send request: ", e);
return false;
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e);
return false;
}
}
}
return true;
} | [
"public",
"static",
"boolean",
"sendHttpPostRequest",
"(",
"HttpURLConnection",
"connection",
",",
"String",
"contentType",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"try",
"{",
"connection",
".",
"setRequestMethod",
"(",
"\"POST\"",
")",
";",
"}",
"catch",
"(",
"ProtocolException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to set post request: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"data",
".",
"length",
">",
"0",
")",
"{",
"connection",
".",
"setRequestProperty",
"(",
"CONTENT_TYPE",
",",
"contentType",
")",
";",
"connection",
".",
"setRequestProperty",
"(",
"CONTENT_LENGTH",
",",
"Integer",
".",
"toString",
"(",
"data",
".",
"length",
")",
")",
";",
"connection",
".",
"setUseCaches",
"(",
"false",
")",
";",
"connection",
".",
"setDoOutput",
"(",
"true",
")",
";",
"OutputStream",
"os",
"=",
"null",
";",
"try",
"{",
"os",
"=",
"connection",
".",
"getOutputStream",
"(",
")",
";",
"os",
".",
"write",
"(",
"data",
")",
";",
"os",
".",
"flush",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to send request: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"try",
"{",
"if",
"(",
"os",
"!=",
"null",
")",
"{",
"os",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to close OutputStream: \"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | Send Http POST Request to a connection with given data in request body
@param connection the connection to send post request to
@param contentType the type of the content to be sent
@param data the data to send in post request body
@return true if success | [
"Send",
"Http",
"POST",
"Request",
"to",
"a",
"connection",
"with",
"given",
"data",
"in",
"request",
"body"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L239-L276 |
27,908 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java | NetworkUtils.readHttpResponse | public static byte[] readHttpResponse(HttpURLConnection connection) {
byte[] res;
try {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
LOG.log(Level.WARNING, "Http Response not OK: " + connection.getResponseCode());
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to get response code", e);
return new byte[0];
}
int responseLength = connection.getContentLength();
if (responseLength <= 0) {
LOG.log(Level.SEVERE, "Response length abnormal: " + responseLength);
return new byte[0];
}
try {
res = new byte[responseLength];
InputStream is = connection.getInputStream();
int off = 0;
int bRead = 0;
while (off != (responseLength - 1)
&& (bRead = is.read(res, off, responseLength - off)) != -1) {
off += bRead;
}
return res;
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read response: ", e);
return new byte[0];
} finally {
try {
connection.getInputStream().close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close InputStream: ", e);
return new byte[0];
}
}
} | java | public static byte[] readHttpResponse(HttpURLConnection connection) {
byte[] res;
try {
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
LOG.log(Level.WARNING, "Http Response not OK: " + connection.getResponseCode());
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to get response code", e);
return new byte[0];
}
int responseLength = connection.getContentLength();
if (responseLength <= 0) {
LOG.log(Level.SEVERE, "Response length abnormal: " + responseLength);
return new byte[0];
}
try {
res = new byte[responseLength];
InputStream is = connection.getInputStream();
int off = 0;
int bRead = 0;
while (off != (responseLength - 1)
&& (bRead = is.read(res, off, responseLength - off)) != -1) {
off += bRead;
}
return res;
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read response: ", e);
return new byte[0];
} finally {
try {
connection.getInputStream().close();
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to close InputStream: ", e);
return new byte[0];
}
}
} | [
"public",
"static",
"byte",
"[",
"]",
"readHttpResponse",
"(",
"HttpURLConnection",
"connection",
")",
"{",
"byte",
"[",
"]",
"res",
";",
"try",
"{",
"if",
"(",
"connection",
".",
"getResponseCode",
"(",
")",
"!=",
"HttpURLConnection",
".",
"HTTP_OK",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"Http Response not OK: \"",
"+",
"connection",
".",
"getResponseCode",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to get response code\"",
",",
"e",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"int",
"responseLength",
"=",
"connection",
".",
"getContentLength",
"(",
")",
";",
"if",
"(",
"responseLength",
"<=",
"0",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Response length abnormal: \"",
"+",
"responseLength",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"try",
"{",
"res",
"=",
"new",
"byte",
"[",
"responseLength",
"]",
";",
"InputStream",
"is",
"=",
"connection",
".",
"getInputStream",
"(",
")",
";",
"int",
"off",
"=",
"0",
";",
"int",
"bRead",
"=",
"0",
";",
"while",
"(",
"off",
"!=",
"(",
"responseLength",
"-",
"1",
")",
"&&",
"(",
"bRead",
"=",
"is",
".",
"read",
"(",
"res",
",",
"off",
",",
"responseLength",
"-",
"off",
")",
")",
"!=",
"-",
"1",
")",
"{",
"off",
"+=",
"bRead",
";",
"}",
"return",
"res",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to read response: \"",
",",
"e",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"finally",
"{",
"try",
"{",
"connection",
".",
"getInputStream",
"(",
")",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to close InputStream: \"",
",",
"e",
")",
";",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"}",
"}"
] | Read http response from a given http connection
@param connection the connection to read response
@return the byte[] in response body, or new byte[0] if failed to read | [
"Read",
"http",
"response",
"from",
"a",
"given",
"http",
"connection"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/NetworkUtils.java#L307-L349 |
27,909 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/TMasterUtils.java | TMasterUtils.sendToTMaster | @VisibleForTesting
public static void sendToTMaster(String command,
String topologyName,
SchedulerStateManagerAdaptor stateManager,
NetworkUtils.TunnelConfig tunnelConfig)
throws TMasterException {
final List<String> empty = new ArrayList<String>();
sendToTMasterWithArguments(command, topologyName, empty, stateManager, tunnelConfig);
} | java | @VisibleForTesting
public static void sendToTMaster(String command,
String topologyName,
SchedulerStateManagerAdaptor stateManager,
NetworkUtils.TunnelConfig tunnelConfig)
throws TMasterException {
final List<String> empty = new ArrayList<String>();
sendToTMasterWithArguments(command, topologyName, empty, stateManager, tunnelConfig);
} | [
"@",
"VisibleForTesting",
"public",
"static",
"void",
"sendToTMaster",
"(",
"String",
"command",
",",
"String",
"topologyName",
",",
"SchedulerStateManagerAdaptor",
"stateManager",
",",
"NetworkUtils",
".",
"TunnelConfig",
"tunnelConfig",
")",
"throws",
"TMasterException",
"{",
"final",
"List",
"<",
"String",
">",
"empty",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"sendToTMasterWithArguments",
"(",
"command",
",",
"topologyName",
",",
"empty",
",",
"stateManager",
",",
"tunnelConfig",
")",
";",
"}"
] | Communicate with TMaster with command
@param command the command requested to TMaster, activate or deactivate. | [
"Communicate",
"with",
"TMaster",
"with",
"command"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/TMasterUtils.java#L55-L63 |
27,910 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/utils/TMasterUtils.java | TMasterUtils.getRuntimeTopologyState | private static TopologyAPI.TopologyState getRuntimeTopologyState(
String topologyName,
SchedulerStateManagerAdaptor statemgr) throws TMasterException {
PhysicalPlans.PhysicalPlan plan = statemgr.getPhysicalPlan(topologyName);
if (plan == null) {
throw new TMasterException(String.format(
"Failed to get physical plan for topology '%s'", topologyName));
}
return plan.getTopology().getState();
} | java | private static TopologyAPI.TopologyState getRuntimeTopologyState(
String topologyName,
SchedulerStateManagerAdaptor statemgr) throws TMasterException {
PhysicalPlans.PhysicalPlan plan = statemgr.getPhysicalPlan(topologyName);
if (plan == null) {
throw new TMasterException(String.format(
"Failed to get physical plan for topology '%s'", topologyName));
}
return plan.getTopology().getState();
} | [
"private",
"static",
"TopologyAPI",
".",
"TopologyState",
"getRuntimeTopologyState",
"(",
"String",
"topologyName",
",",
"SchedulerStateManagerAdaptor",
"statemgr",
")",
"throws",
"TMasterException",
"{",
"PhysicalPlans",
".",
"PhysicalPlan",
"plan",
"=",
"statemgr",
".",
"getPhysicalPlan",
"(",
"topologyName",
")",
";",
"if",
"(",
"plan",
"==",
"null",
")",
"{",
"throw",
"new",
"TMasterException",
"(",
"String",
".",
"format",
"(",
"\"Failed to get physical plan for topology '%s'\"",
",",
"topologyName",
")",
")",
";",
"}",
"return",
"plan",
".",
"getTopology",
"(",
")",
".",
"getState",
"(",
")",
";",
"}"
] | Get current running TopologyState | [
"Get",
"current",
"running",
"TopologyState"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/TMasterUtils.java#L137-L148 |
27,911 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java | RoundRobinPacking.getRoundRobinAllocation | private Map<Integer, List<InstanceId>> getRoundRobinAllocation(
int numContainer, Map<String, Integer> parallelismMap) {
Map<Integer, List<InstanceId>> allocation = new HashMap<>();
int totalInstance = TopologyUtils.getTotalInstance(parallelismMap);
if (numContainer < 1) {
throw new RuntimeException(String.format("Invlaid number of container: %d", numContainer));
} else if (numContainer > totalInstance) {
throw new RuntimeException(
String.format("More containers (%d) allocated than instances (%d).",
numContainer, totalInstance));
}
for (int i = 1; i <= numContainer; ++i) {
allocation.put(i, new ArrayList<>());
}
int index = 1;
int globalTaskIndex = 1;
// To ensure we spread out the big instances first
// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes
List<String> sortedInstances = getSortedRAMComponents(parallelismMap.keySet()).stream()
.map(ResourceRequirement::getComponentName).collect(Collectors.toList());
for (String component : sortedInstances) {
int numInstance = parallelismMap.get(component);
for (int i = 0; i < numInstance; ++i) {
allocation.get(index).add(new InstanceId(component, globalTaskIndex, i));
index = (index == numContainer) ? 1 : index + 1;
globalTaskIndex++;
}
}
return allocation;
} | java | private Map<Integer, List<InstanceId>> getRoundRobinAllocation(
int numContainer, Map<String, Integer> parallelismMap) {
Map<Integer, List<InstanceId>> allocation = new HashMap<>();
int totalInstance = TopologyUtils.getTotalInstance(parallelismMap);
if (numContainer < 1) {
throw new RuntimeException(String.format("Invlaid number of container: %d", numContainer));
} else if (numContainer > totalInstance) {
throw new RuntimeException(
String.format("More containers (%d) allocated than instances (%d).",
numContainer, totalInstance));
}
for (int i = 1; i <= numContainer; ++i) {
allocation.put(i, new ArrayList<>());
}
int index = 1;
int globalTaskIndex = 1;
// To ensure we spread out the big instances first
// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes
List<String> sortedInstances = getSortedRAMComponents(parallelismMap.keySet()).stream()
.map(ResourceRequirement::getComponentName).collect(Collectors.toList());
for (String component : sortedInstances) {
int numInstance = parallelismMap.get(component);
for (int i = 0; i < numInstance; ++i) {
allocation.get(index).add(new InstanceId(component, globalTaskIndex, i));
index = (index == numContainer) ? 1 : index + 1;
globalTaskIndex++;
}
}
return allocation;
} | [
"private",
"Map",
"<",
"Integer",
",",
"List",
"<",
"InstanceId",
">",
">",
"getRoundRobinAllocation",
"(",
"int",
"numContainer",
",",
"Map",
"<",
"String",
",",
"Integer",
">",
"parallelismMap",
")",
"{",
"Map",
"<",
"Integer",
",",
"List",
"<",
"InstanceId",
">",
">",
"allocation",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"int",
"totalInstance",
"=",
"TopologyUtils",
".",
"getTotalInstance",
"(",
"parallelismMap",
")",
";",
"if",
"(",
"numContainer",
"<",
"1",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"Invlaid number of container: %d\"",
",",
"numContainer",
")",
")",
";",
"}",
"else",
"if",
"(",
"numContainer",
">",
"totalInstance",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"More containers (%d) allocated than instances (%d).\"",
",",
"numContainer",
",",
"totalInstance",
")",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"numContainer",
";",
"++",
"i",
")",
"{",
"allocation",
".",
"put",
"(",
"i",
",",
"new",
"ArrayList",
"<>",
"(",
")",
")",
";",
"}",
"int",
"index",
"=",
"1",
";",
"int",
"globalTaskIndex",
"=",
"1",
";",
"// To ensure we spread out the big instances first",
"// Only sorting by RAM here because only RAM can be explicitly capped by JVM processes",
"List",
"<",
"String",
">",
"sortedInstances",
"=",
"getSortedRAMComponents",
"(",
"parallelismMap",
".",
"keySet",
"(",
")",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ResourceRequirement",
"::",
"getComponentName",
")",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"for",
"(",
"String",
"component",
":",
"sortedInstances",
")",
"{",
"int",
"numInstance",
"=",
"parallelismMap",
".",
"get",
"(",
"component",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numInstance",
";",
"++",
"i",
")",
"{",
"allocation",
".",
"get",
"(",
"index",
")",
".",
"add",
"(",
"new",
"InstanceId",
"(",
"component",
",",
"globalTaskIndex",
",",
"i",
")",
")",
";",
"index",
"=",
"(",
"index",
"==",
"numContainer",
")",
"?",
"1",
":",
"index",
"+",
"1",
";",
"globalTaskIndex",
"++",
";",
"}",
"}",
"return",
"allocation",
";",
"}"
] | Get the instances' allocation basing on round robin algorithm
@return containerId -> list of InstanceId belonging to this container | [
"Get",
"the",
"instances",
"allocation",
"basing",
"on",
"round",
"robin",
"algorithm"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java#L363-L395 |
27,912 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java | RoundRobinPacking.validatePackingPlan | private void validatePackingPlan(PackingPlan plan) throws PackingException {
for (PackingPlan.ContainerPlan containerPlan : plan.getContainers()) {
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
// Safe check
if (instancePlan.getResource().getRam().lessThan(MIN_RAM_PER_INSTANCE)) {
throw new PackingException(String.format("Invalid packing plan generated. A minimum of "
+ "%s RAM is required, but InstancePlan for component '%s' has %s",
MIN_RAM_PER_INSTANCE, instancePlan.getComponentName(),
instancePlan.getResource().getRam()));
}
}
}
} | java | private void validatePackingPlan(PackingPlan plan) throws PackingException {
for (PackingPlan.ContainerPlan containerPlan : plan.getContainers()) {
for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) {
// Safe check
if (instancePlan.getResource().getRam().lessThan(MIN_RAM_PER_INSTANCE)) {
throw new PackingException(String.format("Invalid packing plan generated. A minimum of "
+ "%s RAM is required, but InstancePlan for component '%s' has %s",
MIN_RAM_PER_INSTANCE, instancePlan.getComponentName(),
instancePlan.getResource().getRam()));
}
}
}
} | [
"private",
"void",
"validatePackingPlan",
"(",
"PackingPlan",
"plan",
")",
"throws",
"PackingException",
"{",
"for",
"(",
"PackingPlan",
".",
"ContainerPlan",
"containerPlan",
":",
"plan",
".",
"getContainers",
"(",
")",
")",
"{",
"for",
"(",
"PackingPlan",
".",
"InstancePlan",
"instancePlan",
":",
"containerPlan",
".",
"getInstances",
"(",
")",
")",
"{",
"// Safe check",
"if",
"(",
"instancePlan",
".",
"getResource",
"(",
")",
".",
"getRam",
"(",
")",
".",
"lessThan",
"(",
"MIN_RAM_PER_INSTANCE",
")",
")",
"{",
"throw",
"new",
"PackingException",
"(",
"String",
".",
"format",
"(",
"\"Invalid packing plan generated. A minimum of \"",
"+",
"\"%s RAM is required, but InstancePlan for component '%s' has %s\"",
",",
"MIN_RAM_PER_INSTANCE",
",",
"instancePlan",
".",
"getComponentName",
"(",
")",
",",
"instancePlan",
".",
"getResource",
"(",
")",
".",
"getRam",
"(",
")",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Check whether the PackingPlan generated is valid
@param plan The PackingPlan to check
@throws PackingException if it's not a valid plan | [
"Check",
"whether",
"the",
"PackingPlan",
"generated",
"is",
"valid"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/roundrobin/RoundRobinPacking.java#L451-L463 |
27,913 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/packing/Resource.java | Resource.subtractAbsolute | public Resource subtractAbsolute(Resource other) {
double cpuDifference = this.getCpu() - other.getCpu();
double extraCpu = Math.max(0, cpuDifference);
ByteAmount ramDifference = this.getRam().minus(other.getRam());
ByteAmount extraRam = ByteAmount.ZERO.max(ramDifference);
ByteAmount diskDifference = this.getDisk().minus(other.getDisk());
ByteAmount extraDisk = ByteAmount.ZERO.max(diskDifference);
return new Resource(extraCpu, extraRam, extraDisk);
} | java | public Resource subtractAbsolute(Resource other) {
double cpuDifference = this.getCpu() - other.getCpu();
double extraCpu = Math.max(0, cpuDifference);
ByteAmount ramDifference = this.getRam().minus(other.getRam());
ByteAmount extraRam = ByteAmount.ZERO.max(ramDifference);
ByteAmount diskDifference = this.getDisk().minus(other.getDisk());
ByteAmount extraDisk = ByteAmount.ZERO.max(diskDifference);
return new Resource(extraCpu, extraRam, extraDisk);
} | [
"public",
"Resource",
"subtractAbsolute",
"(",
"Resource",
"other",
")",
"{",
"double",
"cpuDifference",
"=",
"this",
".",
"getCpu",
"(",
")",
"-",
"other",
".",
"getCpu",
"(",
")",
";",
"double",
"extraCpu",
"=",
"Math",
".",
"max",
"(",
"0",
",",
"cpuDifference",
")",
";",
"ByteAmount",
"ramDifference",
"=",
"this",
".",
"getRam",
"(",
")",
".",
"minus",
"(",
"other",
".",
"getRam",
"(",
")",
")",
";",
"ByteAmount",
"extraRam",
"=",
"ByteAmount",
".",
"ZERO",
".",
"max",
"(",
"ramDifference",
")",
";",
"ByteAmount",
"diskDifference",
"=",
"this",
".",
"getDisk",
"(",
")",
".",
"minus",
"(",
"other",
".",
"getDisk",
"(",
")",
")",
";",
"ByteAmount",
"extraDisk",
"=",
"ByteAmount",
".",
"ZERO",
".",
"max",
"(",
"diskDifference",
")",
";",
"return",
"new",
"Resource",
"(",
"extraCpu",
",",
"extraRam",
",",
"extraDisk",
")",
";",
"}"
] | Subtracts a given resource from the current resource. The results is never negative. | [
"Subtracts",
"a",
"given",
"resource",
"from",
"the",
"current",
"resource",
".",
"The",
"results",
"is",
"never",
"negative",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/Resource.java#L80-L88 |
27,914 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/packing/Resource.java | Resource.plus | public Resource plus(Resource other) {
double totalCpu = this.getCpu() + other.getCpu();
ByteAmount totalRam = this.getRam().plus(other.getRam());
ByteAmount totalDisk = this.getDisk().plus(other.getDisk());
return new Resource(totalCpu, totalRam, totalDisk);
} | java | public Resource plus(Resource other) {
double totalCpu = this.getCpu() + other.getCpu();
ByteAmount totalRam = this.getRam().plus(other.getRam());
ByteAmount totalDisk = this.getDisk().plus(other.getDisk());
return new Resource(totalCpu, totalRam, totalDisk);
} | [
"public",
"Resource",
"plus",
"(",
"Resource",
"other",
")",
"{",
"double",
"totalCpu",
"=",
"this",
".",
"getCpu",
"(",
")",
"+",
"other",
".",
"getCpu",
"(",
")",
";",
"ByteAmount",
"totalRam",
"=",
"this",
".",
"getRam",
"(",
")",
".",
"plus",
"(",
"other",
".",
"getRam",
"(",
")",
")",
";",
"ByteAmount",
"totalDisk",
"=",
"this",
".",
"getDisk",
"(",
")",
".",
"plus",
"(",
"other",
".",
"getDisk",
"(",
")",
")",
";",
"return",
"new",
"Resource",
"(",
"totalCpu",
",",
"totalRam",
",",
"totalDisk",
")",
";",
"}"
] | Adds a given resource from the current resource. | [
"Adds",
"a",
"given",
"resource",
"from",
"the",
"current",
"resource",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/Resource.java#L93-L98 |
27,915 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/packing/Resource.java | Resource.divideBy | public double divideBy(Resource other) throws RuntimeException {
if (other.getCpu() == 0 || other.getRam().isZero() || other.getDisk().isZero()) {
throw new RuntimeException("Division by 0.");
} else {
double cpuFactor = Math.ceil(this.getCpu() / other.getCpu());
double ramFactor = Math.ceil((double) this.getRam().asBytes() / other.getRam().asBytes());
double diskFactor = Math.ceil((double) this.getDisk().asBytes() / other.getDisk().asBytes());
return Math.max(cpuFactor, Math.max(ramFactor, diskFactor));
}
} | java | public double divideBy(Resource other) throws RuntimeException {
if (other.getCpu() == 0 || other.getRam().isZero() || other.getDisk().isZero()) {
throw new RuntimeException("Division by 0.");
} else {
double cpuFactor = Math.ceil(this.getCpu() / other.getCpu());
double ramFactor = Math.ceil((double) this.getRam().asBytes() / other.getRam().asBytes());
double diskFactor = Math.ceil((double) this.getDisk().asBytes() / other.getDisk().asBytes());
return Math.max(cpuFactor, Math.max(ramFactor, diskFactor));
}
} | [
"public",
"double",
"divideBy",
"(",
"Resource",
"other",
")",
"throws",
"RuntimeException",
"{",
"if",
"(",
"other",
".",
"getCpu",
"(",
")",
"==",
"0",
"||",
"other",
".",
"getRam",
"(",
")",
".",
"isZero",
"(",
")",
"||",
"other",
".",
"getDisk",
"(",
")",
".",
"isZero",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Division by 0.\"",
")",
";",
"}",
"else",
"{",
"double",
"cpuFactor",
"=",
"Math",
".",
"ceil",
"(",
"this",
".",
"getCpu",
"(",
")",
"/",
"other",
".",
"getCpu",
"(",
")",
")",
";",
"double",
"ramFactor",
"=",
"Math",
".",
"ceil",
"(",
"(",
"double",
")",
"this",
".",
"getRam",
"(",
")",
".",
"asBytes",
"(",
")",
"/",
"other",
".",
"getRam",
"(",
")",
".",
"asBytes",
"(",
")",
")",
";",
"double",
"diskFactor",
"=",
"Math",
".",
"ceil",
"(",
"(",
"double",
")",
"this",
".",
"getDisk",
"(",
")",
".",
"asBytes",
"(",
")",
"/",
"other",
".",
"getDisk",
"(",
")",
".",
"asBytes",
"(",
")",
")",
";",
"return",
"Math",
".",
"max",
"(",
"cpuFactor",
",",
"Math",
".",
"max",
"(",
"ramFactor",
",",
"diskFactor",
")",
")",
";",
"}",
"}"
] | Divides a resource by another resource by dividing the CPU, memory and disk values of the resources.
It returns the maximum of the three results. | [
"Divides",
"a",
"resource",
"by",
"another",
"resource",
"by",
"dividing",
"the",
"CPU",
"memory",
"and",
"disk",
"values",
"of",
"the",
"resources",
".",
"It",
"returns",
"the",
"maximum",
"of",
"the",
"three",
"results",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/Resource.java#L104-L113 |
27,916 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/utils/StreamletUtils.java | StreamletUtils.checkNotBlank | public static String checkNotBlank(String text, String errorMessage) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException(errorMessage);
} else {
return text;
}
} | java | public static String checkNotBlank(String text, String errorMessage) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException(errorMessage);
} else {
return text;
}
} | [
"public",
"static",
"String",
"checkNotBlank",
"(",
"String",
"text",
",",
"String",
"errorMessage",
")",
"{",
"if",
"(",
"StringUtils",
".",
"isBlank",
"(",
"text",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"errorMessage",
")",
";",
"}",
"else",
"{",
"return",
"text",
";",
"}",
"}"
] | Verifies not blank text as the utility function.
@param text The text to verify
@param errorMessage The error message
@throws IllegalArgumentException if the requirement fails | [
"Verifies",
"not",
"blank",
"text",
"as",
"the",
"utility",
"function",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/utils/StreamletUtils.java#L47-L53 |
27,917 | apache/incubator-heron | storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java | ConfigUtils.translateConfig | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
// Look at serialization stuff first
doSerializationTranslation(heronConfig);
// Now look at supported apis
doStormTranslation(heronConfig);
doTaskHooksTranslation(heronConfig);
doTopologyLevelTranslation(heronConfig);
return heronConfig;
} | java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
// Look at serialization stuff first
doSerializationTranslation(heronConfig);
// Now look at supported apis
doStormTranslation(heronConfig);
doTaskHooksTranslation(heronConfig);
doTopologyLevelTranslation(heronConfig);
return heronConfig;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"Config",
"translateConfig",
"(",
"Map",
"stormConfig",
")",
"{",
"Config",
"heronConfig",
";",
"if",
"(",
"stormConfig",
"!=",
"null",
")",
"{",
"heronConfig",
"=",
"new",
"Config",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"stormConfig",
")",
";",
"}",
"else",
"{",
"heronConfig",
"=",
"new",
"Config",
"(",
")",
";",
"}",
"// Look at serialization stuff first",
"doSerializationTranslation",
"(",
"heronConfig",
")",
";",
"// Now look at supported apis",
"doStormTranslation",
"(",
"heronConfig",
")",
";",
"doTaskHooksTranslation",
"(",
"heronConfig",
")",
";",
"doTopologyLevelTranslation",
"(",
"heronConfig",
")",
";",
"return",
"heronConfig",
";",
"}"
] | Translate storm config to heron config for topology
@param stormConfig the storm config
@return a heron config | [
"Translate",
"storm",
"config",
"to",
"heron",
"config",
"for",
"topology"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java#L38-L58 |
27,918 | apache/incubator-heron | storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java | ConfigUtils.translateComponentConfig | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateComponentConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
doStormTranslation(heronConfig);
return heronConfig;
} | java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Config translateComponentConfig(Map stormConfig) {
Config heronConfig;
if (stormConfig != null) {
heronConfig = new Config((Map<String, Object>) stormConfig);
} else {
heronConfig = new Config();
}
doStormTranslation(heronConfig);
return heronConfig;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"Config",
"translateComponentConfig",
"(",
"Map",
"stormConfig",
")",
"{",
"Config",
"heronConfig",
";",
"if",
"(",
"stormConfig",
"!=",
"null",
")",
"{",
"heronConfig",
"=",
"new",
"Config",
"(",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"stormConfig",
")",
";",
"}",
"else",
"{",
"heronConfig",
"=",
"new",
"Config",
"(",
")",
";",
"}",
"doStormTranslation",
"(",
"heronConfig",
")",
";",
"return",
"heronConfig",
";",
"}"
] | Translate storm config to heron config for components
@param stormConfig the storm config
@return a heron config | [
"Translate",
"storm",
"config",
"to",
"heron",
"config",
"for",
"components"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java#L65-L77 |
27,919 | apache/incubator-heron | storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java | ConfigUtils.doTopologyLevelTranslation | private static void doTopologyLevelTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ACKER_EXECUTORS)) {
Integer nAckers =
Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_ACKER_EXECUTORS));
if (nAckers > 0) {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATLEAST_ONCE);
} else {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} else {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} | java | private static void doTopologyLevelTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ACKER_EXECUTORS)) {
Integer nAckers =
Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_ACKER_EXECUTORS));
if (nAckers > 0) {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATLEAST_ONCE);
} else {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} else {
org.apache.heron.api.Config.setTopologyReliabilityMode(heronConfig,
org.apache.heron.api.Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} | [
"private",
"static",
"void",
"doTopologyLevelTranslation",
"(",
"Config",
"heronConfig",
")",
"{",
"if",
"(",
"heronConfig",
".",
"containsKey",
"(",
"org",
".",
"apache",
".",
"storm",
".",
"Config",
".",
"TOPOLOGY_ACKER_EXECUTORS",
")",
")",
"{",
"Integer",
"nAckers",
"=",
"Utils",
".",
"getInt",
"(",
"heronConfig",
".",
"get",
"(",
"org",
".",
"apache",
".",
"storm",
".",
"Config",
".",
"TOPOLOGY_ACKER_EXECUTORS",
")",
")",
";",
"if",
"(",
"nAckers",
">",
"0",
")",
"{",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"setTopologyReliabilityMode",
"(",
"heronConfig",
",",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"TopologyReliabilityMode",
".",
"ATLEAST_ONCE",
")",
";",
"}",
"else",
"{",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"setTopologyReliabilityMode",
"(",
"heronConfig",
",",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"TopologyReliabilityMode",
".",
"ATMOST_ONCE",
")",
";",
"}",
"}",
"else",
"{",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"setTopologyReliabilityMode",
"(",
"heronConfig",
",",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"Config",
".",
"TopologyReliabilityMode",
".",
"ATMOST_ONCE",
")",
";",
"}",
"}"
] | Translate topology config.
@param heron the heron config object to receive the results. | [
"Translate",
"topology",
"config",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/org/apache/storm/utils/ConfigUtils.java#L175-L190 |
27,920 | apache/incubator-heron | heron/instance/src/java/org/apache/heron/network/MetricsManagerClient.java | MetricsManagerClient.sendRegisterRequest | private void sendRegisterRequest() {
Metrics.MetricPublisher publisher = Metrics.MetricPublisher.newBuilder().
setHostname(hostname).
setPort(instance.getInfo().getTaskId()).
setComponentName(instance.getInfo().getComponentName()).
setInstanceId(instance.getInstanceId()).
setInstanceIndex(instance.getInfo().getComponentIndex()).
build();
Metrics.MetricPublisherRegisterRequest request =
Metrics.MetricPublisherRegisterRequest.newBuilder().
setPublisher(publisher).
build();
// The timeout would be the reconnect-interval-seconds
sendRequest(request, null,
Metrics.MetricPublisherRegisterResponse.newBuilder(),
systemConfig.getInstanceReconnectMetricsmgrInterval());
} | java | private void sendRegisterRequest() {
Metrics.MetricPublisher publisher = Metrics.MetricPublisher.newBuilder().
setHostname(hostname).
setPort(instance.getInfo().getTaskId()).
setComponentName(instance.getInfo().getComponentName()).
setInstanceId(instance.getInstanceId()).
setInstanceIndex(instance.getInfo().getComponentIndex()).
build();
Metrics.MetricPublisherRegisterRequest request =
Metrics.MetricPublisherRegisterRequest.newBuilder().
setPublisher(publisher).
build();
// The timeout would be the reconnect-interval-seconds
sendRequest(request, null,
Metrics.MetricPublisherRegisterResponse.newBuilder(),
systemConfig.getInstanceReconnectMetricsmgrInterval());
} | [
"private",
"void",
"sendRegisterRequest",
"(",
")",
"{",
"Metrics",
".",
"MetricPublisher",
"publisher",
"=",
"Metrics",
".",
"MetricPublisher",
".",
"newBuilder",
"(",
")",
".",
"setHostname",
"(",
"hostname",
")",
".",
"setPort",
"(",
"instance",
".",
"getInfo",
"(",
")",
".",
"getTaskId",
"(",
")",
")",
".",
"setComponentName",
"(",
"instance",
".",
"getInfo",
"(",
")",
".",
"getComponentName",
"(",
")",
")",
".",
"setInstanceId",
"(",
"instance",
".",
"getInstanceId",
"(",
")",
")",
".",
"setInstanceIndex",
"(",
"instance",
".",
"getInfo",
"(",
")",
".",
"getComponentIndex",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"Metrics",
".",
"MetricPublisherRegisterRequest",
"request",
"=",
"Metrics",
".",
"MetricPublisherRegisterRequest",
".",
"newBuilder",
"(",
")",
".",
"setPublisher",
"(",
"publisher",
")",
".",
"build",
"(",
")",
";",
"// The timeout would be the reconnect-interval-seconds",
"sendRequest",
"(",
"request",
",",
"null",
",",
"Metrics",
".",
"MetricPublisherRegisterResponse",
".",
"newBuilder",
"(",
")",
",",
"systemConfig",
".",
"getInstanceReconnectMetricsmgrInterval",
"(",
")",
")",
";",
"}"
] | Build register request and send to metrics mgr | [
"Build",
"register",
"request",
"and",
"send",
"to",
"metrics",
"mgr"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/instance/src/java/org/apache/heron/network/MetricsManagerClient.java#L160-L177 |
27,921 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java | HttpJsonClient.get | public JsonNode get(Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
byte[] responseData;
try {
if (!NetworkUtils.sendHttpGetRequest(conn)) {
throw new IOException("Failed to send get request to " + endpointURI);
}
// Check the response code
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
responseData = NetworkUtils.readHttpResponse(conn);
} finally {
conn.disconnect();
}
// parse of the json
JsonNode podDefinition;
try {
// read the json data
ObjectMapper mapper = new ObjectMapper();
podDefinition = mapper.readTree(responseData);
} catch (IOException ioe) {
throw new IOException("Failed to parse JSON response from API");
}
return podDefinition;
} | java | public JsonNode get(Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
byte[] responseData;
try {
if (!NetworkUtils.sendHttpGetRequest(conn)) {
throw new IOException("Failed to send get request to " + endpointURI);
}
// Check the response code
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
responseData = NetworkUtils.readHttpResponse(conn);
} finally {
conn.disconnect();
}
// parse of the json
JsonNode podDefinition;
try {
// read the json data
ObjectMapper mapper = new ObjectMapper();
podDefinition = mapper.readTree(responseData);
} catch (IOException ioe) {
throw new IOException("Failed to parse JSON response from API");
}
return podDefinition;
} | [
"public",
"JsonNode",
"get",
"(",
"Integer",
"expectedResponseCode",
")",
"throws",
"IOException",
"{",
"HttpURLConnection",
"conn",
"=",
"getUrlConnection",
"(",
")",
";",
"byte",
"[",
"]",
"responseData",
";",
"try",
"{",
"if",
"(",
"!",
"NetworkUtils",
".",
"sendHttpGetRequest",
"(",
"conn",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to send get request to \"",
"+",
"endpointURI",
")",
";",
"}",
"// Check the response code",
"if",
"(",
"!",
"NetworkUtils",
".",
"checkHttpResponseCode",
"(",
"conn",
",",
"expectedResponseCode",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unexpected response from connection. Expected \"",
"+",
"expectedResponseCode",
"+",
"\" but received \"",
"+",
"conn",
".",
"getResponseCode",
"(",
")",
")",
";",
"}",
"responseData",
"=",
"NetworkUtils",
".",
"readHttpResponse",
"(",
"conn",
")",
";",
"}",
"finally",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"// parse of the json",
"JsonNode",
"podDefinition",
";",
"try",
"{",
"// read the json data",
"ObjectMapper",
"mapper",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"podDefinition",
"=",
"mapper",
".",
"readTree",
"(",
"responseData",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to parse JSON response from API\"",
")",
";",
"}",
"return",
"podDefinition",
";",
"}"
] | Make a GET request to a JSON-based API endpoint
@param expectedResponseCode the response code you expect to get from this endpoint
@return JSON result, the result in the form of a parsed JsonNode | [
"Make",
"a",
"GET",
"request",
"to",
"a",
"JSON",
"-",
"based",
"API",
"endpoint"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java#L56-L88 |
27,922 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java | HttpJsonClient.delete | public void delete(Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
try {
if (!NetworkUtils.sendHttpDeleteRequest(conn)) {
throw new IOException("Failed to send delete request to " + endpointURI);
}
// Check the response code
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
} finally {
conn.disconnect();
}
} | java | public void delete(Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
try {
if (!NetworkUtils.sendHttpDeleteRequest(conn)) {
throw new IOException("Failed to send delete request to " + endpointURI);
}
// Check the response code
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
} finally {
conn.disconnect();
}
} | [
"public",
"void",
"delete",
"(",
"Integer",
"expectedResponseCode",
")",
"throws",
"IOException",
"{",
"HttpURLConnection",
"conn",
"=",
"getUrlConnection",
"(",
")",
";",
"try",
"{",
"if",
"(",
"!",
"NetworkUtils",
".",
"sendHttpDeleteRequest",
"(",
"conn",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to send delete request to \"",
"+",
"endpointURI",
")",
";",
"}",
"// Check the response code",
"if",
"(",
"!",
"NetworkUtils",
".",
"checkHttpResponseCode",
"(",
"conn",
",",
"expectedResponseCode",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unexpected response from connection. Expected \"",
"+",
"expectedResponseCode",
"+",
"\" but received \"",
"+",
"conn",
".",
"getResponseCode",
"(",
")",
")",
";",
"}",
"}",
"finally",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"}"
] | Make a DELETE request to a URI
@param expectedResponseCode the response code you expect to get from this endpoint | [
"Make",
"a",
"DELETE",
"request",
"to",
"a",
"URI"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java#L95-L110 |
27,923 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java | HttpJsonClient.post | public void post(String jsonBody, Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
try {
// send post request with json body for the topology
if (!NetworkUtils.sendHttpPostRequest(conn, NetworkUtils.JSON_TYPE, jsonBody.getBytes())) {
throw new IOException("Failed to send POST to " + endpointURI);
}
// check the response
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
byte[] bytes = NetworkUtils.readHttpResponse(conn);
LOG.log(Level.SEVERE, "Failed to send POST request to endpoint");
LOG.log(Level.SEVERE, new String(bytes));
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
} finally {
conn.disconnect();
}
} | java | public void post(String jsonBody, Integer expectedResponseCode) throws IOException {
HttpURLConnection conn = getUrlConnection();
try {
// send post request with json body for the topology
if (!NetworkUtils.sendHttpPostRequest(conn, NetworkUtils.JSON_TYPE, jsonBody.getBytes())) {
throw new IOException("Failed to send POST to " + endpointURI);
}
// check the response
if (!NetworkUtils.checkHttpResponseCode(conn, expectedResponseCode)) {
byte[] bytes = NetworkUtils.readHttpResponse(conn);
LOG.log(Level.SEVERE, "Failed to send POST request to endpoint");
LOG.log(Level.SEVERE, new String(bytes));
throw new IOException("Unexpected response from connection. Expected "
+ expectedResponseCode + " but received " + conn.getResponseCode());
}
} finally {
conn.disconnect();
}
} | [
"public",
"void",
"post",
"(",
"String",
"jsonBody",
",",
"Integer",
"expectedResponseCode",
")",
"throws",
"IOException",
"{",
"HttpURLConnection",
"conn",
"=",
"getUrlConnection",
"(",
")",
";",
"try",
"{",
"// send post request with json body for the topology",
"if",
"(",
"!",
"NetworkUtils",
".",
"sendHttpPostRequest",
"(",
"conn",
",",
"NetworkUtils",
".",
"JSON_TYPE",
",",
"jsonBody",
".",
"getBytes",
"(",
")",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Failed to send POST to \"",
"+",
"endpointURI",
")",
";",
"}",
"// check the response",
"if",
"(",
"!",
"NetworkUtils",
".",
"checkHttpResponseCode",
"(",
"conn",
",",
"expectedResponseCode",
")",
")",
"{",
"byte",
"[",
"]",
"bytes",
"=",
"NetworkUtils",
".",
"readHttpResponse",
"(",
"conn",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to send POST request to endpoint\"",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"new",
"String",
"(",
"bytes",
")",
")",
";",
"throw",
"new",
"IOException",
"(",
"\"Unexpected response from connection. Expected \"",
"+",
"expectedResponseCode",
"+",
"\" but received \"",
"+",
"conn",
".",
"getResponseCode",
"(",
")",
")",
";",
"}",
"}",
"finally",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"}"
] | Make a POST request to a URI
@param jsonBody String form of the jsonBody
@param expectedResponseCode the response code you expect to get from this endpoint | [
"Make",
"a",
"POST",
"request",
"to",
"a",
"URI"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/utils/HttpJsonClient.java#L118-L138 |
27,924 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/network/SocketChannelHelper.java | SocketChannelHelper.read | public List<IncomingPacket> read() {
// We record the start time to avoid spending too much time on readings
long startOfCycle = System.nanoTime();
long bytesRead = 0;
long nPacketsRead = 0;
List<IncomingPacket> ret = new ArrayList<IncomingPacket>();
// We would stop reading when:
// 1. We spent too much time
// 2. We have read large enough data
while ((System.nanoTime() - startOfCycle - readReadBatchTime.toNanos()) < 0
&& (bytesRead < readBatchSize.asBytes())) {
int readState = incomingPacket.readFromChannel(socketChannel, maximumPacketSize.asBytes());
if (readState > 0) {
// Partial Read, just break, and read next time when the socket is readable
break;
} else if (readState < 0) {
LOG.severe("Something bad happened while reading from channel: "
+ socketChannel.socket().getRemoteSocketAddress());
selectHandler.handleError(socketChannel);
// Clear the list of Incoming Packet to avoid bad state is used externally
ret.clear();
break;
} else {
// readState == 0, we fully read a incomingPacket
nPacketsRead++;
bytesRead += incomingPacket.size();
ret.add(incomingPacket);
incomingPacket = new IncomingPacket();
}
}
totalPacketsRead += nPacketsRead;
totalBytesRead += bytesRead;
return ret;
} | java | public List<IncomingPacket> read() {
// We record the start time to avoid spending too much time on readings
long startOfCycle = System.nanoTime();
long bytesRead = 0;
long nPacketsRead = 0;
List<IncomingPacket> ret = new ArrayList<IncomingPacket>();
// We would stop reading when:
// 1. We spent too much time
// 2. We have read large enough data
while ((System.nanoTime() - startOfCycle - readReadBatchTime.toNanos()) < 0
&& (bytesRead < readBatchSize.asBytes())) {
int readState = incomingPacket.readFromChannel(socketChannel, maximumPacketSize.asBytes());
if (readState > 0) {
// Partial Read, just break, and read next time when the socket is readable
break;
} else if (readState < 0) {
LOG.severe("Something bad happened while reading from channel: "
+ socketChannel.socket().getRemoteSocketAddress());
selectHandler.handleError(socketChannel);
// Clear the list of Incoming Packet to avoid bad state is used externally
ret.clear();
break;
} else {
// readState == 0, we fully read a incomingPacket
nPacketsRead++;
bytesRead += incomingPacket.size();
ret.add(incomingPacket);
incomingPacket = new IncomingPacket();
}
}
totalPacketsRead += nPacketsRead;
totalBytesRead += bytesRead;
return ret;
} | [
"public",
"List",
"<",
"IncomingPacket",
">",
"read",
"(",
")",
"{",
"// We record the start time to avoid spending too much time on readings",
"long",
"startOfCycle",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"long",
"bytesRead",
"=",
"0",
";",
"long",
"nPacketsRead",
"=",
"0",
";",
"List",
"<",
"IncomingPacket",
">",
"ret",
"=",
"new",
"ArrayList",
"<",
"IncomingPacket",
">",
"(",
")",
";",
"// We would stop reading when:",
"// 1. We spent too much time",
"// 2. We have read large enough data",
"while",
"(",
"(",
"System",
".",
"nanoTime",
"(",
")",
"-",
"startOfCycle",
"-",
"readReadBatchTime",
".",
"toNanos",
"(",
")",
")",
"<",
"0",
"&&",
"(",
"bytesRead",
"<",
"readBatchSize",
".",
"asBytes",
"(",
")",
")",
")",
"{",
"int",
"readState",
"=",
"incomingPacket",
".",
"readFromChannel",
"(",
"socketChannel",
",",
"maximumPacketSize",
".",
"asBytes",
"(",
")",
")",
";",
"if",
"(",
"readState",
">",
"0",
")",
"{",
"// Partial Read, just break, and read next time when the socket is readable",
"break",
";",
"}",
"else",
"if",
"(",
"readState",
"<",
"0",
")",
"{",
"LOG",
".",
"severe",
"(",
"\"Something bad happened while reading from channel: \"",
"+",
"socketChannel",
".",
"socket",
"(",
")",
".",
"getRemoteSocketAddress",
"(",
")",
")",
";",
"selectHandler",
".",
"handleError",
"(",
"socketChannel",
")",
";",
"// Clear the list of Incoming Packet to avoid bad state is used externally",
"ret",
".",
"clear",
"(",
")",
";",
"break",
";",
"}",
"else",
"{",
"// readState == 0, we fully read a incomingPacket",
"nPacketsRead",
"++",
";",
"bytesRead",
"+=",
"incomingPacket",
".",
"size",
"(",
")",
";",
"ret",
".",
"add",
"(",
"incomingPacket",
")",
";",
"incomingPacket",
"=",
"new",
"IncomingPacket",
"(",
")",
";",
"}",
"}",
"totalPacketsRead",
"+=",
"nPacketsRead",
";",
"totalBytesRead",
"+=",
"bytesRead",
";",
"return",
"ret",
";",
"}"
] | It would return an empty list if something bad happens | [
"It",
"would",
"return",
"an",
"empty",
"list",
"if",
"something",
"bad",
"happens"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/SocketChannelHelper.java#L133-L173 |
27,925 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/network/SocketChannelHelper.java | SocketChannelHelper.write | public void write() {
// We record the start time to avoid spending too much time on writings
long startOfCycle = System.nanoTime();
long bytesWritten = 0;
long nPacketsWritten = 0;
while ((System.nanoTime() - startOfCycle - writeBatchTime.toNanos()) < 0
&& (bytesWritten < writeBatchSize.asBytes())) {
OutgoingPacket outgoingPacket = outgoingPacketsToWrite.peek();
if (outgoingPacket == null) {
break;
}
int writeState = outgoingPacket.writeToChannel(socketChannel);
if (writeState > 0) {
// Partial writing, we would break since we could not write more data on socket.
// But we have set the next start point of OutgoingPacket
// Next time when the socket is writable, it will start from that point.
break;
} else if (writeState < 0) {
LOG.severe("Something bad happened while writing to channel");
selectHandler.handleError(socketChannel);
return;
} else {
// writeState == 0, we fully write a outgoingPacket
bytesWritten += outgoingPacket.size();
nPacketsWritten++;
outgoingPacketsToWrite.remove();
}
}
totalPacketsWritten += nPacketsWritten;
totalBytesWritten += bytesWritten;
// Disable writing if there are nothing to send in buffer
if (getOutstandingPackets() == 0) {
disableWriting();
}
} | java | public void write() {
// We record the start time to avoid spending too much time on writings
long startOfCycle = System.nanoTime();
long bytesWritten = 0;
long nPacketsWritten = 0;
while ((System.nanoTime() - startOfCycle - writeBatchTime.toNanos()) < 0
&& (bytesWritten < writeBatchSize.asBytes())) {
OutgoingPacket outgoingPacket = outgoingPacketsToWrite.peek();
if (outgoingPacket == null) {
break;
}
int writeState = outgoingPacket.writeToChannel(socketChannel);
if (writeState > 0) {
// Partial writing, we would break since we could not write more data on socket.
// But we have set the next start point of OutgoingPacket
// Next time when the socket is writable, it will start from that point.
break;
} else if (writeState < 0) {
LOG.severe("Something bad happened while writing to channel");
selectHandler.handleError(socketChannel);
return;
} else {
// writeState == 0, we fully write a outgoingPacket
bytesWritten += outgoingPacket.size();
nPacketsWritten++;
outgoingPacketsToWrite.remove();
}
}
totalPacketsWritten += nPacketsWritten;
totalBytesWritten += bytesWritten;
// Disable writing if there are nothing to send in buffer
if (getOutstandingPackets() == 0) {
disableWriting();
}
} | [
"public",
"void",
"write",
"(",
")",
"{",
"// We record the start time to avoid spending too much time on writings",
"long",
"startOfCycle",
"=",
"System",
".",
"nanoTime",
"(",
")",
";",
"long",
"bytesWritten",
"=",
"0",
";",
"long",
"nPacketsWritten",
"=",
"0",
";",
"while",
"(",
"(",
"System",
".",
"nanoTime",
"(",
")",
"-",
"startOfCycle",
"-",
"writeBatchTime",
".",
"toNanos",
"(",
")",
")",
"<",
"0",
"&&",
"(",
"bytesWritten",
"<",
"writeBatchSize",
".",
"asBytes",
"(",
")",
")",
")",
"{",
"OutgoingPacket",
"outgoingPacket",
"=",
"outgoingPacketsToWrite",
".",
"peek",
"(",
")",
";",
"if",
"(",
"outgoingPacket",
"==",
"null",
")",
"{",
"break",
";",
"}",
"int",
"writeState",
"=",
"outgoingPacket",
".",
"writeToChannel",
"(",
"socketChannel",
")",
";",
"if",
"(",
"writeState",
">",
"0",
")",
"{",
"// Partial writing, we would break since we could not write more data on socket.",
"// But we have set the next start point of OutgoingPacket",
"// Next time when the socket is writable, it will start from that point.",
"break",
";",
"}",
"else",
"if",
"(",
"writeState",
"<",
"0",
")",
"{",
"LOG",
".",
"severe",
"(",
"\"Something bad happened while writing to channel\"",
")",
";",
"selectHandler",
".",
"handleError",
"(",
"socketChannel",
")",
";",
"return",
";",
"}",
"else",
"{",
"// writeState == 0, we fully write a outgoingPacket",
"bytesWritten",
"+=",
"outgoingPacket",
".",
"size",
"(",
")",
";",
"nPacketsWritten",
"++",
";",
"outgoingPacketsToWrite",
".",
"remove",
"(",
")",
";",
"}",
"}",
"totalPacketsWritten",
"+=",
"nPacketsWritten",
";",
"totalBytesWritten",
"+=",
"bytesWritten",
";",
"// Disable writing if there are nothing to send in buffer",
"if",
"(",
"getOutstandingPackets",
"(",
")",
"==",
"0",
")",
"{",
"disableWriting",
"(",
")",
";",
"}",
"}"
] | Write the outgoingPackets in buffer to socket | [
"Write",
"the",
"outgoingPackets",
"in",
"buffer",
"to",
"socket"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/network/SocketChannelHelper.java#L176-L216 |
27,926 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/common/TokenSub.java | TokenSub.combinePaths | private static String combinePaths(List<String> paths) {
File file = new File(paths.get(0));
for (int i = 1; i < paths.size(); i++) {
file = new File(file, paths.get(i));
}
return file.getPath();
} | java | private static String combinePaths(List<String> paths) {
File file = new File(paths.get(0));
for (int i = 1; i < paths.size(); i++) {
file = new File(file, paths.get(i));
}
return file.getPath();
} | [
"private",
"static",
"String",
"combinePaths",
"(",
"List",
"<",
"String",
">",
"paths",
")",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"paths",
".",
"get",
"(",
"0",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"paths",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"file",
"=",
"new",
"File",
"(",
"file",
",",
"paths",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"return",
"file",
".",
"getPath",
"(",
")",
";",
"}"
] | Given a list of strings, concatenate them to form a file system
path
@param paths a list of strings to be included in the path
@return String string that gives the file system path | [
"Given",
"a",
"list",
"of",
"strings",
"concatenate",
"them",
"to",
"form",
"a",
"file",
"system",
"path"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/common/TokenSub.java#L149-L157 |
27,927 | apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/executors/InstanceExecutor.java | InstanceExecutor.handleControlSignal | protected void handleControlSignal() {
if (toActivate) {
if (!isInstanceStarted) {
startInstance();
}
instance.activate();
LOG.info("Activated instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toActivate = false;
}
if (toDeactivate) {
instance.deactivate();
LOG.info("Deactivated instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toDeactivate = false;
}
if (toStop) {
instance.shutdown();
LOG.info("Stopped instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toStop = false;
}
} | java | protected void handleControlSignal() {
if (toActivate) {
if (!isInstanceStarted) {
startInstance();
}
instance.activate();
LOG.info("Activated instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toActivate = false;
}
if (toDeactivate) {
instance.deactivate();
LOG.info("Deactivated instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toDeactivate = false;
}
if (toStop) {
instance.shutdown();
LOG.info("Stopped instance: " + physicalPlanHelper.getMyInstanceId());
// Reset the flag value
toStop = false;
}
} | [
"protected",
"void",
"handleControlSignal",
"(",
")",
"{",
"if",
"(",
"toActivate",
")",
"{",
"if",
"(",
"!",
"isInstanceStarted",
")",
"{",
"startInstance",
"(",
")",
";",
"}",
"instance",
".",
"activate",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Activated instance: \"",
"+",
"physicalPlanHelper",
".",
"getMyInstanceId",
"(",
")",
")",
";",
"// Reset the flag value",
"toActivate",
"=",
"false",
";",
"}",
"if",
"(",
"toDeactivate",
")",
"{",
"instance",
".",
"deactivate",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Deactivated instance: \"",
"+",
"physicalPlanHelper",
".",
"getMyInstanceId",
"(",
")",
")",
";",
"// Reset the flag value",
"toDeactivate",
"=",
"false",
";",
"}",
"if",
"(",
"toStop",
")",
"{",
"instance",
".",
"shutdown",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Stopped instance: \"",
"+",
"physicalPlanHelper",
".",
"getMyInstanceId",
"(",
")",
")",
";",
"// Reset the flag value",
"toStop",
"=",
"false",
";",
"}",
"}"
] | But we have to handle these flags inside the WakeableLooper thread | [
"But",
"we",
"have",
"to",
"handle",
"these",
"flags",
"inside",
"the",
"WakeableLooper",
"thread"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/executors/InstanceExecutor.java#L140-L168 |
27,928 | apache/incubator-heron | heron/api/src/java/org/apache/heron/api/Config.java | Config.setEnableAcking | @Deprecated
public static void setEnableAcking(Map<String, Object> conf, boolean acking) {
if (acking) {
setTopologyReliabilityMode(conf, Config.TopologyReliabilityMode.ATLEAST_ONCE);
} else {
setTopologyReliabilityMode(conf, Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} | java | @Deprecated
public static void setEnableAcking(Map<String, Object> conf, boolean acking) {
if (acking) {
setTopologyReliabilityMode(conf, Config.TopologyReliabilityMode.ATLEAST_ONCE);
} else {
setTopologyReliabilityMode(conf, Config.TopologyReliabilityMode.ATMOST_ONCE);
}
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"setEnableAcking",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"conf",
",",
"boolean",
"acking",
")",
"{",
"if",
"(",
"acking",
")",
"{",
"setTopologyReliabilityMode",
"(",
"conf",
",",
"Config",
".",
"TopologyReliabilityMode",
".",
"ATLEAST_ONCE",
")",
";",
"}",
"else",
"{",
"setTopologyReliabilityMode",
"(",
"conf",
",",
"Config",
".",
"TopologyReliabilityMode",
".",
"ATMOST_ONCE",
")",
";",
"}",
"}"
] | Is topology running with acking enabled?
@deprecated use {@link #setTopologyReliabilityMode(Map, TopologyReliabilityMode)} instead. | [
"Is",
"topology",
"running",
"with",
"acking",
"enabled?"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/Config.java#L422-L429 |
27,929 | apache/incubator-heron | heron/api/src/java/org/apache/heron/api/Config.java | Config.registerTopologyTimerEvents | @SuppressWarnings("unchecked")
public static void registerTopologyTimerEvents(Map<String, Object> conf,
String name, Duration interval,
Runnable task) {
if (interval.isZero() || interval.isNegative()) {
throw new IllegalArgumentException("Timer duration needs to be positive");
}
if (!conf.containsKey(Config.TOPOLOGY_TIMER_EVENTS)) {
conf.put(Config.TOPOLOGY_TIMER_EVENTS, new HashMap<String, Pair<Duration, Runnable>>());
}
Map<String, Pair<Duration, Runnable>> timers
= (Map<String, Pair<Duration, Runnable>>) conf.get(Config.TOPOLOGY_TIMER_EVENTS);
if (timers.containsKey(name)) {
throw new IllegalArgumentException("Timer with name " + name + " already exists");
}
timers.put(name, Pair.of(interval, task));
} | java | @SuppressWarnings("unchecked")
public static void registerTopologyTimerEvents(Map<String, Object> conf,
String name, Duration interval,
Runnable task) {
if (interval.isZero() || interval.isNegative()) {
throw new IllegalArgumentException("Timer duration needs to be positive");
}
if (!conf.containsKey(Config.TOPOLOGY_TIMER_EVENTS)) {
conf.put(Config.TOPOLOGY_TIMER_EVENTS, new HashMap<String, Pair<Duration, Runnable>>());
}
Map<String, Pair<Duration, Runnable>> timers
= (Map<String, Pair<Duration, Runnable>>) conf.get(Config.TOPOLOGY_TIMER_EVENTS);
if (timers.containsKey(name)) {
throw new IllegalArgumentException("Timer with name " + name + " already exists");
}
timers.put(name, Pair.of(interval, task));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"void",
"registerTopologyTimerEvents",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"conf",
",",
"String",
"name",
",",
"Duration",
"interval",
",",
"Runnable",
"task",
")",
"{",
"if",
"(",
"interval",
".",
"isZero",
"(",
")",
"||",
"interval",
".",
"isNegative",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Timer duration needs to be positive\"",
")",
";",
"}",
"if",
"(",
"!",
"conf",
".",
"containsKey",
"(",
"Config",
".",
"TOPOLOGY_TIMER_EVENTS",
")",
")",
"{",
"conf",
".",
"put",
"(",
"Config",
".",
"TOPOLOGY_TIMER_EVENTS",
",",
"new",
"HashMap",
"<",
"String",
",",
"Pair",
"<",
"Duration",
",",
"Runnable",
">",
">",
"(",
")",
")",
";",
"}",
"Map",
"<",
"String",
",",
"Pair",
"<",
"Duration",
",",
"Runnable",
">",
">",
"timers",
"=",
"(",
"Map",
"<",
"String",
",",
"Pair",
"<",
"Duration",
",",
"Runnable",
">",
">",
")",
"conf",
".",
"get",
"(",
"Config",
".",
"TOPOLOGY_TIMER_EVENTS",
")",
";",
"if",
"(",
"timers",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Timer with name \"",
"+",
"name",
"+",
"\" already exists\"",
")",
";",
"}",
"timers",
".",
"put",
"(",
"name",
",",
"Pair",
".",
"of",
"(",
"interval",
",",
"task",
")",
")",
";",
"}"
] | Registers a timer event that executes periodically
@param conf the map with the existing topology configs
@param name the name of the timer
@param interval the frequency in which to run the task
@param task the task to run | [
"Registers",
"a",
"timer",
"event",
"that",
"executes",
"periodically"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/Config.java#L670-L688 |
27,930 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/Runner.java | Runner.run | public void run(String name, Config config, Builder builder) {
BuilderImpl bldr = (BuilderImpl) builder;
TopologyBuilder topologyBuilder = bldr.build();
try {
HeronSubmitter.submitTopology(name, config.getHeronConfig(),
topologyBuilder.createTopology());
} catch (AlreadyAliveException | InvalidTopologyException e) {
e.printStackTrace();
}
} | java | public void run(String name, Config config, Builder builder) {
BuilderImpl bldr = (BuilderImpl) builder;
TopologyBuilder topologyBuilder = bldr.build();
try {
HeronSubmitter.submitTopology(name, config.getHeronConfig(),
topologyBuilder.createTopology());
} catch (AlreadyAliveException | InvalidTopologyException e) {
e.printStackTrace();
}
} | [
"public",
"void",
"run",
"(",
"String",
"name",
",",
"Config",
"config",
",",
"Builder",
"builder",
")",
"{",
"BuilderImpl",
"bldr",
"=",
"(",
"BuilderImpl",
")",
"builder",
";",
"TopologyBuilder",
"topologyBuilder",
"=",
"bldr",
".",
"build",
"(",
")",
";",
"try",
"{",
"HeronSubmitter",
".",
"submitTopology",
"(",
"name",
",",
"config",
".",
"getHeronConfig",
"(",
")",
",",
"topologyBuilder",
".",
"createTopology",
"(",
")",
")",
";",
"}",
"catch",
"(",
"AlreadyAliveException",
"|",
"InvalidTopologyException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}"
] | Runs the computation
@param name The name of the topology
@param config Any config that is passed to the topology
@param builder The builder used to keep track of the sources. | [
"Runs",
"the",
"computation"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/Runner.java#L42-L51 |
27,931 | apache/incubator-heron | heron/io/dlog/src/java/org/apache/heron/dlog/DLInputStream.java | DLInputStream.nextLogRecord | private LogRecordWithInputStream nextLogRecord() throws IOException {
try {
return nextLogRecord(reader);
} catch (EndOfStreamException e) {
eos = true;
LOG.info(()->"end of stream is reached");
return null;
}
} | java | private LogRecordWithInputStream nextLogRecord() throws IOException {
try {
return nextLogRecord(reader);
} catch (EndOfStreamException e) {
eos = true;
LOG.info(()->"end of stream is reached");
return null;
}
} | [
"private",
"LogRecordWithInputStream",
"nextLogRecord",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"return",
"nextLogRecord",
"(",
"reader",
")",
";",
"}",
"catch",
"(",
"EndOfStreamException",
"e",
")",
"{",
"eos",
"=",
"true",
";",
"LOG",
".",
"info",
"(",
"(",
")",
"->",
"\"end of stream is reached\"",
")",
";",
"return",
"null",
";",
"}",
"}"
] | Get input stream representing next entry in the
ledger.
@return input stream, or null if no more entries | [
"Get",
"input",
"stream",
"representing",
"next",
"entry",
"in",
"the",
"ledger",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/io/dlog/src/java/org/apache/heron/dlog/DLInputStream.java#L75-L83 |
27,932 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/LaunchRunner.java | LaunchRunner.trimTopology | public TopologyAPI.Topology trimTopology(TopologyAPI.Topology topology) {
// create a copy of the topology physical plan
TopologyAPI.Topology.Builder builder = TopologyAPI.Topology.newBuilder().mergeFrom(topology);
// clear the state of user spout java objects - which can be potentially huge
for (TopologyAPI.Spout.Builder spout : builder.getSpoutsBuilderList()) {
spout.getCompBuilder().clearSerializedObject();
}
// clear the state of user spout java objects - which can be potentially huge
for (TopologyAPI.Bolt.Builder bolt : builder.getBoltsBuilderList()) {
bolt.getCompBuilder().clearSerializedObject();
}
return builder.build();
} | java | public TopologyAPI.Topology trimTopology(TopologyAPI.Topology topology) {
// create a copy of the topology physical plan
TopologyAPI.Topology.Builder builder = TopologyAPI.Topology.newBuilder().mergeFrom(topology);
// clear the state of user spout java objects - which can be potentially huge
for (TopologyAPI.Spout.Builder spout : builder.getSpoutsBuilderList()) {
spout.getCompBuilder().clearSerializedObject();
}
// clear the state of user spout java objects - which can be potentially huge
for (TopologyAPI.Bolt.Builder bolt : builder.getBoltsBuilderList()) {
bolt.getCompBuilder().clearSerializedObject();
}
return builder.build();
} | [
"public",
"TopologyAPI",
".",
"Topology",
"trimTopology",
"(",
"TopologyAPI",
".",
"Topology",
"topology",
")",
"{",
"// create a copy of the topology physical plan",
"TopologyAPI",
".",
"Topology",
".",
"Builder",
"builder",
"=",
"TopologyAPI",
".",
"Topology",
".",
"newBuilder",
"(",
")",
".",
"mergeFrom",
"(",
"topology",
")",
";",
"// clear the state of user spout java objects - which can be potentially huge",
"for",
"(",
"TopologyAPI",
".",
"Spout",
".",
"Builder",
"spout",
":",
"builder",
".",
"getSpoutsBuilderList",
"(",
")",
")",
"{",
"spout",
".",
"getCompBuilder",
"(",
")",
".",
"clearSerializedObject",
"(",
")",
";",
"}",
"// clear the state of user spout java objects - which can be potentially huge",
"for",
"(",
"TopologyAPI",
".",
"Bolt",
".",
"Builder",
"bolt",
":",
"builder",
".",
"getBoltsBuilderList",
"(",
")",
")",
"{",
"bolt",
".",
"getCompBuilder",
"(",
")",
".",
"clearSerializedObject",
"(",
")",
";",
"}",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}"
] | Trim the topology definition for storing into state manager.
This is because the user generated spouts and bolts
might be huge.
@return trimmed topology | [
"Trim",
"the",
"topology",
"definition",
"for",
"storing",
"into",
"state",
"manager",
".",
"This",
"is",
"because",
"the",
"user",
"generated",
"spouts",
"and",
"bolts",
"might",
"be",
"huge",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/LaunchRunner.java#L100-L116 |
27,933 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/LaunchRunner.java | LaunchRunner.call | public void call() throws LauncherException, PackingException, SubmitDryRunResponse {
SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
TopologyAPI.Topology topology = Runtime.topology(runtime);
String topologyName = Context.topologyName(config);
PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime);
if (Context.dryRun(config)) {
throw new SubmitDryRunResponse(topology, config, packedPlan);
}
// initialize the launcher
launcher.initialize(config, runtime);
// Set topology def first since we determine whether a topology is running
// by checking the existence of topology def
// store the trimmed topology definition into the state manager
// TODO(rli): log-and-false anti-pattern is too nested on this path. will not refactor
Boolean result = statemgr.setTopology(trimTopology(topology), topologyName);
if (result == null || !result) {
throw new LauncherException(String.format(
"Failed to set topology definition for topology '%s'", topologyName));
}
result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName);
if (result == null || !result) {
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to set packing plan for topology '%s'", topologyName));
}
// store the execution state into the state manager
ExecutionEnvironment.ExecutionState executionState = createExecutionState();
result = statemgr.setExecutionState(executionState, topologyName);
if (result == null || !result) {
statemgr.deletePackingPlan(topologyName);
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to set execution state for topology '%s'", topologyName));
}
// launch the topology, clear the state if it fails
if (!launcher.launch(packedPlan)) {
statemgr.deleteExecutionState(topologyName);
statemgr.deletePackingPlan(topologyName);
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to launch topology '%s'", topologyName));
}
} | java | public void call() throws LauncherException, PackingException, SubmitDryRunResponse {
SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
TopologyAPI.Topology topology = Runtime.topology(runtime);
String topologyName = Context.topologyName(config);
PackingPlan packedPlan = LauncherUtils.getInstance().createPackingPlan(config, runtime);
if (Context.dryRun(config)) {
throw new SubmitDryRunResponse(topology, config, packedPlan);
}
// initialize the launcher
launcher.initialize(config, runtime);
// Set topology def first since we determine whether a topology is running
// by checking the existence of topology def
// store the trimmed topology definition into the state manager
// TODO(rli): log-and-false anti-pattern is too nested on this path. will not refactor
Boolean result = statemgr.setTopology(trimTopology(topology), topologyName);
if (result == null || !result) {
throw new LauncherException(String.format(
"Failed to set topology definition for topology '%s'", topologyName));
}
result = statemgr.setPackingPlan(createPackingPlan(packedPlan), topologyName);
if (result == null || !result) {
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to set packing plan for topology '%s'", topologyName));
}
// store the execution state into the state manager
ExecutionEnvironment.ExecutionState executionState = createExecutionState();
result = statemgr.setExecutionState(executionState, topologyName);
if (result == null || !result) {
statemgr.deletePackingPlan(topologyName);
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to set execution state for topology '%s'", topologyName));
}
// launch the topology, clear the state if it fails
if (!launcher.launch(packedPlan)) {
statemgr.deleteExecutionState(topologyName);
statemgr.deletePackingPlan(topologyName);
statemgr.deleteTopology(topologyName);
throw new LauncherException(String.format(
"Failed to launch topology '%s'", topologyName));
}
} | [
"public",
"void",
"call",
"(",
")",
"throws",
"LauncherException",
",",
"PackingException",
",",
"SubmitDryRunResponse",
"{",
"SchedulerStateManagerAdaptor",
"statemgr",
"=",
"Runtime",
".",
"schedulerStateManagerAdaptor",
"(",
"runtime",
")",
";",
"TopologyAPI",
".",
"Topology",
"topology",
"=",
"Runtime",
".",
"topology",
"(",
"runtime",
")",
";",
"String",
"topologyName",
"=",
"Context",
".",
"topologyName",
"(",
"config",
")",
";",
"PackingPlan",
"packedPlan",
"=",
"LauncherUtils",
".",
"getInstance",
"(",
")",
".",
"createPackingPlan",
"(",
"config",
",",
"runtime",
")",
";",
"if",
"(",
"Context",
".",
"dryRun",
"(",
"config",
")",
")",
"{",
"throw",
"new",
"SubmitDryRunResponse",
"(",
"topology",
",",
"config",
",",
"packedPlan",
")",
";",
"}",
"// initialize the launcher",
"launcher",
".",
"initialize",
"(",
"config",
",",
"runtime",
")",
";",
"// Set topology def first since we determine whether a topology is running",
"// by checking the existence of topology def",
"// store the trimmed topology definition into the state manager",
"// TODO(rli): log-and-false anti-pattern is too nested on this path. will not refactor",
"Boolean",
"result",
"=",
"statemgr",
".",
"setTopology",
"(",
"trimTopology",
"(",
"topology",
")",
",",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"throw",
"new",
"LauncherException",
"(",
"String",
".",
"format",
"(",
"\"Failed to set topology definition for topology '%s'\"",
",",
"topologyName",
")",
")",
";",
"}",
"result",
"=",
"statemgr",
".",
"setPackingPlan",
"(",
"createPackingPlan",
"(",
"packedPlan",
")",
",",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"statemgr",
".",
"deleteTopology",
"(",
"topologyName",
")",
";",
"throw",
"new",
"LauncherException",
"(",
"String",
".",
"format",
"(",
"\"Failed to set packing plan for topology '%s'\"",
",",
"topologyName",
")",
")",
";",
"}",
"// store the execution state into the state manager",
"ExecutionEnvironment",
".",
"ExecutionState",
"executionState",
"=",
"createExecutionState",
"(",
")",
";",
"result",
"=",
"statemgr",
".",
"setExecutionState",
"(",
"executionState",
",",
"topologyName",
")",
";",
"if",
"(",
"result",
"==",
"null",
"||",
"!",
"result",
")",
"{",
"statemgr",
".",
"deletePackingPlan",
"(",
"topologyName",
")",
";",
"statemgr",
".",
"deleteTopology",
"(",
"topologyName",
")",
";",
"throw",
"new",
"LauncherException",
"(",
"String",
".",
"format",
"(",
"\"Failed to set execution state for topology '%s'\"",
",",
"topologyName",
")",
")",
";",
"}",
"// launch the topology, clear the state if it fails",
"if",
"(",
"!",
"launcher",
".",
"launch",
"(",
"packedPlan",
")",
")",
"{",
"statemgr",
".",
"deleteExecutionState",
"(",
"topologyName",
")",
";",
"statemgr",
".",
"deletePackingPlan",
"(",
"topologyName",
")",
";",
"statemgr",
".",
"deleteTopology",
"(",
"topologyName",
")",
";",
"throw",
"new",
"LauncherException",
"(",
"String",
".",
"format",
"(",
"\"Failed to launch topology '%s'\"",
",",
"topologyName",
")",
")",
";",
"}",
"}"
] | Call launcher to launch topology
@throws LauncherException
@throws PackingException
@throws SubmitDryRunResponse | [
"Call",
"launcher",
"to",
"launch",
"topology"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/LaunchRunner.java#L130-L180 |
27,934 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.startExecutorProcess | @VisibleForTesting
protected Process startExecutorProcess(int container, Set<PackingPlan.InstancePlan> instances) {
return ShellUtils.runASyncProcess(
getExecutorCommand(container, instances),
new File(LocalContext.workingDirectory(config)),
Integer.toString(container));
} | java | @VisibleForTesting
protected Process startExecutorProcess(int container, Set<PackingPlan.InstancePlan> instances) {
return ShellUtils.runASyncProcess(
getExecutorCommand(container, instances),
new File(LocalContext.workingDirectory(config)),
Integer.toString(container));
} | [
"@",
"VisibleForTesting",
"protected",
"Process",
"startExecutorProcess",
"(",
"int",
"container",
",",
"Set",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"instances",
")",
"{",
"return",
"ShellUtils",
".",
"runASyncProcess",
"(",
"getExecutorCommand",
"(",
"container",
",",
"instances",
")",
",",
"new",
"File",
"(",
"LocalContext",
".",
"workingDirectory",
"(",
"config",
")",
")",
",",
"Integer",
".",
"toString",
"(",
"container",
")",
")",
";",
"}"
] | Start executor process via running an async shell process | [
"Start",
"executor",
"process",
"via",
"running",
"an",
"async",
"shell",
"process"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L89-L95 |
27,935 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.startExecutor | @VisibleForTesting
protected void startExecutor(final int container, Set<PackingPlan.InstancePlan> instances) {
LOG.info("Starting a new executor for container: " + container);
// create a process with the executor command and topology working directory
final Process containerExecutor = startExecutorProcess(container, instances);
// associate the process and its container id
processToContainer.put(containerExecutor, container);
LOG.info("Started the executor for container: " + container);
// add the container for monitoring
startExecutorMonitor(container, containerExecutor, instances);
} | java | @VisibleForTesting
protected void startExecutor(final int container, Set<PackingPlan.InstancePlan> instances) {
LOG.info("Starting a new executor for container: " + container);
// create a process with the executor command and topology working directory
final Process containerExecutor = startExecutorProcess(container, instances);
// associate the process and its container id
processToContainer.put(containerExecutor, container);
LOG.info("Started the executor for container: " + container);
// add the container for monitoring
startExecutorMonitor(container, containerExecutor, instances);
} | [
"@",
"VisibleForTesting",
"protected",
"void",
"startExecutor",
"(",
"final",
"int",
"container",
",",
"Set",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"instances",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Starting a new executor for container: \"",
"+",
"container",
")",
";",
"// create a process with the executor command and topology working directory",
"final",
"Process",
"containerExecutor",
"=",
"startExecutorProcess",
"(",
"container",
",",
"instances",
")",
";",
"// associate the process and its container id",
"processToContainer",
".",
"put",
"(",
"containerExecutor",
",",
"container",
")",
";",
"LOG",
".",
"info",
"(",
"\"Started the executor for container: \"",
"+",
"container",
")",
";",
"// add the container for monitoring",
"startExecutorMonitor",
"(",
"container",
",",
"containerExecutor",
",",
"instances",
")",
";",
"}"
] | Start the executor for the given container | [
"Start",
"the",
"executor",
"for",
"the",
"given",
"container"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L100-L113 |
27,936 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.startExecutorMonitor | @VisibleForTesting
protected void startExecutorMonitor(final int container,
final Process containerExecutor,
Set<PackingPlan.InstancePlan> instances) {
// add the container for monitoring
Runnable r = new Runnable() {
@Override
public void run() {
try {
LOG.info("Waiting for container " + container + " to finish.");
containerExecutor.waitFor();
LOG.log(Level.INFO,
"Container {0} is completed. Exit status: {1}",
new Object[]{container, containerExecutor.exitValue()});
if (isTopologyKilled) {
LOG.info("Topology is killed. Not to start new executors.");
return;
} else if (!processToContainer.containsKey(containerExecutor)) {
LOG.log(Level.INFO, "Container {0} is killed. No need to relaunch.", container);
return;
}
LOG.log(Level.INFO, "Trying to restart container {0}", container);
// restart the container
startExecutor(processToContainer.remove(containerExecutor), instances);
} catch (InterruptedException e) {
if (!isTopologyKilled) {
LOG.log(Level.SEVERE, "Process is interrupted: ", e);
}
}
}
};
monitorService.submit(r);
} | java | @VisibleForTesting
protected void startExecutorMonitor(final int container,
final Process containerExecutor,
Set<PackingPlan.InstancePlan> instances) {
// add the container for monitoring
Runnable r = new Runnable() {
@Override
public void run() {
try {
LOG.info("Waiting for container " + container + " to finish.");
containerExecutor.waitFor();
LOG.log(Level.INFO,
"Container {0} is completed. Exit status: {1}",
new Object[]{container, containerExecutor.exitValue()});
if (isTopologyKilled) {
LOG.info("Topology is killed. Not to start new executors.");
return;
} else if (!processToContainer.containsKey(containerExecutor)) {
LOG.log(Level.INFO, "Container {0} is killed. No need to relaunch.", container);
return;
}
LOG.log(Level.INFO, "Trying to restart container {0}", container);
// restart the container
startExecutor(processToContainer.remove(containerExecutor), instances);
} catch (InterruptedException e) {
if (!isTopologyKilled) {
LOG.log(Level.SEVERE, "Process is interrupted: ", e);
}
}
}
};
monitorService.submit(r);
} | [
"@",
"VisibleForTesting",
"protected",
"void",
"startExecutorMonitor",
"(",
"final",
"int",
"container",
",",
"final",
"Process",
"containerExecutor",
",",
"Set",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"instances",
")",
"{",
"// add the container for monitoring",
"Runnable",
"r",
"=",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"LOG",
".",
"info",
"(",
"\"Waiting for container \"",
"+",
"container",
"+",
"\" to finish.\"",
")",
";",
"containerExecutor",
".",
"waitFor",
"(",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Container {0} is completed. Exit status: {1}\"",
",",
"new",
"Object",
"[",
"]",
"{",
"container",
",",
"containerExecutor",
".",
"exitValue",
"(",
")",
"}",
")",
";",
"if",
"(",
"isTopologyKilled",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Topology is killed. Not to start new executors.\"",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"!",
"processToContainer",
".",
"containsKey",
"(",
"containerExecutor",
")",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Container {0} is killed. No need to relaunch.\"",
",",
"container",
")",
";",
"return",
";",
"}",
"LOG",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Trying to restart container {0}\"",
",",
"container",
")",
";",
"// restart the container",
"startExecutor",
"(",
"processToContainer",
".",
"remove",
"(",
"containerExecutor",
")",
",",
"instances",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"if",
"(",
"!",
"isTopologyKilled",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Process is interrupted: \"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
";",
"monitorService",
".",
"submit",
"(",
"r",
")",
";",
"}"
] | Start the monitor of a given executor | [
"Start",
"the",
"monitor",
"of",
"a",
"given",
"executor"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L118-L152 |
27,937 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.onSchedule | @Override
public boolean onSchedule(PackingPlan packing) {
LOG.info("Starting to deploy topology: " + LocalContext.topologyName(config));
synchronized (processToContainer) {
LOG.info("Starting executor for TMaster");
startExecutor(0, null);
// for each container, run its own executor
for (PackingPlan.ContainerPlan container : packing.getContainers()) {
startExecutor(container.getId(), container.getInstances());
}
}
LOG.info("Executor for each container have been started.");
return true;
} | java | @Override
public boolean onSchedule(PackingPlan packing) {
LOG.info("Starting to deploy topology: " + LocalContext.topologyName(config));
synchronized (processToContainer) {
LOG.info("Starting executor for TMaster");
startExecutor(0, null);
// for each container, run its own executor
for (PackingPlan.ContainerPlan container : packing.getContainers()) {
startExecutor(container.getId(), container.getInstances());
}
}
LOG.info("Executor for each container have been started.");
return true;
} | [
"@",
"Override",
"public",
"boolean",
"onSchedule",
"(",
"PackingPlan",
"packing",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Starting to deploy topology: \"",
"+",
"LocalContext",
".",
"topologyName",
"(",
"config",
")",
")",
";",
"synchronized",
"(",
"processToContainer",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Starting executor for TMaster\"",
")",
";",
"startExecutor",
"(",
"0",
",",
"null",
")",
";",
"// for each container, run its own executor",
"for",
"(",
"PackingPlan",
".",
"ContainerPlan",
"container",
":",
"packing",
".",
"getContainers",
"(",
")",
")",
"{",
"startExecutor",
"(",
"container",
".",
"getId",
"(",
")",
",",
"container",
".",
"getInstances",
"(",
")",
")",
";",
"}",
"}",
"LOG",
".",
"info",
"(",
"\"Executor for each container have been started.\"",
")",
";",
"return",
"true",
";",
"}"
] | Schedule the provided packed plan | [
"Schedule",
"the",
"provided",
"packed",
"plan"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L188-L205 |
27,938 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.onKill | @Override
public boolean onKill(Scheduler.KillTopologyRequest request) {
// get the topology name
String topologyName = LocalContext.topologyName(config);
LOG.info("Command to kill topology: " + topologyName);
// set the flag that the topology being killed
isTopologyKilled = true;
synchronized (processToContainer) {
// destroy/kill the process for each container
for (Process p : processToContainer.keySet()) {
// get the container index for the process
int index = processToContainer.get(p);
LOG.info("Killing executor for container: " + index);
// destroy the process
p.destroy();
LOG.info("Killed executor for container: " + index);
}
// clear the mapping between process and container ids
processToContainer.clear();
}
return true;
} | java | @Override
public boolean onKill(Scheduler.KillTopologyRequest request) {
// get the topology name
String topologyName = LocalContext.topologyName(config);
LOG.info("Command to kill topology: " + topologyName);
// set the flag that the topology being killed
isTopologyKilled = true;
synchronized (processToContainer) {
// destroy/kill the process for each container
for (Process p : processToContainer.keySet()) {
// get the container index for the process
int index = processToContainer.get(p);
LOG.info("Killing executor for container: " + index);
// destroy the process
p.destroy();
LOG.info("Killed executor for container: " + index);
}
// clear the mapping between process and container ids
processToContainer.clear();
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"onKill",
"(",
"Scheduler",
".",
"KillTopologyRequest",
"request",
")",
"{",
"// get the topology name",
"String",
"topologyName",
"=",
"LocalContext",
".",
"topologyName",
"(",
"config",
")",
";",
"LOG",
".",
"info",
"(",
"\"Command to kill topology: \"",
"+",
"topologyName",
")",
";",
"// set the flag that the topology being killed",
"isTopologyKilled",
"=",
"true",
";",
"synchronized",
"(",
"processToContainer",
")",
"{",
"// destroy/kill the process for each container",
"for",
"(",
"Process",
"p",
":",
"processToContainer",
".",
"keySet",
"(",
")",
")",
"{",
"// get the container index for the process",
"int",
"index",
"=",
"processToContainer",
".",
"get",
"(",
"p",
")",
";",
"LOG",
".",
"info",
"(",
"\"Killing executor for container: \"",
"+",
"index",
")",
";",
"// destroy the process",
"p",
".",
"destroy",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"Killed executor for container: \"",
"+",
"index",
")",
";",
"}",
"// clear the mapping between process and container ids",
"processToContainer",
".",
"clear",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Handler to kill topology | [
"Handler",
"to",
"kill",
"topology"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L215-L243 |
27,939 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java | LocalScheduler.onRestart | @Override
public boolean onRestart(Scheduler.RestartTopologyRequest request) {
// Containers would be restarted automatically once we destroy it
int containerId = request.getContainerIndex();
List<Process> processesToRestart = new LinkedList<>();
if (containerId == -1) {
LOG.info("Command to restart the entire topology: " + LocalContext.topologyName(config));
processesToRestart.addAll(processToContainer.keySet());
} else {
// restart that particular container
LOG.info("Command to restart a container of topology: " + LocalContext.topologyName(config));
LOG.info("Restart container requested: " + containerId);
// locate the container and destroy it
for (Process p : processToContainer.keySet()) {
if (containerId == processToContainer.get(p)) {
processesToRestart.add(p);
}
}
}
if (processesToRestart.isEmpty()) {
LOG.severe("Container not exist.");
return false;
}
for (Process process : processesToRestart) {
process.destroy();
}
return true;
} | java | @Override
public boolean onRestart(Scheduler.RestartTopologyRequest request) {
// Containers would be restarted automatically once we destroy it
int containerId = request.getContainerIndex();
List<Process> processesToRestart = new LinkedList<>();
if (containerId == -1) {
LOG.info("Command to restart the entire topology: " + LocalContext.topologyName(config));
processesToRestart.addAll(processToContainer.keySet());
} else {
// restart that particular container
LOG.info("Command to restart a container of topology: " + LocalContext.topologyName(config));
LOG.info("Restart container requested: " + containerId);
// locate the container and destroy it
for (Process p : processToContainer.keySet()) {
if (containerId == processToContainer.get(p)) {
processesToRestart.add(p);
}
}
}
if (processesToRestart.isEmpty()) {
LOG.severe("Container not exist.");
return false;
}
for (Process process : processesToRestart) {
process.destroy();
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"onRestart",
"(",
"Scheduler",
".",
"RestartTopologyRequest",
"request",
")",
"{",
"// Containers would be restarted automatically once we destroy it",
"int",
"containerId",
"=",
"request",
".",
"getContainerIndex",
"(",
")",
";",
"List",
"<",
"Process",
">",
"processesToRestart",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"containerId",
"==",
"-",
"1",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Command to restart the entire topology: \"",
"+",
"LocalContext",
".",
"topologyName",
"(",
"config",
")",
")",
";",
"processesToRestart",
".",
"addAll",
"(",
"processToContainer",
".",
"keySet",
"(",
")",
")",
";",
"}",
"else",
"{",
"// restart that particular container",
"LOG",
".",
"info",
"(",
"\"Command to restart a container of topology: \"",
"+",
"LocalContext",
".",
"topologyName",
"(",
"config",
")",
")",
";",
"LOG",
".",
"info",
"(",
"\"Restart container requested: \"",
"+",
"containerId",
")",
";",
"// locate the container and destroy it",
"for",
"(",
"Process",
"p",
":",
"processToContainer",
".",
"keySet",
"(",
")",
")",
"{",
"if",
"(",
"containerId",
"==",
"processToContainer",
".",
"get",
"(",
"p",
")",
")",
"{",
"processesToRestart",
".",
"add",
"(",
"p",
")",
";",
"}",
"}",
"}",
"if",
"(",
"processesToRestart",
".",
"isEmpty",
"(",
")",
")",
"{",
"LOG",
".",
"severe",
"(",
"\"Container not exist.\"",
")",
";",
"return",
"false",
";",
"}",
"for",
"(",
"Process",
"process",
":",
"processesToRestart",
")",
"{",
"process",
".",
"destroy",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Handler to restart topology | [
"Handler",
"to",
"restart",
"topology"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/local/LocalScheduler.java#L248-L281 |
27,940 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/aurora/AuroraHeronShellController.java | AuroraHeronShellController.restart | @Override
public boolean restart(Integer containerId) {
// there is no backpressure for container 0, delegate to aurora client
if (containerId == null || containerId == 0) {
return cliController.restart(containerId);
}
if (stateMgrAdaptor == null) {
LOG.warning("SchedulerStateManagerAdaptor not initialized");
return false;
}
StMgr sm = searchContainer(containerId);
if (sm == null) {
LOG.warning("container not found in pplan " + containerId);
return false;
}
String url = "http://" + sm.getHostName() + ":" + sm.getShellPort() + "/killexecutor";
String payload = "secret=" + stateMgrAdaptor.getExecutionState(topologyName).getTopologyId();
LOG.info("sending `kill container` to " + url + "; payload: " + payload);
HttpURLConnection con = NetworkUtils.getHttpConnection(url);
try {
if (NetworkUtils.sendHttpPostRequest(con, "X", payload.getBytes())) {
return NetworkUtils.checkHttpResponseCode(con, 200);
} else { // if heron-shell command fails, delegate to aurora client
LOG.info("heron-shell killexecutor failed; try aurora client ..");
return cliController.restart(containerId);
}
} finally {
con.disconnect();
}
} | java | @Override
public boolean restart(Integer containerId) {
// there is no backpressure for container 0, delegate to aurora client
if (containerId == null || containerId == 0) {
return cliController.restart(containerId);
}
if (stateMgrAdaptor == null) {
LOG.warning("SchedulerStateManagerAdaptor not initialized");
return false;
}
StMgr sm = searchContainer(containerId);
if (sm == null) {
LOG.warning("container not found in pplan " + containerId);
return false;
}
String url = "http://" + sm.getHostName() + ":" + sm.getShellPort() + "/killexecutor";
String payload = "secret=" + stateMgrAdaptor.getExecutionState(topologyName).getTopologyId();
LOG.info("sending `kill container` to " + url + "; payload: " + payload);
HttpURLConnection con = NetworkUtils.getHttpConnection(url);
try {
if (NetworkUtils.sendHttpPostRequest(con, "X", payload.getBytes())) {
return NetworkUtils.checkHttpResponseCode(con, 200);
} else { // if heron-shell command fails, delegate to aurora client
LOG.info("heron-shell killexecutor failed; try aurora client ..");
return cliController.restart(containerId);
}
} finally {
con.disconnect();
}
} | [
"@",
"Override",
"public",
"boolean",
"restart",
"(",
"Integer",
"containerId",
")",
"{",
"// there is no backpressure for container 0, delegate to aurora client",
"if",
"(",
"containerId",
"==",
"null",
"||",
"containerId",
"==",
"0",
")",
"{",
"return",
"cliController",
".",
"restart",
"(",
"containerId",
")",
";",
"}",
"if",
"(",
"stateMgrAdaptor",
"==",
"null",
")",
"{",
"LOG",
".",
"warning",
"(",
"\"SchedulerStateManagerAdaptor not initialized\"",
")",
";",
"return",
"false",
";",
"}",
"StMgr",
"sm",
"=",
"searchContainer",
"(",
"containerId",
")",
";",
"if",
"(",
"sm",
"==",
"null",
")",
"{",
"LOG",
".",
"warning",
"(",
"\"container not found in pplan \"",
"+",
"containerId",
")",
";",
"return",
"false",
";",
"}",
"String",
"url",
"=",
"\"http://\"",
"+",
"sm",
".",
"getHostName",
"(",
")",
"+",
"\":\"",
"+",
"sm",
".",
"getShellPort",
"(",
")",
"+",
"\"/killexecutor\"",
";",
"String",
"payload",
"=",
"\"secret=\"",
"+",
"stateMgrAdaptor",
".",
"getExecutionState",
"(",
"topologyName",
")",
".",
"getTopologyId",
"(",
")",
";",
"LOG",
".",
"info",
"(",
"\"sending `kill container` to \"",
"+",
"url",
"+",
"\"; payload: \"",
"+",
"payload",
")",
";",
"HttpURLConnection",
"con",
"=",
"NetworkUtils",
".",
"getHttpConnection",
"(",
"url",
")",
";",
"try",
"{",
"if",
"(",
"NetworkUtils",
".",
"sendHttpPostRequest",
"(",
"con",
",",
"\"X\"",
",",
"payload",
".",
"getBytes",
"(",
")",
")",
")",
"{",
"return",
"NetworkUtils",
".",
"checkHttpResponseCode",
"(",
"con",
",",
"200",
")",
";",
"}",
"else",
"{",
"// if heron-shell command fails, delegate to aurora client",
"LOG",
".",
"info",
"(",
"\"heron-shell killexecutor failed; try aurora client ..\"",
")",
";",
"return",
"cliController",
".",
"restart",
"(",
"containerId",
")",
";",
"}",
"}",
"finally",
"{",
"con",
".",
"disconnect",
"(",
")",
";",
"}",
"}"
] | Restart an aurora container | [
"Restart",
"an",
"aurora",
"container"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/aurora/AuroraHeronShellController.java#L88-L121 |
27,941 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/TaskResources.java | TaskResources.canSatisfy | public boolean canSatisfy(TaskResources needed) {
return this.ports >= needed.ports
&& (this.cpu >= needed.cpu)
&& (this.mem >= needed.mem)
&& (this.disk >= needed.disk);
} | java | public boolean canSatisfy(TaskResources needed) {
return this.ports >= needed.ports
&& (this.cpu >= needed.cpu)
&& (this.mem >= needed.mem)
&& (this.disk >= needed.disk);
} | [
"public",
"boolean",
"canSatisfy",
"(",
"TaskResources",
"needed",
")",
"{",
"return",
"this",
".",
"ports",
">=",
"needed",
".",
"ports",
"&&",
"(",
"this",
".",
"cpu",
">=",
"needed",
".",
"cpu",
")",
"&&",
"(",
"this",
".",
"mem",
">=",
"needed",
".",
"mem",
")",
"&&",
"(",
"this",
".",
"disk",
">=",
"needed",
".",
"disk",
")",
";",
"}"
] | Whether this resource can satisfy the TaskResources needed from parameter | [
"Whether",
"this",
"resource",
"can",
"satisfy",
"the",
"TaskResources",
"needed",
"from",
"parameter"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/TaskResources.java#L74-L79 |
27,942 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/TaskResources.java | TaskResources.apply | public static TaskResources apply(Protos.Offer offer, String role) {
double cpu = 0;
double mem = 0;
double disk = 0;
List<Range> portsResource = new ArrayList<>();
for (Protos.Resource r : offer.getResourcesList()) {
if (!r.hasRole() || r.getRole().equals("*") || r.getRole().equals(role)) {
if (r.getName().equals(CPUS_RESOURCE_NAME)) {
cpu = r.getScalar().getValue();
}
if (r.getName().equals(MEM_RESOURCE_NAME)) {
mem = r.getScalar().getValue();
}
if (r.getName().equals(DISK_RESOURCE_NAME)) {
disk = r.getScalar().getValue();
}
if (r.getName().equals(PORT_RESOURCE_NAME)) {
Protos.Value.Ranges ranges = r.getRanges();
for (Protos.Value.Range range : ranges.getRangeList()) {
portsResource.add(new Range(range.getBegin(), range.getEnd()));
}
}
}
}
return new TaskResources(cpu, mem, disk, portsResource);
} | java | public static TaskResources apply(Protos.Offer offer, String role) {
double cpu = 0;
double mem = 0;
double disk = 0;
List<Range> portsResource = new ArrayList<>();
for (Protos.Resource r : offer.getResourcesList()) {
if (!r.hasRole() || r.getRole().equals("*") || r.getRole().equals(role)) {
if (r.getName().equals(CPUS_RESOURCE_NAME)) {
cpu = r.getScalar().getValue();
}
if (r.getName().equals(MEM_RESOURCE_NAME)) {
mem = r.getScalar().getValue();
}
if (r.getName().equals(DISK_RESOURCE_NAME)) {
disk = r.getScalar().getValue();
}
if (r.getName().equals(PORT_RESOURCE_NAME)) {
Protos.Value.Ranges ranges = r.getRanges();
for (Protos.Value.Range range : ranges.getRangeList()) {
portsResource.add(new Range(range.getBegin(), range.getEnd()));
}
}
}
}
return new TaskResources(cpu, mem, disk, portsResource);
} | [
"public",
"static",
"TaskResources",
"apply",
"(",
"Protos",
".",
"Offer",
"offer",
",",
"String",
"role",
")",
"{",
"double",
"cpu",
"=",
"0",
";",
"double",
"mem",
"=",
"0",
";",
"double",
"disk",
"=",
"0",
";",
"List",
"<",
"Range",
">",
"portsResource",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Protos",
".",
"Resource",
"r",
":",
"offer",
".",
"getResourcesList",
"(",
")",
")",
"{",
"if",
"(",
"!",
"r",
".",
"hasRole",
"(",
")",
"||",
"r",
".",
"getRole",
"(",
")",
".",
"equals",
"(",
"\"*\"",
")",
"||",
"r",
".",
"getRole",
"(",
")",
".",
"equals",
"(",
"role",
")",
")",
"{",
"if",
"(",
"r",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"CPUS_RESOURCE_NAME",
")",
")",
"{",
"cpu",
"=",
"r",
".",
"getScalar",
"(",
")",
".",
"getValue",
"(",
")",
";",
"}",
"if",
"(",
"r",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"MEM_RESOURCE_NAME",
")",
")",
"{",
"mem",
"=",
"r",
".",
"getScalar",
"(",
")",
".",
"getValue",
"(",
")",
";",
"}",
"if",
"(",
"r",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"DISK_RESOURCE_NAME",
")",
")",
"{",
"disk",
"=",
"r",
".",
"getScalar",
"(",
")",
".",
"getValue",
"(",
")",
";",
"}",
"if",
"(",
"r",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"PORT_RESOURCE_NAME",
")",
")",
"{",
"Protos",
".",
"Value",
".",
"Ranges",
"ranges",
"=",
"r",
".",
"getRanges",
"(",
")",
";",
"for",
"(",
"Protos",
".",
"Value",
".",
"Range",
"range",
":",
"ranges",
".",
"getRangeList",
"(",
")",
")",
"{",
"portsResource",
".",
"add",
"(",
"new",
"Range",
"(",
"range",
".",
"getBegin",
"(",
")",
",",
"range",
".",
"getEnd",
"(",
")",
")",
")",
";",
"}",
"}",
"}",
"}",
"return",
"new",
"TaskResources",
"(",
"cpu",
",",
"mem",
",",
"disk",
",",
"portsResource",
")",
";",
"}"
] | A static method to construct a TaskResources from mesos Protos.Offer | [
"A",
"static",
"method",
"to",
"construct",
"a",
"TaskResources",
"from",
"mesos",
"Protos",
".",
"Offer"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/mesos/framework/TaskResources.java#L128-L155 |
27,943 | apache/incubator-heron | heron/instance/src/java/org/apache/heron/metrics/GatewayMetrics.java | GatewayMetrics.registerMetrics | public void registerMetrics(MetricsCollector metricsCollector) {
SystemConfig systemConfig =
(SystemConfig) SingletonRegistry.INSTANCE.getSingleton(SystemConfig.HERON_SYSTEM_CONFIG);
int interval = (int) systemConfig.getHeronMetricsExportInterval().getSeconds();
metricsCollector.registerMetric("__gateway-received-packets-size",
receivedPacketsSize,
interval);
metricsCollector.registerMetric("__gateway-sent-packets-size",
sentPacketsSize,
interval);
metricsCollector.registerMetric("__gateway-received-packets-count",
receivedPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-packets-count",
sentPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-size",
sentMetricsSize,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-packets-count",
sentMetricsPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-count",
sentMetricsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-exceptions-count",
sentExceptionsCount,
interval);
metricsCollector.registerMetric("__gateway-in-stream-queue-size",
inStreamQueueSize,
interval);
metricsCollector.registerMetric("__gateway-out-stream-queue-size",
outStreamQueueSize,
interval);
metricsCollector.registerMetric("__gateway-in-stream-queue-expected-capacity",
inStreamQueueExpectedCapacity,
interval);
metricsCollector.registerMetric("__gateway-out-stream-queue-expected-capacity",
outStreamQueueExpectedCapacity,
interval);
metricsCollector.registerMetric("__gateway-in-queue-full-count",
inQueueFullCount,
interval);
} | java | public void registerMetrics(MetricsCollector metricsCollector) {
SystemConfig systemConfig =
(SystemConfig) SingletonRegistry.INSTANCE.getSingleton(SystemConfig.HERON_SYSTEM_CONFIG);
int interval = (int) systemConfig.getHeronMetricsExportInterval().getSeconds();
metricsCollector.registerMetric("__gateway-received-packets-size",
receivedPacketsSize,
interval);
metricsCollector.registerMetric("__gateway-sent-packets-size",
sentPacketsSize,
interval);
metricsCollector.registerMetric("__gateway-received-packets-count",
receivedPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-packets-count",
sentPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-size",
sentMetricsSize,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-packets-count",
sentMetricsPacketsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-metrics-count",
sentMetricsCount,
interval);
metricsCollector.registerMetric("__gateway-sent-exceptions-count",
sentExceptionsCount,
interval);
metricsCollector.registerMetric("__gateway-in-stream-queue-size",
inStreamQueueSize,
interval);
metricsCollector.registerMetric("__gateway-out-stream-queue-size",
outStreamQueueSize,
interval);
metricsCollector.registerMetric("__gateway-in-stream-queue-expected-capacity",
inStreamQueueExpectedCapacity,
interval);
metricsCollector.registerMetric("__gateway-out-stream-queue-expected-capacity",
outStreamQueueExpectedCapacity,
interval);
metricsCollector.registerMetric("__gateway-in-queue-full-count",
inQueueFullCount,
interval);
} | [
"public",
"void",
"registerMetrics",
"(",
"MetricsCollector",
"metricsCollector",
")",
"{",
"SystemConfig",
"systemConfig",
"=",
"(",
"SystemConfig",
")",
"SingletonRegistry",
".",
"INSTANCE",
".",
"getSingleton",
"(",
"SystemConfig",
".",
"HERON_SYSTEM_CONFIG",
")",
";",
"int",
"interval",
"=",
"(",
"int",
")",
"systemConfig",
".",
"getHeronMetricsExportInterval",
"(",
")",
".",
"getSeconds",
"(",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-received-packets-size\"",
",",
"receivedPacketsSize",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-packets-size\"",
",",
"sentPacketsSize",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-received-packets-count\"",
",",
"receivedPacketsCount",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-packets-count\"",
",",
"sentPacketsCount",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-metrics-size\"",
",",
"sentMetricsSize",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-metrics-packets-count\"",
",",
"sentMetricsPacketsCount",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-metrics-count\"",
",",
"sentMetricsCount",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-sent-exceptions-count\"",
",",
"sentExceptionsCount",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-in-stream-queue-size\"",
",",
"inStreamQueueSize",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-out-stream-queue-size\"",
",",
"outStreamQueueSize",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-in-stream-queue-expected-capacity\"",
",",
"inStreamQueueExpectedCapacity",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-out-stream-queue-expected-capacity\"",
",",
"outStreamQueueExpectedCapacity",
",",
"interval",
")",
";",
"metricsCollector",
".",
"registerMetric",
"(",
"\"__gateway-in-queue-full-count\"",
",",
"inQueueFullCount",
",",
"interval",
")",
";",
"}"
] | Register default Gateway Metrics to given MetricsCollector
@param metricsCollector the MetricsCollector to register Metrics on | [
"Register",
"default",
"Gateway",
"Metrics",
"to",
"given",
"MetricsCollector"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/instance/src/java/org/apache/heron/metrics/GatewayMetrics.java#L86-L134 |
27,944 | apache/incubator-heron | heron/metricsmgr/src/java/org/apache/heron/metricsmgr/MetricsManagerServer.java | MetricsManagerServer.onInternalMessage | public void onInternalMessage(Metrics.MetricPublisher request,
Metrics.MetricPublisherPublishMessage message) {
handlePublisherPublishMessage(request, message);
} | java | public void onInternalMessage(Metrics.MetricPublisher request,
Metrics.MetricPublisherPublishMessage message) {
handlePublisherPublishMessage(request, message);
} | [
"public",
"void",
"onInternalMessage",
"(",
"Metrics",
".",
"MetricPublisher",
"request",
",",
"Metrics",
".",
"MetricPublisherPublishMessage",
"message",
")",
"{",
"handlePublisherPublishMessage",
"(",
"request",
",",
"message",
")",
";",
"}"
] | This method is thread-safe, since we would push Messages into a Concurrent Queue. | [
"This",
"method",
"is",
"thread",
"-",
"safe",
"since",
"we",
"would",
"push",
"Messages",
"into",
"a",
"Concurrent",
"Queue",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricsmgr/src/java/org/apache/heron/metricsmgr/MetricsManagerServer.java#L197-L200 |
27,945 | apache/incubator-heron | heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/tmaster/TMasterSink.java | TMasterSink.startTMasterChecker | private void startTMasterChecker() {
final int checkIntervalSec =
TypeUtils.getInteger(sinkConfig.get(KEY_TMASTER_LOCATION_CHECK_INTERVAL_SEC));
Runnable runnable = new Runnable() {
@Override
public void run() {
TopologyMaster.TMasterLocation location =
(TopologyMaster.TMasterLocation) SingletonRegistry.INSTANCE.getSingleton(
TMASTER_LOCATION_BEAN_NAME);
if (location != null) {
if (currentTMasterLocation == null || !location.equals(currentTMasterLocation)) {
LOG.info("Update current TMasterLocation to: " + location);
currentTMasterLocation = location;
tMasterClientService.updateTMasterLocation(currentTMasterLocation);
tMasterClientService.startNewMasterClient();
// Update Metrics
sinkContext.exportCountMetric(TMASTER_LOCATION_UPDATE_COUNT, 1);
}
}
// Schedule itself in future
tMasterLocationStarter.schedule(this, checkIntervalSec, TimeUnit.SECONDS);
}
};
// First Entry
tMasterLocationStarter.schedule(runnable, checkIntervalSec, TimeUnit.SECONDS);
LOG.info("TMasterChecker started with interval: " + checkIntervalSec);
} | java | private void startTMasterChecker() {
final int checkIntervalSec =
TypeUtils.getInteger(sinkConfig.get(KEY_TMASTER_LOCATION_CHECK_INTERVAL_SEC));
Runnable runnable = new Runnable() {
@Override
public void run() {
TopologyMaster.TMasterLocation location =
(TopologyMaster.TMasterLocation) SingletonRegistry.INSTANCE.getSingleton(
TMASTER_LOCATION_BEAN_NAME);
if (location != null) {
if (currentTMasterLocation == null || !location.equals(currentTMasterLocation)) {
LOG.info("Update current TMasterLocation to: " + location);
currentTMasterLocation = location;
tMasterClientService.updateTMasterLocation(currentTMasterLocation);
tMasterClientService.startNewMasterClient();
// Update Metrics
sinkContext.exportCountMetric(TMASTER_LOCATION_UPDATE_COUNT, 1);
}
}
// Schedule itself in future
tMasterLocationStarter.schedule(this, checkIntervalSec, TimeUnit.SECONDS);
}
};
// First Entry
tMasterLocationStarter.schedule(runnable, checkIntervalSec, TimeUnit.SECONDS);
LOG.info("TMasterChecker started with interval: " + checkIntervalSec);
} | [
"private",
"void",
"startTMasterChecker",
"(",
")",
"{",
"final",
"int",
"checkIntervalSec",
"=",
"TypeUtils",
".",
"getInteger",
"(",
"sinkConfig",
".",
"get",
"(",
"KEY_TMASTER_LOCATION_CHECK_INTERVAL_SEC",
")",
")",
";",
"Runnable",
"runnable",
"=",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"TopologyMaster",
".",
"TMasterLocation",
"location",
"=",
"(",
"TopologyMaster",
".",
"TMasterLocation",
")",
"SingletonRegistry",
".",
"INSTANCE",
".",
"getSingleton",
"(",
"TMASTER_LOCATION_BEAN_NAME",
")",
";",
"if",
"(",
"location",
"!=",
"null",
")",
"{",
"if",
"(",
"currentTMasterLocation",
"==",
"null",
"||",
"!",
"location",
".",
"equals",
"(",
"currentTMasterLocation",
")",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Update current TMasterLocation to: \"",
"+",
"location",
")",
";",
"currentTMasterLocation",
"=",
"location",
";",
"tMasterClientService",
".",
"updateTMasterLocation",
"(",
"currentTMasterLocation",
")",
";",
"tMasterClientService",
".",
"startNewMasterClient",
"(",
")",
";",
"// Update Metrics",
"sinkContext",
".",
"exportCountMetric",
"(",
"TMASTER_LOCATION_UPDATE_COUNT",
",",
"1",
")",
";",
"}",
"}",
"// Schedule itself in future",
"tMasterLocationStarter",
".",
"schedule",
"(",
"this",
",",
"checkIntervalSec",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}",
"}",
";",
"// First Entry",
"tMasterLocationStarter",
".",
"schedule",
"(",
"runnable",
",",
"checkIntervalSec",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"LOG",
".",
"info",
"(",
"\"TMasterChecker started with interval: \"",
"+",
"checkIntervalSec",
")",
";",
"}"
] | If so, restart the TMasterClientService with the new TMasterLocation | [
"If",
"so",
"restart",
"the",
"TMasterClientService",
"with",
"the",
"new",
"TMasterLocation"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/tmaster/TMasterSink.java#L161-L192 |
27,946 | apache/incubator-heron | heron/statemgrs/src/java/org/apache/heron/statemgr/zookeeper/ZkUtils.java | ZkUtils.setupZkTunnel | public static Pair<String, List<Process>> setupZkTunnel(Config config,
NetworkUtils.TunnelConfig tunnelConfig) {
// Remove all spaces
String connectionString = Context.stateManagerConnectionString(config).replaceAll("\\s+", "");
List<Pair<InetSocketAddress, Process>> ret = new ArrayList<>();
// For zookeeper, connection String can be a list of host:port, separated by comma
String[] endpoints = connectionString.split(",");
for (String endpoint : endpoints) {
InetSocketAddress address = NetworkUtils.getInetSocketAddress(endpoint);
// Get the tunnel process if needed
Pair<InetSocketAddress, Process> pair =
NetworkUtils.establishSSHTunnelIfNeeded(
address, tunnelConfig, NetworkUtils.TunnelType.PORT_FORWARD);
ret.add(pair);
}
// Construct the new ConnectionString and tunnel processes
StringBuilder connectionStringBuilder = new StringBuilder();
List<Process> tunnelProcesses = new ArrayList<>();
String delim = "";
for (Pair<InetSocketAddress, Process> pair : ret) {
// Join the list of String with comma as delim
if (pair.first != null) {
connectionStringBuilder.append(delim).
append(pair.first.getHostName()).append(":").append(pair.first.getPort());
delim = ",";
// If tunneled
if (pair.second != null) {
tunnelProcesses.add(pair.second);
}
}
}
String newConnectionString = connectionStringBuilder.toString();
return new Pair<String, List<Process>>(newConnectionString, tunnelProcesses);
} | java | public static Pair<String, List<Process>> setupZkTunnel(Config config,
NetworkUtils.TunnelConfig tunnelConfig) {
// Remove all spaces
String connectionString = Context.stateManagerConnectionString(config).replaceAll("\\s+", "");
List<Pair<InetSocketAddress, Process>> ret = new ArrayList<>();
// For zookeeper, connection String can be a list of host:port, separated by comma
String[] endpoints = connectionString.split(",");
for (String endpoint : endpoints) {
InetSocketAddress address = NetworkUtils.getInetSocketAddress(endpoint);
// Get the tunnel process if needed
Pair<InetSocketAddress, Process> pair =
NetworkUtils.establishSSHTunnelIfNeeded(
address, tunnelConfig, NetworkUtils.TunnelType.PORT_FORWARD);
ret.add(pair);
}
// Construct the new ConnectionString and tunnel processes
StringBuilder connectionStringBuilder = new StringBuilder();
List<Process> tunnelProcesses = new ArrayList<>();
String delim = "";
for (Pair<InetSocketAddress, Process> pair : ret) {
// Join the list of String with comma as delim
if (pair.first != null) {
connectionStringBuilder.append(delim).
append(pair.first.getHostName()).append(":").append(pair.first.getPort());
delim = ",";
// If tunneled
if (pair.second != null) {
tunnelProcesses.add(pair.second);
}
}
}
String newConnectionString = connectionStringBuilder.toString();
return new Pair<String, List<Process>>(newConnectionString, tunnelProcesses);
} | [
"public",
"static",
"Pair",
"<",
"String",
",",
"List",
"<",
"Process",
">",
">",
"setupZkTunnel",
"(",
"Config",
"config",
",",
"NetworkUtils",
".",
"TunnelConfig",
"tunnelConfig",
")",
"{",
"// Remove all spaces",
"String",
"connectionString",
"=",
"Context",
".",
"stateManagerConnectionString",
"(",
"config",
")",
".",
"replaceAll",
"(",
"\"\\\\s+\"",
",",
"\"\"",
")",
";",
"List",
"<",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
">",
"ret",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"// For zookeeper, connection String can be a list of host:port, separated by comma",
"String",
"[",
"]",
"endpoints",
"=",
"connectionString",
".",
"split",
"(",
"\",\"",
")",
";",
"for",
"(",
"String",
"endpoint",
":",
"endpoints",
")",
"{",
"InetSocketAddress",
"address",
"=",
"NetworkUtils",
".",
"getInetSocketAddress",
"(",
"endpoint",
")",
";",
"// Get the tunnel process if needed",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"pair",
"=",
"NetworkUtils",
".",
"establishSSHTunnelIfNeeded",
"(",
"address",
",",
"tunnelConfig",
",",
"NetworkUtils",
".",
"TunnelType",
".",
"PORT_FORWARD",
")",
";",
"ret",
".",
"add",
"(",
"pair",
")",
";",
"}",
"// Construct the new ConnectionString and tunnel processes",
"StringBuilder",
"connectionStringBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"List",
"<",
"Process",
">",
"tunnelProcesses",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"String",
"delim",
"=",
"\"\"",
";",
"for",
"(",
"Pair",
"<",
"InetSocketAddress",
",",
"Process",
">",
"pair",
":",
"ret",
")",
"{",
"// Join the list of String with comma as delim",
"if",
"(",
"pair",
".",
"first",
"!=",
"null",
")",
"{",
"connectionStringBuilder",
".",
"append",
"(",
"delim",
")",
".",
"append",
"(",
"pair",
".",
"first",
".",
"getHostName",
"(",
")",
")",
".",
"append",
"(",
"\":\"",
")",
".",
"append",
"(",
"pair",
".",
"first",
".",
"getPort",
"(",
")",
")",
";",
"delim",
"=",
"\",\"",
";",
"// If tunneled",
"if",
"(",
"pair",
".",
"second",
"!=",
"null",
")",
"{",
"tunnelProcesses",
".",
"add",
"(",
"pair",
".",
"second",
")",
";",
"}",
"}",
"}",
"String",
"newConnectionString",
"=",
"connectionStringBuilder",
".",
"toString",
"(",
")",
";",
"return",
"new",
"Pair",
"<",
"String",
",",
"List",
"<",
"Process",
">",
">",
"(",
"newConnectionString",
",",
"tunnelProcesses",
")",
";",
"}"
] | Setup the tunnel if needed
@param config basing on which we setup the tunnel process
@return Pair of (zk_format_connectionString, List of tunneled processes) | [
"Setup",
"the",
"tunnel",
"if",
"needed"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/statemgrs/src/java/org/apache/heron/statemgr/zookeeper/ZkUtils.java#L47-L88 |
27,947 | apache/incubator-heron | heron/api/src/java/org/apache/heron/api/utils/DefaultMaxSpoutPendingTuner.java | DefaultMaxSpoutPendingTuner.autoTune | public void autoTune(Long progress) {
// LOG.info ("Called auto tune with progress " + progress);
if (lastAction == ACTION.NOOP) {
// We did not take any action last time
if (prevProgress == -1) {
// The first time around when we are called
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (moreThanNum(progress, prevProgress, progressBound)) {
// We have seen a sudden increase in progress in the steady state (NOOP) try to push
// the max spout pending limit even more
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (lessThanNum(progress, prevProgress, progressBound)) {
// We have seen a sudden drop in progress in the steady state try to decrease
// the max spout pending proportionately to see if we can introduce an improvement
// in progress;
doAction(ACTION.DECREASE,
Math.max((prevProgress - progress) / (float) prevProgress, autoTuneFactor), progress);
} else {
++callsInNoop;
// If the progress remains the same then once in a while try increasing the
// max spout pending.
if (callsInNoop >= NOOP_THRESHOLD) {
doAction(speculativeAction, autoTuneFactor, progress);
speculativeAction =
speculativeAction == ACTION.INCREASE ? ACTION.DECREASE : ACTION.INCREASE;
}
}
} else if (lastAction == ACTION.INCREASE) {
if (moreThanNum(progress, prevProgress, autoTuneFactor - progressBound)) {
// Our increase last time did result in a commisurate increase. Increase even more
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (lessThanNum(progress, prevProgress, progressBound)) {
// Our increase last time actually resulted in a decrease.
// Check how much we decreased. If our decrease was disproportionate
// decrease accordingly.
float drop = Math.max((prevProgress - progress) / (float) prevProgress, autoTuneFactor);
if (drop > autoTuneFactor) {
doAction(ACTION.DECREASE, drop, progress);
} else {
doAction(ACTION.RESTORE, autoTuneFactor, progress);
}
} else {
// Our increase last time did not really change anything. So restore.
doAction(ACTION.RESTORE, autoTuneFactor, progress);
}
} else if (lastAction == ACTION.DECREASE) {
if (moreThanNum(progress, prevProgress, progressBound)) {
// We actually saw an increase in progress. So decrease more
doAction(ACTION.DECREASE, autoTuneFactor, progress);
} else {
// Hold off any decision. We will take any decision next time around.
doAction(ACTION.NOOP, autoTuneFactor, progress);
}
} else if (lastAction == ACTION.RESTORE) {
// Lets ignore the effects of the restore and wait out for the next cycle
doAction(ACTION.NOOP, autoTuneFactor, progress);
}
} | java | public void autoTune(Long progress) {
// LOG.info ("Called auto tune with progress " + progress);
if (lastAction == ACTION.NOOP) {
// We did not take any action last time
if (prevProgress == -1) {
// The first time around when we are called
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (moreThanNum(progress, prevProgress, progressBound)) {
// We have seen a sudden increase in progress in the steady state (NOOP) try to push
// the max spout pending limit even more
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (lessThanNum(progress, prevProgress, progressBound)) {
// We have seen a sudden drop in progress in the steady state try to decrease
// the max spout pending proportionately to see if we can introduce an improvement
// in progress;
doAction(ACTION.DECREASE,
Math.max((prevProgress - progress) / (float) prevProgress, autoTuneFactor), progress);
} else {
++callsInNoop;
// If the progress remains the same then once in a while try increasing the
// max spout pending.
if (callsInNoop >= NOOP_THRESHOLD) {
doAction(speculativeAction, autoTuneFactor, progress);
speculativeAction =
speculativeAction == ACTION.INCREASE ? ACTION.DECREASE : ACTION.INCREASE;
}
}
} else if (lastAction == ACTION.INCREASE) {
if (moreThanNum(progress, prevProgress, autoTuneFactor - progressBound)) {
// Our increase last time did result in a commisurate increase. Increase even more
doAction(ACTION.INCREASE, autoTuneFactor, progress);
} else if (lessThanNum(progress, prevProgress, progressBound)) {
// Our increase last time actually resulted in a decrease.
// Check how much we decreased. If our decrease was disproportionate
// decrease accordingly.
float drop = Math.max((prevProgress - progress) / (float) prevProgress, autoTuneFactor);
if (drop > autoTuneFactor) {
doAction(ACTION.DECREASE, drop, progress);
} else {
doAction(ACTION.RESTORE, autoTuneFactor, progress);
}
} else {
// Our increase last time did not really change anything. So restore.
doAction(ACTION.RESTORE, autoTuneFactor, progress);
}
} else if (lastAction == ACTION.DECREASE) {
if (moreThanNum(progress, prevProgress, progressBound)) {
// We actually saw an increase in progress. So decrease more
doAction(ACTION.DECREASE, autoTuneFactor, progress);
} else {
// Hold off any decision. We will take any decision next time around.
doAction(ACTION.NOOP, autoTuneFactor, progress);
}
} else if (lastAction == ACTION.RESTORE) {
// Lets ignore the effects of the restore and wait out for the next cycle
doAction(ACTION.NOOP, autoTuneFactor, progress);
}
} | [
"public",
"void",
"autoTune",
"(",
"Long",
"progress",
")",
"{",
"// LOG.info (\"Called auto tune with progress \" + progress);",
"if",
"(",
"lastAction",
"==",
"ACTION",
".",
"NOOP",
")",
"{",
"// We did not take any action last time",
"if",
"(",
"prevProgress",
"==",
"-",
"1",
")",
"{",
"// The first time around when we are called",
"doAction",
"(",
"ACTION",
".",
"INCREASE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"else",
"if",
"(",
"moreThanNum",
"(",
"progress",
",",
"prevProgress",
",",
"progressBound",
")",
")",
"{",
"// We have seen a sudden increase in progress in the steady state (NOOP) try to push",
"// the max spout pending limit even more",
"doAction",
"(",
"ACTION",
".",
"INCREASE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"else",
"if",
"(",
"lessThanNum",
"(",
"progress",
",",
"prevProgress",
",",
"progressBound",
")",
")",
"{",
"// We have seen a sudden drop in progress in the steady state try to decrease",
"// the max spout pending proportionately to see if we can introduce an improvement",
"// in progress;",
"doAction",
"(",
"ACTION",
".",
"DECREASE",
",",
"Math",
".",
"max",
"(",
"(",
"prevProgress",
"-",
"progress",
")",
"/",
"(",
"float",
")",
"prevProgress",
",",
"autoTuneFactor",
")",
",",
"progress",
")",
";",
"}",
"else",
"{",
"++",
"callsInNoop",
";",
"// If the progress remains the same then once in a while try increasing the",
"// max spout pending.",
"if",
"(",
"callsInNoop",
">=",
"NOOP_THRESHOLD",
")",
"{",
"doAction",
"(",
"speculativeAction",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"speculativeAction",
"=",
"speculativeAction",
"==",
"ACTION",
".",
"INCREASE",
"?",
"ACTION",
".",
"DECREASE",
":",
"ACTION",
".",
"INCREASE",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"lastAction",
"==",
"ACTION",
".",
"INCREASE",
")",
"{",
"if",
"(",
"moreThanNum",
"(",
"progress",
",",
"prevProgress",
",",
"autoTuneFactor",
"-",
"progressBound",
")",
")",
"{",
"// Our increase last time did result in a commisurate increase. Increase even more",
"doAction",
"(",
"ACTION",
".",
"INCREASE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"else",
"if",
"(",
"lessThanNum",
"(",
"progress",
",",
"prevProgress",
",",
"progressBound",
")",
")",
"{",
"// Our increase last time actually resulted in a decrease.",
"// Check how much we decreased. If our decrease was disproportionate",
"// decrease accordingly.",
"float",
"drop",
"=",
"Math",
".",
"max",
"(",
"(",
"prevProgress",
"-",
"progress",
")",
"/",
"(",
"float",
")",
"prevProgress",
",",
"autoTuneFactor",
")",
";",
"if",
"(",
"drop",
">",
"autoTuneFactor",
")",
"{",
"doAction",
"(",
"ACTION",
".",
"DECREASE",
",",
"drop",
",",
"progress",
")",
";",
"}",
"else",
"{",
"doAction",
"(",
"ACTION",
".",
"RESTORE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"}",
"else",
"{",
"// Our increase last time did not really change anything. So restore.",
"doAction",
"(",
"ACTION",
".",
"RESTORE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"}",
"else",
"if",
"(",
"lastAction",
"==",
"ACTION",
".",
"DECREASE",
")",
"{",
"if",
"(",
"moreThanNum",
"(",
"progress",
",",
"prevProgress",
",",
"progressBound",
")",
")",
"{",
"// We actually saw an increase in progress. So decrease more",
"doAction",
"(",
"ACTION",
".",
"DECREASE",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"else",
"{",
"// Hold off any decision. We will take any decision next time around.",
"doAction",
"(",
"ACTION",
".",
"NOOP",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"}",
"else",
"if",
"(",
"lastAction",
"==",
"ACTION",
".",
"RESTORE",
")",
"{",
"// Lets ignore the effects of the restore and wait out for the next cycle",
"doAction",
"(",
"ACTION",
".",
"NOOP",
",",
"autoTuneFactor",
",",
"progress",
")",
";",
"}",
"}"
] | Tune max default max spout pending based on progress | [
"Tune",
"max",
"default",
"max",
"spout",
"pending",
"based",
"on",
"progress"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/utils/DefaultMaxSpoutPendingTuner.java#L93-L151 |
27,948 | apache/incubator-heron | heron/api/src/java/org/apache/heron/classification/HeronAnnotationProcessor.java | HeronAnnotationProcessor.process | @Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
for (TypeElement te : annotations) {
for (Element elt : roundEnv.getElementsAnnotatedWith(te)) {
if (!elt.toString().startsWith("org.apache.heron")) {
env.getMessager().printMessage(
Kind.WARNING,
String.format("%s extends from a class annotated with %s", elt, te),
elt);
}
}
}
}
return true;
} | java | @Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!roundEnv.processingOver()) {
for (TypeElement te : annotations) {
for (Element elt : roundEnv.getElementsAnnotatedWith(te)) {
if (!elt.toString().startsWith("org.apache.heron")) {
env.getMessager().printMessage(
Kind.WARNING,
String.format("%s extends from a class annotated with %s", elt, te),
elt);
}
}
}
}
return true;
} | [
"@",
"Override",
"public",
"boolean",
"process",
"(",
"Set",
"<",
"?",
"extends",
"TypeElement",
">",
"annotations",
",",
"RoundEnvironment",
"roundEnv",
")",
"{",
"if",
"(",
"!",
"roundEnv",
".",
"processingOver",
"(",
")",
")",
"{",
"for",
"(",
"TypeElement",
"te",
":",
"annotations",
")",
"{",
"for",
"(",
"Element",
"elt",
":",
"roundEnv",
".",
"getElementsAnnotatedWith",
"(",
"te",
")",
")",
"{",
"if",
"(",
"!",
"elt",
".",
"toString",
"(",
")",
".",
"startsWith",
"(",
"\"org.apache.heron\"",
")",
")",
"{",
"env",
".",
"getMessager",
"(",
")",
".",
"printMessage",
"(",
"Kind",
".",
"WARNING",
",",
"String",
".",
"format",
"(",
"\"%s extends from a class annotated with %s\"",
",",
"elt",
",",
"te",
")",
",",
"elt",
")",
";",
"}",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | If a non-heron class extends from a class annotated as Unstable, Private or LimitedPrivate,
emit a warning. | [
"If",
"a",
"non",
"-",
"heron",
"class",
"extends",
"from",
"a",
"class",
"annotated",
"as",
"Unstable",
"Private",
"or",
"LimitedPrivate",
"emit",
"a",
"warning",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/classification/HeronAnnotationProcessor.java#L55-L70 |
27,949 | apache/incubator-heron | heron/tools/apiserver/src/java/org/apache/heron/apiserver/utils/ConfigUtils.java | ConfigUtils.applyOverridesToStateManagerConfig | @SuppressWarnings("unchecked")
public static void applyOverridesToStateManagerConfig(Path overridesPath,
Path stateManagerPath) throws IOException {
final Path tempStateManagerPath = Files.createTempFile("statemgr-", CONFIG_SUFFIX);
Reader stateManagerReader = null;
try (
Reader overrideReader = Files.newBufferedReader(overridesPath);
Writer writer = Files.newBufferedWriter(tempStateManagerPath);
) {
stateManagerReader = Files.newBufferedReader(stateManagerPath);
final Map<String, Object> overrides = (Map<String, Object>) new Yaml().load(overrideReader);
final Map<String, Object> stateMangerConfig =
(Map<String, Object>) new Yaml().load(stateManagerReader);
// update the state manager config with the overrides
for (Map.Entry<String, Object> entry : overrides.entrySet()) {
// does this key have an override?
if (stateMangerConfig.containsKey(entry.getKey())) {
stateMangerConfig.put(entry.getKey(), entry.getValue());
}
}
// write new state manager config
newYaml().dump(stateMangerConfig, writer);
// close state manager file so we can replace it with the updated configuration
stateManagerReader.close();
FileHelper.copy(tempStateManagerPath, stateManagerPath);
} finally {
tempStateManagerPath.toFile().delete();
SysUtils.closeIgnoringExceptions(stateManagerReader);
}
} | java | @SuppressWarnings("unchecked")
public static void applyOverridesToStateManagerConfig(Path overridesPath,
Path stateManagerPath) throws IOException {
final Path tempStateManagerPath = Files.createTempFile("statemgr-", CONFIG_SUFFIX);
Reader stateManagerReader = null;
try (
Reader overrideReader = Files.newBufferedReader(overridesPath);
Writer writer = Files.newBufferedWriter(tempStateManagerPath);
) {
stateManagerReader = Files.newBufferedReader(stateManagerPath);
final Map<String, Object> overrides = (Map<String, Object>) new Yaml().load(overrideReader);
final Map<String, Object> stateMangerConfig =
(Map<String, Object>) new Yaml().load(stateManagerReader);
// update the state manager config with the overrides
for (Map.Entry<String, Object> entry : overrides.entrySet()) {
// does this key have an override?
if (stateMangerConfig.containsKey(entry.getKey())) {
stateMangerConfig.put(entry.getKey(), entry.getValue());
}
}
// write new state manager config
newYaml().dump(stateMangerConfig, writer);
// close state manager file so we can replace it with the updated configuration
stateManagerReader.close();
FileHelper.copy(tempStateManagerPath, stateManagerPath);
} finally {
tempStateManagerPath.toFile().delete();
SysUtils.closeIgnoringExceptions(stateManagerReader);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"void",
"applyOverridesToStateManagerConfig",
"(",
"Path",
"overridesPath",
",",
"Path",
"stateManagerPath",
")",
"throws",
"IOException",
"{",
"final",
"Path",
"tempStateManagerPath",
"=",
"Files",
".",
"createTempFile",
"(",
"\"statemgr-\"",
",",
"CONFIG_SUFFIX",
")",
";",
"Reader",
"stateManagerReader",
"=",
"null",
";",
"try",
"(",
"Reader",
"overrideReader",
"=",
"Files",
".",
"newBufferedReader",
"(",
"overridesPath",
")",
";",
"Writer",
"writer",
"=",
"Files",
".",
"newBufferedWriter",
"(",
"tempStateManagerPath",
")",
";",
")",
"{",
"stateManagerReader",
"=",
"Files",
".",
"newBufferedReader",
"(",
"stateManagerPath",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"overrides",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"new",
"Yaml",
"(",
")",
".",
"load",
"(",
"overrideReader",
")",
";",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"stateMangerConfig",
"=",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"new",
"Yaml",
"(",
")",
".",
"load",
"(",
"stateManagerReader",
")",
";",
"// update the state manager config with the overrides",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"Object",
">",
"entry",
":",
"overrides",
".",
"entrySet",
"(",
")",
")",
"{",
"// does this key have an override?",
"if",
"(",
"stateMangerConfig",
".",
"containsKey",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
"{",
"stateMangerConfig",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"// write new state manager config",
"newYaml",
"(",
")",
".",
"dump",
"(",
"stateMangerConfig",
",",
"writer",
")",
";",
"// close state manager file so we can replace it with the updated configuration",
"stateManagerReader",
".",
"close",
"(",
")",
";",
"FileHelper",
".",
"copy",
"(",
"tempStateManagerPath",
",",
"stateManagerPath",
")",
";",
"}",
"finally",
"{",
"tempStateManagerPath",
".",
"toFile",
"(",
")",
".",
"delete",
"(",
")",
";",
"SysUtils",
".",
"closeIgnoringExceptions",
"(",
"stateManagerReader",
")",
";",
"}",
"}"
] | this is needed because the heron executor ignores the override.yaml | [
"this",
"is",
"needed",
"because",
"the",
"heron",
"executor",
"ignores",
"the",
"override",
".",
"yaml"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/tools/apiserver/src/java/org/apache/heron/apiserver/utils/ConfigUtils.java#L130-L163 |
27,950 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java | ByteAmount.minus | @Override
public ByteAmount minus(ResourceMeasure<Long> other) {
checkArgument(Long.MIN_VALUE + other.value <= value,
String.format("Subtracting %s from %s would overshoot Long.MIN_LONG", other, this));
return ByteAmount.fromBytes(value - other.value);
} | java | @Override
public ByteAmount minus(ResourceMeasure<Long> other) {
checkArgument(Long.MIN_VALUE + other.value <= value,
String.format("Subtracting %s from %s would overshoot Long.MIN_LONG", other, this));
return ByteAmount.fromBytes(value - other.value);
} | [
"@",
"Override",
"public",
"ByteAmount",
"minus",
"(",
"ResourceMeasure",
"<",
"Long",
">",
"other",
")",
"{",
"checkArgument",
"(",
"Long",
".",
"MIN_VALUE",
"+",
"other",
".",
"value",
"<=",
"value",
",",
"String",
".",
"format",
"(",
"\"Subtracting %s from %s would overshoot Long.MIN_LONG\"",
",",
"other",
",",
"this",
")",
")",
";",
"return",
"ByteAmount",
".",
"fromBytes",
"(",
"value",
"-",
"other",
".",
"value",
")",
";",
"}"
] | Subtracts other from this.
@param other ByteValue to subtract
@return a new ByteValue of this minus other ByteValue
@throws IllegalArgumentException if subtraction would overshoot Long.MIN_VALUE | [
"Subtracts",
"other",
"from",
"this",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java#L133-L138 |
27,951 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java | ByteAmount.plus | @Override
public ByteAmount plus(ResourceMeasure<Long> other) {
checkArgument(Long.MAX_VALUE - value >= other.value,
String.format("Adding %s to %s would exceed Long.MAX_LONG", other, this));
return ByteAmount.fromBytes(value + other.value);
} | java | @Override
public ByteAmount plus(ResourceMeasure<Long> other) {
checkArgument(Long.MAX_VALUE - value >= other.value,
String.format("Adding %s to %s would exceed Long.MAX_LONG", other, this));
return ByteAmount.fromBytes(value + other.value);
} | [
"@",
"Override",
"public",
"ByteAmount",
"plus",
"(",
"ResourceMeasure",
"<",
"Long",
">",
"other",
")",
"{",
"checkArgument",
"(",
"Long",
".",
"MAX_VALUE",
"-",
"value",
">=",
"other",
".",
"value",
",",
"String",
".",
"format",
"(",
"\"Adding %s to %s would exceed Long.MAX_LONG\"",
",",
"other",
",",
"this",
")",
")",
";",
"return",
"ByteAmount",
".",
"fromBytes",
"(",
"value",
"+",
"other",
".",
"value",
")",
";",
"}"
] | Adds other to this.
@param other ByteValue to add
@return a new ByteValue of this plus other ByteValue
@throws IllegalArgumentException if addition would exceed Long.MAX_VALUE | [
"Adds",
"other",
"to",
"this",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java#L146-L151 |
27,952 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java | ByteAmount.multiply | @Override
public ByteAmount multiply(int factor) {
checkArgument(value <= Long.MAX_VALUE / factor,
String.format("Multiplying %s by %d would exceed Long.MAX_LONG", this, factor));
return ByteAmount.fromBytes(value * factor);
} | java | @Override
public ByteAmount multiply(int factor) {
checkArgument(value <= Long.MAX_VALUE / factor,
String.format("Multiplying %s by %d would exceed Long.MAX_LONG", this, factor));
return ByteAmount.fromBytes(value * factor);
} | [
"@",
"Override",
"public",
"ByteAmount",
"multiply",
"(",
"int",
"factor",
")",
"{",
"checkArgument",
"(",
"value",
"<=",
"Long",
".",
"MAX_VALUE",
"/",
"factor",
",",
"String",
".",
"format",
"(",
"\"Multiplying %s by %d would exceed Long.MAX_LONG\"",
",",
"this",
",",
"factor",
")",
")",
";",
"return",
"ByteAmount",
".",
"fromBytes",
"(",
"value",
"*",
"factor",
")",
";",
"}"
] | Multiplies by factor
@param factor value to multiply by
@return a new ByteValue of this ByteValue multiplied by factor
@throws IllegalArgumentException if multiplication would exceed Long.MAX_VALUE | [
"Multiplies",
"by",
"factor"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java#L159-L164 |
27,953 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java | ByteAmount.increaseBy | @Override
public ByteAmount increaseBy(int percentage) {
checkArgument(percentage >= 0,
String.format("Increasing by negative percent (%d) not supported", percentage));
double factor = 1.0 + ((double) percentage / 100);
long max = Math.round(Long.MAX_VALUE / factor);
checkArgument(value <= max,
String.format("Increasing %s by %d percent would exceed Long.MAX_LONG", this, percentage));
return ByteAmount.fromBytes(Math.round(value.doubleValue() * factor));
} | java | @Override
public ByteAmount increaseBy(int percentage) {
checkArgument(percentage >= 0,
String.format("Increasing by negative percent (%d) not supported", percentage));
double factor = 1.0 + ((double) percentage / 100);
long max = Math.round(Long.MAX_VALUE / factor);
checkArgument(value <= max,
String.format("Increasing %s by %d percent would exceed Long.MAX_LONG", this, percentage));
return ByteAmount.fromBytes(Math.round(value.doubleValue() * factor));
} | [
"@",
"Override",
"public",
"ByteAmount",
"increaseBy",
"(",
"int",
"percentage",
")",
"{",
"checkArgument",
"(",
"percentage",
">=",
"0",
",",
"String",
".",
"format",
"(",
"\"Increasing by negative percent (%d) not supported\"",
",",
"percentage",
")",
")",
";",
"double",
"factor",
"=",
"1.0",
"+",
"(",
"(",
"double",
")",
"percentage",
"/",
"100",
")",
";",
"long",
"max",
"=",
"Math",
".",
"round",
"(",
"Long",
".",
"MAX_VALUE",
"/",
"factor",
")",
";",
"checkArgument",
"(",
"value",
"<=",
"max",
",",
"String",
".",
"format",
"(",
"\"Increasing %s by %d percent would exceed Long.MAX_LONG\"",
",",
"this",
",",
"percentage",
")",
")",
";",
"return",
"ByteAmount",
".",
"fromBytes",
"(",
"Math",
".",
"round",
"(",
"value",
".",
"doubleValue",
"(",
")",
"*",
"factor",
")",
")",
";",
"}"
] | Increases by a percentage, rounding any remainder. Be aware that because of rounding, increases
will be approximate to the nearest byte.
@param percentage value to increase by
@return a new ByteValue of this ByteValue increased by percentage
@throws IllegalArgumentException if increase would exceed Long.MAX_VALUE | [
"Increases",
"by",
"a",
"percentage",
"rounding",
"any",
"remainder",
".",
"Be",
"aware",
"that",
"because",
"of",
"rounding",
"increases",
"will",
"be",
"approximate",
"to",
"the",
"nearest",
"byte",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/ByteAmount.java#L186-L195 |
27,954 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.createJob | public boolean createJob(String slurmScript, String heronExec,
String[] commandArgs, String topologyWorkingDirectory,
long containers, String partition) {
// get the command to run the job on Slurm cluster
List<String> slurmCmd = slurmCommand(slurmScript, heronExec, containers, partition);
// change the empty strings of command args to "", because batch
// doesn't recognize space as an arguments
List<String> transformedArgs = new ArrayList<>();
for (int i = 0; i < commandArgs.length; i++) {
String arg = commandArgs[i];
if (arg == null || arg.trim().equals("")) {
transformedArgs.add("\"\"");
} else {
transformedArgs.add(arg);
}
}
// add the args to the command
slurmCmd.addAll(transformedArgs);
String[] slurmCmdArray = slurmCmd.toArray(new String[0]);
LOG.log(Level.INFO, "Executing job [" + topologyWorkingDirectory + "]:",
Arrays.toString(slurmCmdArray));
StringBuilder stderr = new StringBuilder();
boolean ret = runProcess(topologyWorkingDirectory, slurmCmdArray, stderr);
return ret;
} | java | public boolean createJob(String slurmScript, String heronExec,
String[] commandArgs, String topologyWorkingDirectory,
long containers, String partition) {
// get the command to run the job on Slurm cluster
List<String> slurmCmd = slurmCommand(slurmScript, heronExec, containers, partition);
// change the empty strings of command args to "", because batch
// doesn't recognize space as an arguments
List<String> transformedArgs = new ArrayList<>();
for (int i = 0; i < commandArgs.length; i++) {
String arg = commandArgs[i];
if (arg == null || arg.trim().equals("")) {
transformedArgs.add("\"\"");
} else {
transformedArgs.add(arg);
}
}
// add the args to the command
slurmCmd.addAll(transformedArgs);
String[] slurmCmdArray = slurmCmd.toArray(new String[0]);
LOG.log(Level.INFO, "Executing job [" + topologyWorkingDirectory + "]:",
Arrays.toString(slurmCmdArray));
StringBuilder stderr = new StringBuilder();
boolean ret = runProcess(topologyWorkingDirectory, slurmCmdArray, stderr);
return ret;
} | [
"public",
"boolean",
"createJob",
"(",
"String",
"slurmScript",
",",
"String",
"heronExec",
",",
"String",
"[",
"]",
"commandArgs",
",",
"String",
"topologyWorkingDirectory",
",",
"long",
"containers",
",",
"String",
"partition",
")",
"{",
"// get the command to run the job on Slurm cluster",
"List",
"<",
"String",
">",
"slurmCmd",
"=",
"slurmCommand",
"(",
"slurmScript",
",",
"heronExec",
",",
"containers",
",",
"partition",
")",
";",
"// change the empty strings of command args to \"\", because batch",
"// doesn't recognize space as an arguments",
"List",
"<",
"String",
">",
"transformedArgs",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"commandArgs",
".",
"length",
";",
"i",
"++",
")",
"{",
"String",
"arg",
"=",
"commandArgs",
"[",
"i",
"]",
";",
"if",
"(",
"arg",
"==",
"null",
"||",
"arg",
".",
"trim",
"(",
")",
".",
"equals",
"(",
"\"\"",
")",
")",
"{",
"transformedArgs",
".",
"add",
"(",
"\"\\\"\\\"\"",
")",
";",
"}",
"else",
"{",
"transformedArgs",
".",
"add",
"(",
"arg",
")",
";",
"}",
"}",
"// add the args to the command",
"slurmCmd",
".",
"addAll",
"(",
"transformedArgs",
")",
";",
"String",
"[",
"]",
"slurmCmdArray",
"=",
"slurmCmd",
".",
"toArray",
"(",
"new",
"String",
"[",
"0",
"]",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Executing job [\"",
"+",
"topologyWorkingDirectory",
"+",
"\"]:\"",
",",
"Arrays",
".",
"toString",
"(",
"slurmCmdArray",
")",
")",
";",
"StringBuilder",
"stderr",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"boolean",
"ret",
"=",
"runProcess",
"(",
"topologyWorkingDirectory",
",",
"slurmCmdArray",
",",
"stderr",
")",
";",
"return",
"ret",
";",
"}"
] | Create a slurm job. Use the slurm scheduler's sbatch command to submit the job.
sbatch allocates the nodes and runs the script specified by slurmScript.
This script runs the heron executor on each of the nodes allocated.
@param slurmScript slurm bash script to execute
@param heronExec the heron executable
@param commandArgs arguments to the heron executor
@param topologyWorkingDirectory working directory
@param containers number of containers required to run the topology
@param partition the queue to submit the job
@return true if the job creation is successful | [
"Create",
"a",
"slurm",
"job",
".",
"Use",
"the",
"slurm",
"scheduler",
"s",
"sbatch",
"command",
"to",
"submit",
"the",
"job",
".",
"sbatch",
"allocates",
"the",
"nodes",
"and",
"runs",
"the",
"script",
"specified",
"by",
"slurmScript",
".",
"This",
"script",
"runs",
"the",
"heron",
"executor",
"on",
"each",
"of",
"the",
"nodes",
"allocated",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L56-L82 |
27,955 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.slurmCommand | private List<String> slurmCommand(String slurmScript, String heronExec,
long containers, String partition) {
String nTasks = String.format("--ntasks=%d", containers);
List<String> slurmCmd;
if (partition != null) {
slurmCmd = new ArrayList<>(Arrays.asList("sbatch", "-N",
Long.toString(containers), nTasks, "-p", partition, slurmScript, heronExec));
} else {
slurmCmd = new ArrayList<>(Arrays.asList("sbatch", "-N",
Long.toString(containers), nTasks, slurmScript, heronExec));
}
return slurmCmd;
} | java | private List<String> slurmCommand(String slurmScript, String heronExec,
long containers, String partition) {
String nTasks = String.format("--ntasks=%d", containers);
List<String> slurmCmd;
if (partition != null) {
slurmCmd = new ArrayList<>(Arrays.asList("sbatch", "-N",
Long.toString(containers), nTasks, "-p", partition, slurmScript, heronExec));
} else {
slurmCmd = new ArrayList<>(Arrays.asList("sbatch", "-N",
Long.toString(containers), nTasks, slurmScript, heronExec));
}
return slurmCmd;
} | [
"private",
"List",
"<",
"String",
">",
"slurmCommand",
"(",
"String",
"slurmScript",
",",
"String",
"heronExec",
",",
"long",
"containers",
",",
"String",
"partition",
")",
"{",
"String",
"nTasks",
"=",
"String",
".",
"format",
"(",
"\"--ntasks=%d\"",
",",
"containers",
")",
";",
"List",
"<",
"String",
">",
"slurmCmd",
";",
"if",
"(",
"partition",
"!=",
"null",
")",
"{",
"slurmCmd",
"=",
"new",
"ArrayList",
"<>",
"(",
"Arrays",
".",
"asList",
"(",
"\"sbatch\"",
",",
"\"-N\"",
",",
"Long",
".",
"toString",
"(",
"containers",
")",
",",
"nTasks",
",",
"\"-p\"",
",",
"partition",
",",
"slurmScript",
",",
"heronExec",
")",
")",
";",
"}",
"else",
"{",
"slurmCmd",
"=",
"new",
"ArrayList",
"<>",
"(",
"Arrays",
".",
"asList",
"(",
"\"sbatch\"",
",",
"\"-N\"",
",",
"Long",
".",
"toString",
"(",
"containers",
")",
",",
"nTasks",
",",
"slurmScript",
",",
"heronExec",
")",
")",
";",
"}",
"return",
"slurmCmd",
";",
"}"
] | Construct the SLURM Command
@param slurmScript slurm script name
@param heronExec heron executable name
@param containers number of containers
@param partition the partition to submit the job
@return list with the command | [
"Construct",
"the",
"SLURM",
"Command"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L92-L104 |
27,956 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.createJob | public boolean createJob(String slurmScript, String heronExec,
String[] commandArgs, String topologyWorkingDirectory,
long containers) {
return createJob(slurmScript, heronExec, commandArgs,
topologyWorkingDirectory, containers, null);
} | java | public boolean createJob(String slurmScript, String heronExec,
String[] commandArgs, String topologyWorkingDirectory,
long containers) {
return createJob(slurmScript, heronExec, commandArgs,
topologyWorkingDirectory, containers, null);
} | [
"public",
"boolean",
"createJob",
"(",
"String",
"slurmScript",
",",
"String",
"heronExec",
",",
"String",
"[",
"]",
"commandArgs",
",",
"String",
"topologyWorkingDirectory",
",",
"long",
"containers",
")",
"{",
"return",
"createJob",
"(",
"slurmScript",
",",
"heronExec",
",",
"commandArgs",
",",
"topologyWorkingDirectory",
",",
"containers",
",",
"null",
")",
";",
"}"
] | Create a slurm job. Use the slurm schedule'r sbatch command to submit the job.
sbatch allocates the nodes and runs the script specified by slurmScript.
This script runs the heron executor on each of the nodes allocated.
@param slurmScript slurm bash script to execute
@param heronExec the heron executable
@param commandArgs arguments to the heron executor
@param topologyWorkingDirectory working directory
@param containers number of containers required to run the topology
@return true if the job creation is successful | [
"Create",
"a",
"slurm",
"job",
".",
"Use",
"the",
"slurm",
"schedule",
"r",
"sbatch",
"command",
"to",
"submit",
"the",
"job",
".",
"sbatch",
"allocates",
"the",
"nodes",
"and",
"runs",
"the",
"script",
"specified",
"by",
"slurmScript",
".",
"This",
"script",
"runs",
"the",
"heron",
"executor",
"on",
"each",
"of",
"the",
"nodes",
"allocated",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L118-L123 |
27,957 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.runProcess | protected boolean runProcess(String topologyWorkingDirectory, String[] slurmCmd,
StringBuilder stderr) {
File file = topologyWorkingDirectory == null ? null : new File(topologyWorkingDirectory);
return 0 == ShellUtils.runSyncProcess(true, false, slurmCmd, stderr, file);
} | java | protected boolean runProcess(String topologyWorkingDirectory, String[] slurmCmd,
StringBuilder stderr) {
File file = topologyWorkingDirectory == null ? null : new File(topologyWorkingDirectory);
return 0 == ShellUtils.runSyncProcess(true, false, slurmCmd, stderr, file);
} | [
"protected",
"boolean",
"runProcess",
"(",
"String",
"topologyWorkingDirectory",
",",
"String",
"[",
"]",
"slurmCmd",
",",
"StringBuilder",
"stderr",
")",
"{",
"File",
"file",
"=",
"topologyWorkingDirectory",
"==",
"null",
"?",
"null",
":",
"new",
"File",
"(",
"topologyWorkingDirectory",
")",
";",
"return",
"0",
"==",
"ShellUtils",
".",
"runSyncProcess",
"(",
"true",
",",
"false",
",",
"slurmCmd",
",",
"stderr",
",",
"file",
")",
";",
"}"
] | This is for unit testing | [
"This",
"is",
"for",
"unit",
"testing"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L128-L132 |
27,958 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.killJob | public boolean killJob(String jobIdFile) {
List<String> jobIdFileContent = readFromFile(jobIdFile);
if (jobIdFileContent.size() > 0) {
String[] slurmCmd = new String[]{"scancel", jobIdFileContent.get(0)};
return runProcess(null, slurmCmd, new StringBuilder());
} else {
LOG.log(Level.SEVERE, "Failed to read the Slurm Job id from file: {0}", jobIdFile);
return false;
}
} | java | public boolean killJob(String jobIdFile) {
List<String> jobIdFileContent = readFromFile(jobIdFile);
if (jobIdFileContent.size() > 0) {
String[] slurmCmd = new String[]{"scancel", jobIdFileContent.get(0)};
return runProcess(null, slurmCmd, new StringBuilder());
} else {
LOG.log(Level.SEVERE, "Failed to read the Slurm Job id from file: {0}", jobIdFile);
return false;
}
} | [
"public",
"boolean",
"killJob",
"(",
"String",
"jobIdFile",
")",
"{",
"List",
"<",
"String",
">",
"jobIdFileContent",
"=",
"readFromFile",
"(",
"jobIdFile",
")",
";",
"if",
"(",
"jobIdFileContent",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"String",
"[",
"]",
"slurmCmd",
"=",
"new",
"String",
"[",
"]",
"{",
"\"scancel\"",
",",
"jobIdFileContent",
".",
"get",
"(",
"0",
")",
"}",
";",
"return",
"runProcess",
"(",
"null",
",",
"slurmCmd",
",",
"new",
"StringBuilder",
"(",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to read the Slurm Job id from file: {0}\"",
",",
"jobIdFile",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Cancel the Slurm job by reading the jobid from the jobIdFile. Uses scancel
command to cancel the job. The file contains a single line with the job id.
This file is written by the slurm job script after the job is allocated.
@param jobIdFile the jobId file
@return true if the job is cancelled successfully | [
"Cancel",
"the",
"Slurm",
"job",
"by",
"reading",
"the",
"jobid",
"from",
"the",
"jobIdFile",
".",
"Uses",
"scancel",
"command",
"to",
"cancel",
"the",
"job",
".",
"The",
"file",
"contains",
"a",
"single",
"line",
"with",
"the",
"job",
"id",
".",
"This",
"file",
"is",
"written",
"by",
"the",
"slurm",
"job",
"script",
"after",
"the",
"job",
"is",
"allocated",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L141-L150 |
27,959 | apache/incubator-heron | heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java | SlurmController.readFromFile | protected List<String> readFromFile(String filename) {
Path path = new File(filename).toPath();
List<String> result = new ArrayList<>();
try {
List<String> tempResult = Files.readAllLines(path);
if (tempResult != null) {
result.addAll(tempResult);
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read from file. ", e);
}
return result;
} | java | protected List<String> readFromFile(String filename) {
Path path = new File(filename).toPath();
List<String> result = new ArrayList<>();
try {
List<String> tempResult = Files.readAllLines(path);
if (tempResult != null) {
result.addAll(tempResult);
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "Failed to read from file. ", e);
}
return result;
} | [
"protected",
"List",
"<",
"String",
">",
"readFromFile",
"(",
"String",
"filename",
")",
"{",
"Path",
"path",
"=",
"new",
"File",
"(",
"filename",
")",
".",
"toPath",
"(",
")",
";",
"List",
"<",
"String",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"try",
"{",
"List",
"<",
"String",
">",
"tempResult",
"=",
"Files",
".",
"readAllLines",
"(",
"path",
")",
";",
"if",
"(",
"tempResult",
"!=",
"null",
")",
"{",
"result",
".",
"addAll",
"(",
"tempResult",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Failed to read from file. \"",
",",
"e",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Read all the data from a text file line by line
For now lets keep this util function here. We need to move it to a util location
@param filename name of the file
@return string list containing the lines of the file, if failed to read, return an empty list | [
"Read",
"all",
"the",
"data",
"from",
"a",
"text",
"file",
"line",
"by",
"line",
"For",
"now",
"lets",
"keep",
"this",
"util",
"function",
"here",
".",
"We",
"need",
"to",
"move",
"it",
"to",
"a",
"util",
"location"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/schedulers/src/java/org/apache/heron/scheduler/slurm/SlurmController.java#L158-L170 |
27,960 | apache/incubator-heron | heron/downloaders/src/java/org/apache/heron/downloader/DownloadRunner.java | DownloadRunner.main | public static void main(String[] args) throws Exception {
CommandLineParser parser = new DefaultParser();
Options slaManagerCliOptions = constructCliOptions();
// parse the help options first.
Options helpOptions = constructHelpOptions();
CommandLine cmd = parser.parse(helpOptions, args, true);
if (cmd.hasOption("h")) {
usage(slaManagerCliOptions);
return;
}
try {
cmd = parser.parse(slaManagerCliOptions, args);
} catch (ParseException e) {
usage(slaManagerCliOptions);
throw new RuntimeException("Error parsing command line options: ", e);
}
DownloaderMode mode = DownloaderMode.cluster;
if (cmd.hasOption(CliArgs.MODE.text)) {
mode = DownloaderMode.valueOf(cmd.getOptionValue(CliArgs.MODE.text, null));
}
Config config;
switch (mode) {
case cluster:
config = Config.toClusterMode(Config.newBuilder()
.putAll(ConfigLoader.loadClusterConfig())
.build());
break;
case local:
if (!cmd.hasOption(CliArgs.HERON_HOME.text) || !cmd.hasOption(CliArgs.CONFIG_PATH.text)) {
throw new IllegalArgumentException("Missing heron_home or config_path argument");
}
String heronHome = cmd.getOptionValue(CliArgs.HERON_HOME.text, null);
String configPath = cmd.getOptionValue(CliArgs.CONFIG_PATH.text, null);
config = Config.toLocalMode(Config.newBuilder()
.putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
.build());
break;
default:
throw new IllegalArgumentException(
"Invalid mode: " + cmd.getOptionValue(CliArgs.MODE.text));
}
String uri = cmd.getOptionValue(CliArgs.TOPOLOGY_PACKAGE_URI.text, null);
String destination = cmd.getOptionValue(CliArgs.EXTRACT_DESTINATION.text, null);
// make it compatible with old param format
if (uri == null && destination == null) {
String[] leftOverArgs = cmd.getArgs();
if (leftOverArgs.length != 2) {
System.err.println("Usage: downloader <topology-package-uri> <extract-destination>");
return;
}
uri = leftOverArgs[0];
destination = leftOverArgs[1];
}
final URI topologyLocation = new URI(uri);
final Path topologyDestination = Paths.get(destination);
final File file = topologyDestination.toFile();
if (!file.exists()) {
file.mkdirs();
}
Class clazz = Registry.UriToClass(config, topologyLocation);
final Downloader downloader = Registry.getDownloader(clazz, topologyLocation);
downloader.download(topologyLocation, topologyDestination);
} | java | public static void main(String[] args) throws Exception {
CommandLineParser parser = new DefaultParser();
Options slaManagerCliOptions = constructCliOptions();
// parse the help options first.
Options helpOptions = constructHelpOptions();
CommandLine cmd = parser.parse(helpOptions, args, true);
if (cmd.hasOption("h")) {
usage(slaManagerCliOptions);
return;
}
try {
cmd = parser.parse(slaManagerCliOptions, args);
} catch (ParseException e) {
usage(slaManagerCliOptions);
throw new RuntimeException("Error parsing command line options: ", e);
}
DownloaderMode mode = DownloaderMode.cluster;
if (cmd.hasOption(CliArgs.MODE.text)) {
mode = DownloaderMode.valueOf(cmd.getOptionValue(CliArgs.MODE.text, null));
}
Config config;
switch (mode) {
case cluster:
config = Config.toClusterMode(Config.newBuilder()
.putAll(ConfigLoader.loadClusterConfig())
.build());
break;
case local:
if (!cmd.hasOption(CliArgs.HERON_HOME.text) || !cmd.hasOption(CliArgs.CONFIG_PATH.text)) {
throw new IllegalArgumentException("Missing heron_home or config_path argument");
}
String heronHome = cmd.getOptionValue(CliArgs.HERON_HOME.text, null);
String configPath = cmd.getOptionValue(CliArgs.CONFIG_PATH.text, null);
config = Config.toLocalMode(Config.newBuilder()
.putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
.build());
break;
default:
throw new IllegalArgumentException(
"Invalid mode: " + cmd.getOptionValue(CliArgs.MODE.text));
}
String uri = cmd.getOptionValue(CliArgs.TOPOLOGY_PACKAGE_URI.text, null);
String destination = cmd.getOptionValue(CliArgs.EXTRACT_DESTINATION.text, null);
// make it compatible with old param format
if (uri == null && destination == null) {
String[] leftOverArgs = cmd.getArgs();
if (leftOverArgs.length != 2) {
System.err.println("Usage: downloader <topology-package-uri> <extract-destination>");
return;
}
uri = leftOverArgs[0];
destination = leftOverArgs[1];
}
final URI topologyLocation = new URI(uri);
final Path topologyDestination = Paths.get(destination);
final File file = topologyDestination.toFile();
if (!file.exists()) {
file.mkdirs();
}
Class clazz = Registry.UriToClass(config, topologyLocation);
final Downloader downloader = Registry.getDownloader(clazz, topologyLocation);
downloader.download(topologyLocation, topologyDestination);
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"CommandLineParser",
"parser",
"=",
"new",
"DefaultParser",
"(",
")",
";",
"Options",
"slaManagerCliOptions",
"=",
"constructCliOptions",
"(",
")",
";",
"// parse the help options first.",
"Options",
"helpOptions",
"=",
"constructHelpOptions",
"(",
")",
";",
"CommandLine",
"cmd",
"=",
"parser",
".",
"parse",
"(",
"helpOptions",
",",
"args",
",",
"true",
")",
";",
"if",
"(",
"cmd",
".",
"hasOption",
"(",
"\"h\"",
")",
")",
"{",
"usage",
"(",
"slaManagerCliOptions",
")",
";",
"return",
";",
"}",
"try",
"{",
"cmd",
"=",
"parser",
".",
"parse",
"(",
"slaManagerCliOptions",
",",
"args",
")",
";",
"}",
"catch",
"(",
"ParseException",
"e",
")",
"{",
"usage",
"(",
"slaManagerCliOptions",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"\"Error parsing command line options: \"",
",",
"e",
")",
";",
"}",
"DownloaderMode",
"mode",
"=",
"DownloaderMode",
".",
"cluster",
";",
"if",
"(",
"cmd",
".",
"hasOption",
"(",
"CliArgs",
".",
"MODE",
".",
"text",
")",
")",
"{",
"mode",
"=",
"DownloaderMode",
".",
"valueOf",
"(",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"MODE",
".",
"text",
",",
"null",
")",
")",
";",
"}",
"Config",
"config",
";",
"switch",
"(",
"mode",
")",
"{",
"case",
"cluster",
":",
"config",
"=",
"Config",
".",
"toClusterMode",
"(",
"Config",
".",
"newBuilder",
"(",
")",
".",
"putAll",
"(",
"ConfigLoader",
".",
"loadClusterConfig",
"(",
")",
")",
".",
"build",
"(",
")",
")",
";",
"break",
";",
"case",
"local",
":",
"if",
"(",
"!",
"cmd",
".",
"hasOption",
"(",
"CliArgs",
".",
"HERON_HOME",
".",
"text",
")",
"||",
"!",
"cmd",
".",
"hasOption",
"(",
"CliArgs",
".",
"CONFIG_PATH",
".",
"text",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Missing heron_home or config_path argument\"",
")",
";",
"}",
"String",
"heronHome",
"=",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"HERON_HOME",
".",
"text",
",",
"null",
")",
";",
"String",
"configPath",
"=",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"CONFIG_PATH",
".",
"text",
",",
"null",
")",
";",
"config",
"=",
"Config",
".",
"toLocalMode",
"(",
"Config",
".",
"newBuilder",
"(",
")",
".",
"putAll",
"(",
"ConfigLoader",
".",
"loadConfig",
"(",
"heronHome",
",",
"configPath",
",",
"null",
",",
"null",
")",
")",
".",
"build",
"(",
")",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid mode: \"",
"+",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"MODE",
".",
"text",
")",
")",
";",
"}",
"String",
"uri",
"=",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"TOPOLOGY_PACKAGE_URI",
".",
"text",
",",
"null",
")",
";",
"String",
"destination",
"=",
"cmd",
".",
"getOptionValue",
"(",
"CliArgs",
".",
"EXTRACT_DESTINATION",
".",
"text",
",",
"null",
")",
";",
"// make it compatible with old param format",
"if",
"(",
"uri",
"==",
"null",
"&&",
"destination",
"==",
"null",
")",
"{",
"String",
"[",
"]",
"leftOverArgs",
"=",
"cmd",
".",
"getArgs",
"(",
")",
";",
"if",
"(",
"leftOverArgs",
".",
"length",
"!=",
"2",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Usage: downloader <topology-package-uri> <extract-destination>\"",
")",
";",
"return",
";",
"}",
"uri",
"=",
"leftOverArgs",
"[",
"0",
"]",
";",
"destination",
"=",
"leftOverArgs",
"[",
"1",
"]",
";",
"}",
"final",
"URI",
"topologyLocation",
"=",
"new",
"URI",
"(",
"uri",
")",
";",
"final",
"Path",
"topologyDestination",
"=",
"Paths",
".",
"get",
"(",
"destination",
")",
";",
"final",
"File",
"file",
"=",
"topologyDestination",
".",
"toFile",
"(",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"file",
".",
"mkdirs",
"(",
")",
";",
"}",
"Class",
"clazz",
"=",
"Registry",
".",
"UriToClass",
"(",
"config",
",",
"topologyLocation",
")",
";",
"final",
"Downloader",
"downloader",
"=",
"Registry",
".",
"getDownloader",
"(",
"clazz",
",",
"topologyLocation",
")",
";",
"downloader",
".",
"download",
"(",
"topologyLocation",
",",
"topologyDestination",
")",
";",
"}"
] | takes topology package URI and extracts it to a directory | [
"takes",
"topology",
"package",
"URI",
"and",
"extracts",
"it",
"to",
"a",
"directory"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/downloaders/src/java/org/apache/heron/downloader/DownloadRunner.java#L129-L201 |
27,961 | apache/incubator-heron | eco/src/java/org/apache/heron/eco/Eco.java | Eco.submit | public void submit(FileInputStream fileInputStream,
FileInputStream propertiesFile, boolean envFilter)
throws Exception {
EcoTopologyDefinition topologyDefinition = ecoParser
.parseFromInputStream(fileInputStream, propertiesFile, envFilter);
String topologyName = topologyDefinition.getName();
String topologyType = topologyDefinition.getType();
if ("storm".equals(topologyType)) {
System.out.println("topology type is Storm");
org.apache.heron.eco.builder.storm.EcoBuilder ecoBuilder =
new org.apache.heron.eco.builder.storm.EcoBuilder(
new org.apache.heron.eco.builder.storm.SpoutBuilder(),
new BoltBuilder(),
new org.apache.heron.eco.builder.storm.StreamBuilder(),
new ComponentBuilder(),
new ConfigBuilder());
Config topologyConfig = ecoBuilder
.buildConfig(topologyDefinition);
EcoExecutionContext executionContext
= new EcoExecutionContext(topologyDefinition, topologyConfig);
printTopologyInfo(executionContext);
ObjectBuilder objectBuilder = new ObjectBuilder();
objectBuilder.setBuilderUtility(new BuilderUtility());
org.apache.storm.topology.TopologyBuilder builder = ecoBuilder
.buildTopologyBuilder(executionContext, objectBuilder);
ecoSubmitter.submitStormTopology(topologyName, topologyConfig, builder.createTopology());
} else if ("heron".equals(topologyType)) {
System.out.println("topology type is Heron");
org.apache.heron.eco.builder.heron.EcoBuilder ecoBuilder =
new org.apache.heron.eco.builder.heron.EcoBuilder(
new org.apache.heron.eco.builder.heron.SpoutBuilder(),
new BoltBuilder(),
new org.apache.heron.eco.builder.heron.StreamBuilder(),
new ComponentBuilder(),
new ConfigBuilder());
Config topologyConfig = ecoBuilder
.buildConfig(topologyDefinition);
EcoExecutionContext executionContext
= new EcoExecutionContext(topologyDefinition, topologyConfig);
printTopologyInfo(executionContext);
ObjectBuilder objectBuilder = new ObjectBuilder();
objectBuilder.setBuilderUtility(new BuilderUtility());
org.apache.heron.api.topology.TopologyBuilder builder = ecoBuilder
.buildTopologyBuilder(executionContext, objectBuilder);
ecoSubmitter.submitHeronTopology(topologyName, topologyConfig, builder.createTopology());
} else {
LOG.log(Level.SEVERE,
String.format("Unknown topology type \'%s\' for topology %s, not submitted",
topologyType, topologyName));
}
} | java | public void submit(FileInputStream fileInputStream,
FileInputStream propertiesFile, boolean envFilter)
throws Exception {
EcoTopologyDefinition topologyDefinition = ecoParser
.parseFromInputStream(fileInputStream, propertiesFile, envFilter);
String topologyName = topologyDefinition.getName();
String topologyType = topologyDefinition.getType();
if ("storm".equals(topologyType)) {
System.out.println("topology type is Storm");
org.apache.heron.eco.builder.storm.EcoBuilder ecoBuilder =
new org.apache.heron.eco.builder.storm.EcoBuilder(
new org.apache.heron.eco.builder.storm.SpoutBuilder(),
new BoltBuilder(),
new org.apache.heron.eco.builder.storm.StreamBuilder(),
new ComponentBuilder(),
new ConfigBuilder());
Config topologyConfig = ecoBuilder
.buildConfig(topologyDefinition);
EcoExecutionContext executionContext
= new EcoExecutionContext(topologyDefinition, topologyConfig);
printTopologyInfo(executionContext);
ObjectBuilder objectBuilder = new ObjectBuilder();
objectBuilder.setBuilderUtility(new BuilderUtility());
org.apache.storm.topology.TopologyBuilder builder = ecoBuilder
.buildTopologyBuilder(executionContext, objectBuilder);
ecoSubmitter.submitStormTopology(topologyName, topologyConfig, builder.createTopology());
} else if ("heron".equals(topologyType)) {
System.out.println("topology type is Heron");
org.apache.heron.eco.builder.heron.EcoBuilder ecoBuilder =
new org.apache.heron.eco.builder.heron.EcoBuilder(
new org.apache.heron.eco.builder.heron.SpoutBuilder(),
new BoltBuilder(),
new org.apache.heron.eco.builder.heron.StreamBuilder(),
new ComponentBuilder(),
new ConfigBuilder());
Config topologyConfig = ecoBuilder
.buildConfig(topologyDefinition);
EcoExecutionContext executionContext
= new EcoExecutionContext(topologyDefinition, topologyConfig);
printTopologyInfo(executionContext);
ObjectBuilder objectBuilder = new ObjectBuilder();
objectBuilder.setBuilderUtility(new BuilderUtility());
org.apache.heron.api.topology.TopologyBuilder builder = ecoBuilder
.buildTopologyBuilder(executionContext, objectBuilder);
ecoSubmitter.submitHeronTopology(topologyName, topologyConfig, builder.createTopology());
} else {
LOG.log(Level.SEVERE,
String.format("Unknown topology type \'%s\' for topology %s, not submitted",
topologyType, topologyName));
}
} | [
"public",
"void",
"submit",
"(",
"FileInputStream",
"fileInputStream",
",",
"FileInputStream",
"propertiesFile",
",",
"boolean",
"envFilter",
")",
"throws",
"Exception",
"{",
"EcoTopologyDefinition",
"topologyDefinition",
"=",
"ecoParser",
".",
"parseFromInputStream",
"(",
"fileInputStream",
",",
"propertiesFile",
",",
"envFilter",
")",
";",
"String",
"topologyName",
"=",
"topologyDefinition",
".",
"getName",
"(",
")",
";",
"String",
"topologyType",
"=",
"topologyDefinition",
".",
"getType",
"(",
")",
";",
"if",
"(",
"\"storm\"",
".",
"equals",
"(",
"topologyType",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"topology type is Storm\"",
")",
";",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"storm",
".",
"EcoBuilder",
"ecoBuilder",
"=",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"storm",
".",
"EcoBuilder",
"(",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"storm",
".",
"SpoutBuilder",
"(",
")",
",",
"new",
"BoltBuilder",
"(",
")",
",",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"storm",
".",
"StreamBuilder",
"(",
")",
",",
"new",
"ComponentBuilder",
"(",
")",
",",
"new",
"ConfigBuilder",
"(",
")",
")",
";",
"Config",
"topologyConfig",
"=",
"ecoBuilder",
".",
"buildConfig",
"(",
"topologyDefinition",
")",
";",
"EcoExecutionContext",
"executionContext",
"=",
"new",
"EcoExecutionContext",
"(",
"topologyDefinition",
",",
"topologyConfig",
")",
";",
"printTopologyInfo",
"(",
"executionContext",
")",
";",
"ObjectBuilder",
"objectBuilder",
"=",
"new",
"ObjectBuilder",
"(",
")",
";",
"objectBuilder",
".",
"setBuilderUtility",
"(",
"new",
"BuilderUtility",
"(",
")",
")",
";",
"org",
".",
"apache",
".",
"storm",
".",
"topology",
".",
"TopologyBuilder",
"builder",
"=",
"ecoBuilder",
".",
"buildTopologyBuilder",
"(",
"executionContext",
",",
"objectBuilder",
")",
";",
"ecoSubmitter",
".",
"submitStormTopology",
"(",
"topologyName",
",",
"topologyConfig",
",",
"builder",
".",
"createTopology",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"\"heron\"",
".",
"equals",
"(",
"topologyType",
")",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"topology type is Heron\"",
")",
";",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"heron",
".",
"EcoBuilder",
"ecoBuilder",
"=",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"heron",
".",
"EcoBuilder",
"(",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"heron",
".",
"SpoutBuilder",
"(",
")",
",",
"new",
"BoltBuilder",
"(",
")",
",",
"new",
"org",
".",
"apache",
".",
"heron",
".",
"eco",
".",
"builder",
".",
"heron",
".",
"StreamBuilder",
"(",
")",
",",
"new",
"ComponentBuilder",
"(",
")",
",",
"new",
"ConfigBuilder",
"(",
")",
")",
";",
"Config",
"topologyConfig",
"=",
"ecoBuilder",
".",
"buildConfig",
"(",
"topologyDefinition",
")",
";",
"EcoExecutionContext",
"executionContext",
"=",
"new",
"EcoExecutionContext",
"(",
"topologyDefinition",
",",
"topologyConfig",
")",
";",
"printTopologyInfo",
"(",
"executionContext",
")",
";",
"ObjectBuilder",
"objectBuilder",
"=",
"new",
"ObjectBuilder",
"(",
")",
";",
"objectBuilder",
".",
"setBuilderUtility",
"(",
"new",
"BuilderUtility",
"(",
")",
")",
";",
"org",
".",
"apache",
".",
"heron",
".",
"api",
".",
"topology",
".",
"TopologyBuilder",
"builder",
"=",
"ecoBuilder",
".",
"buildTopologyBuilder",
"(",
"executionContext",
",",
"objectBuilder",
")",
";",
"ecoSubmitter",
".",
"submitHeronTopology",
"(",
"topologyName",
",",
"topologyConfig",
",",
"builder",
".",
"createTopology",
"(",
")",
")",
";",
"}",
"else",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"String",
".",
"format",
"(",
"\"Unknown topology type \\'%s\\' for topology %s, not submitted\"",
",",
"topologyType",
",",
"topologyName",
")",
")",
";",
"}",
"}"
] | Submit an ECO topology
@param fileInputStream The input stream associated with ECO topology definition file
@param propertiesFile The optional key-value property file for optional property substitution.
@param envFilter The optional flag to tell ECO to perform environment variable substitution
@throws Exception the exception thrown | [
"Submit",
"an",
"ECO",
"topology"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/eco/src/java/org/apache/heron/eco/Eco.java#L70-L132 |
27,962 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/basics/SysUtils.java | SysUtils.closeIgnoringExceptions | public static void closeIgnoringExceptions(AutoCloseable closeable) {
if (closeable != null) {
try {
closeable.close();
// Suppress it since we ignore any exceptions
// SUPPRESS CHECKSTYLE IllegalCatch
} catch (Exception e) {
// Still log the Exception for issue tracing
LOG.log(Level.WARNING, String.format("Failed to close %s", closeable), e);
}
}
} | java | public static void closeIgnoringExceptions(AutoCloseable closeable) {
if (closeable != null) {
try {
closeable.close();
// Suppress it since we ignore any exceptions
// SUPPRESS CHECKSTYLE IllegalCatch
} catch (Exception e) {
// Still log the Exception for issue tracing
LOG.log(Level.WARNING, String.format("Failed to close %s", closeable), e);
}
}
} | [
"public",
"static",
"void",
"closeIgnoringExceptions",
"(",
"AutoCloseable",
"closeable",
")",
"{",
"if",
"(",
"closeable",
"!=",
"null",
")",
"{",
"try",
"{",
"closeable",
".",
"close",
"(",
")",
";",
"// Suppress it since we ignore any exceptions",
"// SUPPRESS CHECKSTYLE IllegalCatch",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Still log the Exception for issue tracing",
"LOG",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"String",
".",
"format",
"(",
"\"Failed to close %s\"",
",",
"closeable",
")",
",",
"e",
")",
";",
"}",
"}",
"}"
] | Close a closable ignoring any exceptions.
This method is used during cleanup, or in a finally block.
@param closeable source or destination of data can be closed | [
"Close",
"a",
"closable",
"ignoring",
"any",
"exceptions",
".",
"This",
"method",
"is",
"used",
"during",
"cleanup",
"or",
"in",
"a",
"finally",
"block",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/basics/SysUtils.java#L68-L80 |
27,963 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerConfigUtils.java | SchedulerConfigUtils.topologyConfigs | private static Config topologyConfigs(String topologyBinaryFile,
String topologyDefnFile, TopologyAPI.Topology topology) {
PackageType packageType = PackageType.getPackageType(topologyBinaryFile);
return Config.newBuilder()
.put(Key.TOPOLOGY_ID, topology.getId())
.put(Key.TOPOLOGY_NAME, topology.getName())
.put(Key.TOPOLOGY_DEFINITION_FILE, topologyDefnFile)
.put(Key.TOPOLOGY_BINARY_FILE, topologyBinaryFile)
.put(Key.TOPOLOGY_PACKAGE_TYPE, packageType)
.build();
} | java | private static Config topologyConfigs(String topologyBinaryFile,
String topologyDefnFile, TopologyAPI.Topology topology) {
PackageType packageType = PackageType.getPackageType(topologyBinaryFile);
return Config.newBuilder()
.put(Key.TOPOLOGY_ID, topology.getId())
.put(Key.TOPOLOGY_NAME, topology.getName())
.put(Key.TOPOLOGY_DEFINITION_FILE, topologyDefnFile)
.put(Key.TOPOLOGY_BINARY_FILE, topologyBinaryFile)
.put(Key.TOPOLOGY_PACKAGE_TYPE, packageType)
.build();
} | [
"private",
"static",
"Config",
"topologyConfigs",
"(",
"String",
"topologyBinaryFile",
",",
"String",
"topologyDefnFile",
",",
"TopologyAPI",
".",
"Topology",
"topology",
")",
"{",
"PackageType",
"packageType",
"=",
"PackageType",
".",
"getPackageType",
"(",
"topologyBinaryFile",
")",
";",
"return",
"Config",
".",
"newBuilder",
"(",
")",
".",
"put",
"(",
"Key",
".",
"TOPOLOGY_ID",
",",
"topology",
".",
"getId",
"(",
")",
")",
".",
"put",
"(",
"Key",
".",
"TOPOLOGY_NAME",
",",
"topology",
".",
"getName",
"(",
")",
")",
".",
"put",
"(",
"Key",
".",
"TOPOLOGY_DEFINITION_FILE",
",",
"topologyDefnFile",
")",
".",
"put",
"(",
"Key",
".",
"TOPOLOGY_BINARY_FILE",
",",
"topologyBinaryFile",
")",
".",
"put",
"(",
"Key",
".",
"TOPOLOGY_PACKAGE_TYPE",
",",
"packageType",
")",
".",
"build",
"(",
")",
";",
"}"
] | Load the topology config
@param topologyBinaryFile, name of the user submitted topology jar/tar/pex file
@param topologyDefnFile, name of the topology defintion file
@param topology, proto in memory version of topology definition
@return config, the topology config | [
"Load",
"the",
"topology",
"config"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerConfigUtils.java#L44-L55 |
27,964 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerConfigUtils.java | SchedulerConfigUtils.loadConfig | public static Config loadConfig(
String cluster,
String role,
String environ,
String topologyBinaryFile,
String topologyDefnFile,
Boolean verbose,
TopologyAPI.Topology topology) {
return Config.toClusterMode(
Config.newBuilder()
.putAll(ConfigLoader.loadClusterConfig())
.putAll(commandLineConfigs(cluster, role, environ, verbose))
.putAll(topologyConfigs(topologyBinaryFile, topologyDefnFile, topology))
.build());
} | java | public static Config loadConfig(
String cluster,
String role,
String environ,
String topologyBinaryFile,
String topologyDefnFile,
Boolean verbose,
TopologyAPI.Topology topology) {
return Config.toClusterMode(
Config.newBuilder()
.putAll(ConfigLoader.loadClusterConfig())
.putAll(commandLineConfigs(cluster, role, environ, verbose))
.putAll(topologyConfigs(topologyBinaryFile, topologyDefnFile, topology))
.build());
} | [
"public",
"static",
"Config",
"loadConfig",
"(",
"String",
"cluster",
",",
"String",
"role",
",",
"String",
"environ",
",",
"String",
"topologyBinaryFile",
",",
"String",
"topologyDefnFile",
",",
"Boolean",
"verbose",
",",
"TopologyAPI",
".",
"Topology",
"topology",
")",
"{",
"return",
"Config",
".",
"toClusterMode",
"(",
"Config",
".",
"newBuilder",
"(",
")",
".",
"putAll",
"(",
"ConfigLoader",
".",
"loadClusterConfig",
"(",
")",
")",
".",
"putAll",
"(",
"commandLineConfigs",
"(",
"cluster",
",",
"role",
",",
"environ",
",",
"verbose",
")",
")",
".",
"putAll",
"(",
"topologyConfigs",
"(",
"topologyBinaryFile",
",",
"topologyDefnFile",
",",
"topology",
")",
")",
".",
"build",
"(",
")",
")",
";",
"}"
] | build the config by expanding all the variables | [
"build",
"the",
"config",
"by",
"expanding",
"all",
"the",
"variables"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/utils/SchedulerConfigUtils.java#L76-L91 |
27,965 | apache/incubator-heron | storm-compatibility/src/java/backtype/storm/serialization/SerializationFactory.java | SerializationFactory.getKryo | @SuppressWarnings({"rawtypes", "unchecked"})
public static Kryo getKryo(Map conf) {
IKryoFactory kryoFactory =
(IKryoFactory) Utils.newInstance((String) conf.get(Config.TOPOLOGY_KRYO_FACTORY));
Kryo k = kryoFactory.getKryo(conf);
k.register(byte[].class);
k.register(ListDelegate.class);
k.register(ArrayList.class, new ArrayListSerializer());
k.register(HashMap.class, new HashMapSerializer());
k.register(HashSet.class, new HashSetSerializer());
k.register(BigInteger.class, new BigIntegerSerializer());
// k.register(TransactionAttempt.class);
k.register(Values.class);
// k.register(backtype.storm.metric.api.IMetricsConsumer.DataPoint.class);
// k.register(backtype.storm.metric.api.IMetricsConsumer.TaskInfo.class);
/*
try {
JavaBridge.registerPrimitives(k);
JavaBridge.registerCollections(k);
} catch(Exception e) {
throw new RuntimeException(e);
}
*/
Map<String, String> registrations = normalizeKryoRegister(conf);
kryoFactory.preRegister(k, conf);
boolean skipMissing = (Boolean) conf.get(Config.TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS);
for (String klassName : registrations.keySet()) {
String serializerClassName = registrations.get(klassName);
try {
Class klass = Class.forName(klassName);
Class serializerClass = null;
if (serializerClassName != null) {
serializerClass = Class.forName(serializerClassName);
}
LOG.info("Doing kryo.register for class " + klass);
if (serializerClass == null) {
k.register(klass);
} else {
k.register(klass, resolveSerializerInstance(k, klass, serializerClass));
}
} catch (ClassNotFoundException e) {
if (skipMissing) {
LOG.info("Could not find serialization or class for "
+ serializerClassName + ". Skipping registration...");
} else {
throw new RuntimeException(e);
}
}
}
kryoFactory.postRegister(k, conf);
if (conf.get(Config.TOPOLOGY_KRYO_DECORATORS) != null) {
for (String klassName : (List<String>) conf.get(Config.TOPOLOGY_KRYO_DECORATORS)) {
try {
Class klass = Class.forName(klassName);
IKryoDecorator decorator = (IKryoDecorator) klass.newInstance();
decorator.decorate(k);
} catch (ClassNotFoundException e) {
if (skipMissing) {
LOG.info("Could not find kryo decorator named "
+ klassName + ". Skipping registration...");
} else {
throw new RuntimeException(e);
}
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
kryoFactory.postDecorate(k, conf);
return k;
} | java | @SuppressWarnings({"rawtypes", "unchecked"})
public static Kryo getKryo(Map conf) {
IKryoFactory kryoFactory =
(IKryoFactory) Utils.newInstance((String) conf.get(Config.TOPOLOGY_KRYO_FACTORY));
Kryo k = kryoFactory.getKryo(conf);
k.register(byte[].class);
k.register(ListDelegate.class);
k.register(ArrayList.class, new ArrayListSerializer());
k.register(HashMap.class, new HashMapSerializer());
k.register(HashSet.class, new HashSetSerializer());
k.register(BigInteger.class, new BigIntegerSerializer());
// k.register(TransactionAttempt.class);
k.register(Values.class);
// k.register(backtype.storm.metric.api.IMetricsConsumer.DataPoint.class);
// k.register(backtype.storm.metric.api.IMetricsConsumer.TaskInfo.class);
/*
try {
JavaBridge.registerPrimitives(k);
JavaBridge.registerCollections(k);
} catch(Exception e) {
throw new RuntimeException(e);
}
*/
Map<String, String> registrations = normalizeKryoRegister(conf);
kryoFactory.preRegister(k, conf);
boolean skipMissing = (Boolean) conf.get(Config.TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS);
for (String klassName : registrations.keySet()) {
String serializerClassName = registrations.get(klassName);
try {
Class klass = Class.forName(klassName);
Class serializerClass = null;
if (serializerClassName != null) {
serializerClass = Class.forName(serializerClassName);
}
LOG.info("Doing kryo.register for class " + klass);
if (serializerClass == null) {
k.register(klass);
} else {
k.register(klass, resolveSerializerInstance(k, klass, serializerClass));
}
} catch (ClassNotFoundException e) {
if (skipMissing) {
LOG.info("Could not find serialization or class for "
+ serializerClassName + ". Skipping registration...");
} else {
throw new RuntimeException(e);
}
}
}
kryoFactory.postRegister(k, conf);
if (conf.get(Config.TOPOLOGY_KRYO_DECORATORS) != null) {
for (String klassName : (List<String>) conf.get(Config.TOPOLOGY_KRYO_DECORATORS)) {
try {
Class klass = Class.forName(klassName);
IKryoDecorator decorator = (IKryoDecorator) klass.newInstance();
decorator.decorate(k);
} catch (ClassNotFoundException e) {
if (skipMissing) {
LOG.info("Could not find kryo decorator named "
+ klassName + ". Skipping registration...");
} else {
throw new RuntimeException(e);
}
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
kryoFactory.postDecorate(k, conf);
return k;
} | [
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"Kryo",
"getKryo",
"(",
"Map",
"conf",
")",
"{",
"IKryoFactory",
"kryoFactory",
"=",
"(",
"IKryoFactory",
")",
"Utils",
".",
"newInstance",
"(",
"(",
"String",
")",
"conf",
".",
"get",
"(",
"Config",
".",
"TOPOLOGY_KRYO_FACTORY",
")",
")",
";",
"Kryo",
"k",
"=",
"kryoFactory",
".",
"getKryo",
"(",
"conf",
")",
";",
"k",
".",
"register",
"(",
"byte",
"[",
"]",
".",
"class",
")",
";",
"k",
".",
"register",
"(",
"ListDelegate",
".",
"class",
")",
";",
"k",
".",
"register",
"(",
"ArrayList",
".",
"class",
",",
"new",
"ArrayListSerializer",
"(",
")",
")",
";",
"k",
".",
"register",
"(",
"HashMap",
".",
"class",
",",
"new",
"HashMapSerializer",
"(",
")",
")",
";",
"k",
".",
"register",
"(",
"HashSet",
".",
"class",
",",
"new",
"HashSetSerializer",
"(",
")",
")",
";",
"k",
".",
"register",
"(",
"BigInteger",
".",
"class",
",",
"new",
"BigIntegerSerializer",
"(",
")",
")",
";",
"// k.register(TransactionAttempt.class);",
"k",
".",
"register",
"(",
"Values",
".",
"class",
")",
";",
"// k.register(backtype.storm.metric.api.IMetricsConsumer.DataPoint.class);",
"// k.register(backtype.storm.metric.api.IMetricsConsumer.TaskInfo.class);",
"/*\n try {\n JavaBridge.registerPrimitives(k);\n JavaBridge.registerCollections(k);\n } catch(Exception e) {\n throw new RuntimeException(e);\n }\n */",
"Map",
"<",
"String",
",",
"String",
">",
"registrations",
"=",
"normalizeKryoRegister",
"(",
"conf",
")",
";",
"kryoFactory",
".",
"preRegister",
"(",
"k",
",",
"conf",
")",
";",
"boolean",
"skipMissing",
"=",
"(",
"Boolean",
")",
"conf",
".",
"get",
"(",
"Config",
".",
"TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS",
")",
";",
"for",
"(",
"String",
"klassName",
":",
"registrations",
".",
"keySet",
"(",
")",
")",
"{",
"String",
"serializerClassName",
"=",
"registrations",
".",
"get",
"(",
"klassName",
")",
";",
"try",
"{",
"Class",
"klass",
"=",
"Class",
".",
"forName",
"(",
"klassName",
")",
";",
"Class",
"serializerClass",
"=",
"null",
";",
"if",
"(",
"serializerClassName",
"!=",
"null",
")",
"{",
"serializerClass",
"=",
"Class",
".",
"forName",
"(",
"serializerClassName",
")",
";",
"}",
"LOG",
".",
"info",
"(",
"\"Doing kryo.register for class \"",
"+",
"klass",
")",
";",
"if",
"(",
"serializerClass",
"==",
"null",
")",
"{",
"k",
".",
"register",
"(",
"klass",
")",
";",
"}",
"else",
"{",
"k",
".",
"register",
"(",
"klass",
",",
"resolveSerializerInstance",
"(",
"k",
",",
"klass",
",",
"serializerClass",
")",
")",
";",
"}",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"if",
"(",
"skipMissing",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Could not find serialization or class for \"",
"+",
"serializerClassName",
"+",
"\". Skipping registration...\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}",
"kryoFactory",
".",
"postRegister",
"(",
"k",
",",
"conf",
")",
";",
"if",
"(",
"conf",
".",
"get",
"(",
"Config",
".",
"TOPOLOGY_KRYO_DECORATORS",
")",
"!=",
"null",
")",
"{",
"for",
"(",
"String",
"klassName",
":",
"(",
"List",
"<",
"String",
">",
")",
"conf",
".",
"get",
"(",
"Config",
".",
"TOPOLOGY_KRYO_DECORATORS",
")",
")",
"{",
"try",
"{",
"Class",
"klass",
"=",
"Class",
".",
"forName",
"(",
"klassName",
")",
";",
"IKryoDecorator",
"decorator",
"=",
"(",
"IKryoDecorator",
")",
"klass",
".",
"newInstance",
"(",
")",
";",
"decorator",
".",
"decorate",
"(",
"k",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"e",
")",
"{",
"if",
"(",
"skipMissing",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Could not find kryo decorator named \"",
"+",
"klassName",
"+",
"\". Skipping registration...\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}",
"kryoFactory",
".",
"postDecorate",
"(",
"k",
",",
"conf",
")",
";",
"return",
"k",
";",
"}"
] | Get kryo based on conf
@param conf the config
@return Kryo | [
"Get",
"kryo",
"based",
"on",
"conf"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/storm-compatibility/src/java/backtype/storm/serialization/SerializationFactory.java#L55-L135 |
27,966 | apache/incubator-heron | heron/healthmgr/src/java/org/apache/heron/healthmgr/detectors/LargeWaitQueueDetector.java | LargeWaitQueueDetector.detect | @Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
Collection<Symptom> result = new ArrayList<>();
MeasurementsTable waitQueueMetrics
= MeasurementsTable.of(measurements).type(METRIC_WAIT_Q_SIZE.text());
for (String component : waitQueueMetrics.uniqueComponents()) {
Set<String> addresses = new HashSet<>();
MeasurementsTable instanceMetrics = waitQueueMetrics.component(component);
for (String instance : instanceMetrics.uniqueInstances()) {
double avgWaitQSize = instanceMetrics.instance(instance).mean();
if (avgWaitQSize > sizeLimit) {
LOG.info(String.format("Detected large wait queues for instance"
+ "%s, smallest queue is + %f", instance, avgWaitQSize));
addresses.add(instance);
}
}
if (addresses.size() > 0) {
result.add(new Symptom(SYMPTOM_LARGE_WAIT_Q.text(), context.checkpoint(), addresses));
}
}
return result;
} | java | @Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
Collection<Symptom> result = new ArrayList<>();
MeasurementsTable waitQueueMetrics
= MeasurementsTable.of(measurements).type(METRIC_WAIT_Q_SIZE.text());
for (String component : waitQueueMetrics.uniqueComponents()) {
Set<String> addresses = new HashSet<>();
MeasurementsTable instanceMetrics = waitQueueMetrics.component(component);
for (String instance : instanceMetrics.uniqueInstances()) {
double avgWaitQSize = instanceMetrics.instance(instance).mean();
if (avgWaitQSize > sizeLimit) {
LOG.info(String.format("Detected large wait queues for instance"
+ "%s, smallest queue is + %f", instance, avgWaitQSize));
addresses.add(instance);
}
}
if (addresses.size() > 0) {
result.add(new Symptom(SYMPTOM_LARGE_WAIT_Q.text(), context.checkpoint(), addresses));
}
}
return result;
} | [
"@",
"Override",
"public",
"Collection",
"<",
"Symptom",
">",
"detect",
"(",
"Collection",
"<",
"Measurement",
">",
"measurements",
")",
"{",
"Collection",
"<",
"Symptom",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"MeasurementsTable",
"waitQueueMetrics",
"=",
"MeasurementsTable",
".",
"of",
"(",
"measurements",
")",
".",
"type",
"(",
"METRIC_WAIT_Q_SIZE",
".",
"text",
"(",
")",
")",
";",
"for",
"(",
"String",
"component",
":",
"waitQueueMetrics",
".",
"uniqueComponents",
"(",
")",
")",
"{",
"Set",
"<",
"String",
">",
"addresses",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"MeasurementsTable",
"instanceMetrics",
"=",
"waitQueueMetrics",
".",
"component",
"(",
"component",
")",
";",
"for",
"(",
"String",
"instance",
":",
"instanceMetrics",
".",
"uniqueInstances",
"(",
")",
")",
"{",
"double",
"avgWaitQSize",
"=",
"instanceMetrics",
".",
"instance",
"(",
"instance",
")",
".",
"mean",
"(",
")",
";",
"if",
"(",
"avgWaitQSize",
">",
"sizeLimit",
")",
"{",
"LOG",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Detected large wait queues for instance\"",
"+",
"\"%s, smallest queue is + %f\"",
",",
"instance",
",",
"avgWaitQSize",
")",
")",
";",
"addresses",
".",
"add",
"(",
"instance",
")",
";",
"}",
"}",
"if",
"(",
"addresses",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"result",
".",
"add",
"(",
"new",
"Symptom",
"(",
"SYMPTOM_LARGE_WAIT_Q",
".",
"text",
"(",
")",
",",
"context",
".",
"checkpoint",
"(",
")",
",",
"addresses",
")",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Detects all components having a large pending buffer or wait queue
@return A collection of symptoms each one corresponding to components with
large wait queues. | [
"Detects",
"all",
"components",
"having",
"a",
"large",
"pending",
"buffer",
"or",
"wait",
"queue"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/healthmgr/src/java/org/apache/heron/healthmgr/detectors/LargeWaitQueueDetector.java#L56-L80 |
27,967 | apache/incubator-heron | heron/api/src/java/org/apache/heron/api/HeronSubmitter.java | HeronSubmitter.submitTopologyToFile | private static void submitTopologyToFile(TopologyAPI.Topology fTopology,
Map<String, String> heronCmdOptions) {
String dirName = heronCmdOptions.get(CMD_TOPOLOGY_DEFN_TEMPDIR);
if (dirName == null || dirName.isEmpty()) {
throw new TopologySubmissionException("Topology definition temp directory not specified. "
+ "Please set cmdline option: " + CMD_TOPOLOGY_DEFN_TEMPDIR);
}
String fileName =
Paths.get(dirName, fTopology.getName() + TOPOLOGY_DEFINITION_SUFFIX).toString();
try (FileOutputStream fos = new FileOutputStream(new File(fileName));
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] topEncoding = fTopology.toByteArray();
bos.write(topEncoding);
} catch (IOException e) {
throw new TopologySubmissionException("Error writing topology definition to temp directory: "
+ dirName, e);
}
} | java | private static void submitTopologyToFile(TopologyAPI.Topology fTopology,
Map<String, String> heronCmdOptions) {
String dirName = heronCmdOptions.get(CMD_TOPOLOGY_DEFN_TEMPDIR);
if (dirName == null || dirName.isEmpty()) {
throw new TopologySubmissionException("Topology definition temp directory not specified. "
+ "Please set cmdline option: " + CMD_TOPOLOGY_DEFN_TEMPDIR);
}
String fileName =
Paths.get(dirName, fTopology.getName() + TOPOLOGY_DEFINITION_SUFFIX).toString();
try (FileOutputStream fos = new FileOutputStream(new File(fileName));
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] topEncoding = fTopology.toByteArray();
bos.write(topEncoding);
} catch (IOException e) {
throw new TopologySubmissionException("Error writing topology definition to temp directory: "
+ dirName, e);
}
} | [
"private",
"static",
"void",
"submitTopologyToFile",
"(",
"TopologyAPI",
".",
"Topology",
"fTopology",
",",
"Map",
"<",
"String",
",",
"String",
">",
"heronCmdOptions",
")",
"{",
"String",
"dirName",
"=",
"heronCmdOptions",
".",
"get",
"(",
"CMD_TOPOLOGY_DEFN_TEMPDIR",
")",
";",
"if",
"(",
"dirName",
"==",
"null",
"||",
"dirName",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"TopologySubmissionException",
"(",
"\"Topology definition temp directory not specified. \"",
"+",
"\"Please set cmdline option: \"",
"+",
"CMD_TOPOLOGY_DEFN_TEMPDIR",
")",
";",
"}",
"String",
"fileName",
"=",
"Paths",
".",
"get",
"(",
"dirName",
",",
"fTopology",
".",
"getName",
"(",
")",
"+",
"TOPOLOGY_DEFINITION_SUFFIX",
")",
".",
"toString",
"(",
")",
";",
"try",
"(",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"new",
"File",
"(",
"fileName",
")",
")",
";",
"BufferedOutputStream",
"bos",
"=",
"new",
"BufferedOutputStream",
"(",
"fos",
")",
")",
"{",
"byte",
"[",
"]",
"topEncoding",
"=",
"fTopology",
".",
"toByteArray",
"(",
")",
";",
"bos",
".",
"write",
"(",
"topEncoding",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"TopologySubmissionException",
"(",
"\"Error writing topology definition to temp directory: \"",
"+",
"dirName",
",",
"e",
")",
";",
"}",
"}"
] | Submits a topology to definition file
@param fTopology the processing to execute.
@param heronCmdOptions the commandline options.
@throws TopologySubmissionException if the topology submission is failed | [
"Submits",
"a",
"topology",
"to",
"definition",
"file"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/HeronSubmitter.java#L111-L130 |
27,968 | apache/incubator-heron | heron/scheduler-core/src/java/org/apache/heron/scheduler/client/SchedulerClientFactory.java | SchedulerClientFactory.getSchedulerClient | public ISchedulerClient getSchedulerClient() throws SchedulerException {
LOG.fine("Creating scheduler client");
ISchedulerClient schedulerClient;
if (Context.schedulerService(config)) {
// get the instance of the state manager
SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
Scheduler.SchedulerLocation schedulerLocation =
statemgr.getSchedulerLocation(Runtime.topologyName(runtime));
if (schedulerLocation == null) {
throw new SchedulerException("Failed to get scheduler location from state manager");
}
LOG.log(Level.FINE, "Scheduler is listening on location: {0} ", schedulerLocation.toString());
schedulerClient =
new HttpServiceSchedulerClient(config, runtime, schedulerLocation.getHttpEndpoint());
} else {
// create an instance of scheduler
final IScheduler scheduler = LauncherUtils.getInstance()
.getSchedulerInstance(config, runtime);
LOG.fine("Invoke scheduler as a library");
schedulerClient = new LibrarySchedulerClient(config, runtime, scheduler);
}
return schedulerClient;
} | java | public ISchedulerClient getSchedulerClient() throws SchedulerException {
LOG.fine("Creating scheduler client");
ISchedulerClient schedulerClient;
if (Context.schedulerService(config)) {
// get the instance of the state manager
SchedulerStateManagerAdaptor statemgr = Runtime.schedulerStateManagerAdaptor(runtime);
Scheduler.SchedulerLocation schedulerLocation =
statemgr.getSchedulerLocation(Runtime.topologyName(runtime));
if (schedulerLocation == null) {
throw new SchedulerException("Failed to get scheduler location from state manager");
}
LOG.log(Level.FINE, "Scheduler is listening on location: {0} ", schedulerLocation.toString());
schedulerClient =
new HttpServiceSchedulerClient(config, runtime, schedulerLocation.getHttpEndpoint());
} else {
// create an instance of scheduler
final IScheduler scheduler = LauncherUtils.getInstance()
.getSchedulerInstance(config, runtime);
LOG.fine("Invoke scheduler as a library");
schedulerClient = new LibrarySchedulerClient(config, runtime, scheduler);
}
return schedulerClient;
} | [
"public",
"ISchedulerClient",
"getSchedulerClient",
"(",
")",
"throws",
"SchedulerException",
"{",
"LOG",
".",
"fine",
"(",
"\"Creating scheduler client\"",
")",
";",
"ISchedulerClient",
"schedulerClient",
";",
"if",
"(",
"Context",
".",
"schedulerService",
"(",
"config",
")",
")",
"{",
"// get the instance of the state manager",
"SchedulerStateManagerAdaptor",
"statemgr",
"=",
"Runtime",
".",
"schedulerStateManagerAdaptor",
"(",
"runtime",
")",
";",
"Scheduler",
".",
"SchedulerLocation",
"schedulerLocation",
"=",
"statemgr",
".",
"getSchedulerLocation",
"(",
"Runtime",
".",
"topologyName",
"(",
"runtime",
")",
")",
";",
"if",
"(",
"schedulerLocation",
"==",
"null",
")",
"{",
"throw",
"new",
"SchedulerException",
"(",
"\"Failed to get scheduler location from state manager\"",
")",
";",
"}",
"LOG",
".",
"log",
"(",
"Level",
".",
"FINE",
",",
"\"Scheduler is listening on location: {0} \"",
",",
"schedulerLocation",
".",
"toString",
"(",
")",
")",
";",
"schedulerClient",
"=",
"new",
"HttpServiceSchedulerClient",
"(",
"config",
",",
"runtime",
",",
"schedulerLocation",
".",
"getHttpEndpoint",
"(",
")",
")",
";",
"}",
"else",
"{",
"// create an instance of scheduler",
"final",
"IScheduler",
"scheduler",
"=",
"LauncherUtils",
".",
"getInstance",
"(",
")",
".",
"getSchedulerInstance",
"(",
"config",
",",
"runtime",
")",
";",
"LOG",
".",
"fine",
"(",
"\"Invoke scheduler as a library\"",
")",
";",
"schedulerClient",
"=",
"new",
"LibrarySchedulerClient",
"(",
"config",
",",
"runtime",
",",
"scheduler",
")",
";",
"}",
"return",
"schedulerClient",
";",
"}"
] | Implementation of getSchedulerClient - Used to create objects
Currently it creates either HttpServiceSchedulerClient or LibrarySchedulerClient
@return getSchedulerClient created. return null if failed to create ISchedulerClient instance | [
"Implementation",
"of",
"getSchedulerClient",
"-",
"Used",
"to",
"create",
"objects",
"Currently",
"it",
"creates",
"either",
"HttpServiceSchedulerClient",
"or",
"LibrarySchedulerClient"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/scheduler-core/src/java/org/apache/heron/scheduler/client/SchedulerClientFactory.java#L52-L81 |
27,969 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.setName | @Override
public Streamlet<R> setName(String sName) {
checkNotBlank(sName, "Streamlet name cannot be null/blank");
this.name = sName;
return this;
} | java | @Override
public Streamlet<R> setName(String sName) {
checkNotBlank(sName, "Streamlet name cannot be null/blank");
this.name = sName;
return this;
} | [
"@",
"Override",
"public",
"Streamlet",
"<",
"R",
">",
"setName",
"(",
"String",
"sName",
")",
"{",
"checkNotBlank",
"(",
"sName",
",",
"\"Streamlet name cannot be null/blank\"",
")",
";",
"this",
".",
"name",
"=",
"sName",
";",
"return",
"this",
";",
"}"
] | Sets the name of the Streamlet.
@param sName The name given by the user for this streamlet
@return Returns back the Streamlet with changed name | [
"Sets",
"the",
"name",
"of",
"the",
"Streamlet",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L164-L170 |
27,970 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.setDefaultNameIfNone | protected void setDefaultNameIfNone(StreamletNamePrefix prefix, Set<String> stageNames) {
if (getName() == null) {
setName(defaultNameCalculator(prefix, stageNames));
}
if (stageNames.contains(getName())) {
throw new RuntimeException(String.format(
"The stage name %s is used multiple times in the same topology", getName()));
}
stageNames.add(getName());
} | java | protected void setDefaultNameIfNone(StreamletNamePrefix prefix, Set<String> stageNames) {
if (getName() == null) {
setName(defaultNameCalculator(prefix, stageNames));
}
if (stageNames.contains(getName())) {
throw new RuntimeException(String.format(
"The stage name %s is used multiple times in the same topology", getName()));
}
stageNames.add(getName());
} | [
"protected",
"void",
"setDefaultNameIfNone",
"(",
"StreamletNamePrefix",
"prefix",
",",
"Set",
"<",
"String",
">",
"stageNames",
")",
"{",
"if",
"(",
"getName",
"(",
")",
"==",
"null",
")",
"{",
"setName",
"(",
"defaultNameCalculator",
"(",
"prefix",
",",
"stageNames",
")",
")",
";",
"}",
"if",
"(",
"stageNames",
".",
"contains",
"(",
"getName",
"(",
")",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"String",
".",
"format",
"(",
"\"The stage name %s is used multiple times in the same topology\"",
",",
"getName",
"(",
")",
")",
")",
";",
"}",
"stageNames",
".",
"add",
"(",
"getName",
"(",
")",
")",
";",
"}"
] | Sets a default unique name to the Streamlet by type if it is not set.
Otherwise, just checks its uniqueness.
@param prefix The name prefix of this streamlet
@param stageNames The collections of created streamlet/stage names | [
"Sets",
"a",
"default",
"unique",
"name",
"to",
"the",
"Streamlet",
"by",
"type",
"if",
"it",
"is",
"not",
"set",
".",
"Otherwise",
"just",
"checks",
"its",
"uniqueness",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L187-L196 |
27,971 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.getAvailableStreamIds | protected Set<String> getAvailableStreamIds() {
HashSet<String> ids = new HashSet<String>();
ids.add(getStreamId());
return ids;
} | java | protected Set<String> getAvailableStreamIds() {
HashSet<String> ids = new HashSet<String>();
ids.add(getStreamId());
return ids;
} | [
"protected",
"Set",
"<",
"String",
">",
"getAvailableStreamIds",
"(",
")",
"{",
"HashSet",
"<",
"String",
">",
"ids",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"ids",
".",
"add",
"(",
"getStreamId",
"(",
")",
")",
";",
"return",
"ids",
";",
"}"
] | Get the available stream ids in the Streamlet. For most Streamlets,
there is only one internal stream id, therefore the function
returns a set of one single stream id.
@return Returns a set of one single stream id. | [
"Get",
"the",
"available",
"stream",
"ids",
"in",
"the",
"Streamlet",
".",
"For",
"most",
"Streamlets",
"there",
"is",
"only",
"one",
"internal",
"stream",
"id",
"therefore",
"the",
"function",
"returns",
"a",
"set",
"of",
"one",
"single",
"stream",
"id",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L255-L259 |
27,972 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.map | @Override
public <T> Streamlet<T> map(SerializableFunction<R, ? extends T> mapFn) {
checkNotNull(mapFn, "mapFn cannot be null");
MapStreamlet<R, T> retval = new MapStreamlet<>(this, mapFn);
addChild(retval);
return retval;
} | java | @Override
public <T> Streamlet<T> map(SerializableFunction<R, ? extends T> mapFn) {
checkNotNull(mapFn, "mapFn cannot be null");
MapStreamlet<R, T> retval = new MapStreamlet<>(this, mapFn);
addChild(retval);
return retval;
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"Streamlet",
"<",
"T",
">",
"map",
"(",
"SerializableFunction",
"<",
"R",
",",
"?",
"extends",
"T",
">",
"mapFn",
")",
"{",
"checkNotNull",
"(",
"mapFn",
",",
"\"mapFn cannot be null\"",
")",
";",
"MapStreamlet",
"<",
"R",
",",
"T",
">",
"retval",
"=",
"new",
"MapStreamlet",
"<>",
"(",
"this",
",",
"mapFn",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"retval",
";",
"}"
] | Return a new Streamlet by applying mapFn to each element of this Streamlet
@param mapFn The Map Function that should be applied to each element | [
"Return",
"a",
"new",
"Streamlet",
"by",
"applying",
"mapFn",
"to",
"each",
"element",
"of",
"this",
"Streamlet"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L319-L326 |
27,973 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.flatMap | @Override
public <T> Streamlet<T> flatMap(
SerializableFunction<R, ? extends Iterable<? extends T>> flatMapFn) {
checkNotNull(flatMapFn, "flatMapFn cannot be null");
FlatMapStreamlet<R, T> retval = new FlatMapStreamlet<>(this, flatMapFn);
addChild(retval);
return retval;
} | java | @Override
public <T> Streamlet<T> flatMap(
SerializableFunction<R, ? extends Iterable<? extends T>> flatMapFn) {
checkNotNull(flatMapFn, "flatMapFn cannot be null");
FlatMapStreamlet<R, T> retval = new FlatMapStreamlet<>(this, flatMapFn);
addChild(retval);
return retval;
} | [
"@",
"Override",
"public",
"<",
"T",
">",
"Streamlet",
"<",
"T",
">",
"flatMap",
"(",
"SerializableFunction",
"<",
"R",
",",
"?",
"extends",
"Iterable",
"<",
"?",
"extends",
"T",
">",
">",
"flatMapFn",
")",
"{",
"checkNotNull",
"(",
"flatMapFn",
",",
"\"flatMapFn cannot be null\"",
")",
";",
"FlatMapStreamlet",
"<",
"R",
",",
"T",
">",
"retval",
"=",
"new",
"FlatMapStreamlet",
"<>",
"(",
"this",
",",
"flatMapFn",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"retval",
";",
"}"
] | Return a new Streamlet by applying flatMapFn to each element of this Streamlet and
flattening the result
@param flatMapFn The FlatMap Function that should be applied to each element | [
"Return",
"a",
"new",
"Streamlet",
"by",
"applying",
"flatMapFn",
"to",
"each",
"element",
"of",
"this",
"Streamlet",
"and",
"flattening",
"the",
"result"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L333-L341 |
27,974 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.filter | @Override
public Streamlet<R> filter(SerializablePredicate<R> filterFn) {
checkNotNull(filterFn, "filterFn cannot be null");
FilterStreamlet<R> retval = new FilterStreamlet<>(this, filterFn);
addChild(retval);
return retval;
} | java | @Override
public Streamlet<R> filter(SerializablePredicate<R> filterFn) {
checkNotNull(filterFn, "filterFn cannot be null");
FilterStreamlet<R> retval = new FilterStreamlet<>(this, filterFn);
addChild(retval);
return retval;
} | [
"@",
"Override",
"public",
"Streamlet",
"<",
"R",
">",
"filter",
"(",
"SerializablePredicate",
"<",
"R",
">",
"filterFn",
")",
"{",
"checkNotNull",
"(",
"filterFn",
",",
"\"filterFn cannot be null\"",
")",
";",
"FilterStreamlet",
"<",
"R",
">",
"retval",
"=",
"new",
"FilterStreamlet",
"<>",
"(",
"this",
",",
"filterFn",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"retval",
";",
"}"
] | Return a new Streamlet by applying the filterFn on each element of this streamlet
and including only those elements that satisfy the filterFn
@param filterFn The filter Function that should be applied to each element | [
"Return",
"a",
"new",
"Streamlet",
"by",
"applying",
"the",
"filterFn",
"on",
"each",
"element",
"of",
"this",
"streamlet",
"and",
"including",
"only",
"those",
"elements",
"that",
"satisfy",
"the",
"filterFn"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L348-L355 |
27,975 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.repartition | @Override
public Streamlet<R> repartition(int numPartitions,
SerializableBiFunction<R, Integer, List<Integer>> partitionFn) {
checkNotNull(partitionFn, "partitionFn cannot be null");
RemapStreamlet<R> retval = new RemapStreamlet<>(this, partitionFn);
retval.setNumPartitions(numPartitions);
addChild(retval);
return retval;
} | java | @Override
public Streamlet<R> repartition(int numPartitions,
SerializableBiFunction<R, Integer, List<Integer>> partitionFn) {
checkNotNull(partitionFn, "partitionFn cannot be null");
RemapStreamlet<R> retval = new RemapStreamlet<>(this, partitionFn);
retval.setNumPartitions(numPartitions);
addChild(retval);
return retval;
} | [
"@",
"Override",
"public",
"Streamlet",
"<",
"R",
">",
"repartition",
"(",
"int",
"numPartitions",
",",
"SerializableBiFunction",
"<",
"R",
",",
"Integer",
",",
"List",
"<",
"Integer",
">",
">",
"partitionFn",
")",
"{",
"checkNotNull",
"(",
"partitionFn",
",",
"\"partitionFn cannot be null\"",
")",
";",
"RemapStreamlet",
"<",
"R",
">",
"retval",
"=",
"new",
"RemapStreamlet",
"<>",
"(",
"this",
",",
"partitionFn",
")",
";",
"retval",
".",
"setNumPartitions",
"(",
"numPartitions",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"retval",
";",
"}"
] | A more generalized version of repartition where a user can determine which partitions
any particular tuple should go to | [
"A",
"more",
"generalized",
"version",
"of",
"repartition",
"where",
"a",
"user",
"can",
"determine",
"which",
"partitions",
"any",
"particular",
"tuple",
"should",
"go",
"to"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L369-L378 |
27,976 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.reduceByKeyAndWindow | @Override
public <K, T> KVStreamlet<KeyedWindow<K>, T> reduceByKeyAndWindow(
SerializableFunction<R, K> keyExtractor, SerializableFunction<R, T> valueExtractor,
WindowConfig windowCfg, SerializableBinaryOperator<T> reduceFn) {
checkNotNull(keyExtractor, "keyExtractor cannot be null");
checkNotNull(valueExtractor, "valueExtractor cannot be null");
checkNotNull(windowCfg, "windowCfg cannot be null");
checkNotNull(reduceFn, "reduceFn cannot be null");
ReduceByKeyAndWindowStreamlet<R, K, T> retval =
new ReduceByKeyAndWindowStreamlet<>(this, keyExtractor, valueExtractor,
windowCfg, reduceFn);
addChild(retval);
return new KVStreamletShadow<KeyedWindow<K>, T>(retval);
} | java | @Override
public <K, T> KVStreamlet<KeyedWindow<K>, T> reduceByKeyAndWindow(
SerializableFunction<R, K> keyExtractor, SerializableFunction<R, T> valueExtractor,
WindowConfig windowCfg, SerializableBinaryOperator<T> reduceFn) {
checkNotNull(keyExtractor, "keyExtractor cannot be null");
checkNotNull(valueExtractor, "valueExtractor cannot be null");
checkNotNull(windowCfg, "windowCfg cannot be null");
checkNotNull(reduceFn, "reduceFn cannot be null");
ReduceByKeyAndWindowStreamlet<R, K, T> retval =
new ReduceByKeyAndWindowStreamlet<>(this, keyExtractor, valueExtractor,
windowCfg, reduceFn);
addChild(retval);
return new KVStreamletShadow<KeyedWindow<K>, T>(retval);
} | [
"@",
"Override",
"public",
"<",
"K",
",",
"T",
">",
"KVStreamlet",
"<",
"KeyedWindow",
"<",
"K",
">",
",",
"T",
">",
"reduceByKeyAndWindow",
"(",
"SerializableFunction",
"<",
"R",
",",
"K",
">",
"keyExtractor",
",",
"SerializableFunction",
"<",
"R",
",",
"T",
">",
"valueExtractor",
",",
"WindowConfig",
"windowCfg",
",",
"SerializableBinaryOperator",
"<",
"T",
">",
"reduceFn",
")",
"{",
"checkNotNull",
"(",
"keyExtractor",
",",
"\"keyExtractor cannot be null\"",
")",
";",
"checkNotNull",
"(",
"valueExtractor",
",",
"\"valueExtractor cannot be null\"",
")",
";",
"checkNotNull",
"(",
"windowCfg",
",",
"\"windowCfg cannot be null\"",
")",
";",
"checkNotNull",
"(",
"reduceFn",
",",
"\"reduceFn cannot be null\"",
")",
";",
"ReduceByKeyAndWindowStreamlet",
"<",
"R",
",",
"K",
",",
"T",
">",
"retval",
"=",
"new",
"ReduceByKeyAndWindowStreamlet",
"<>",
"(",
"this",
",",
"keyExtractor",
",",
"valueExtractor",
",",
"windowCfg",
",",
"reduceFn",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"new",
"KVStreamletShadow",
"<",
"KeyedWindow",
"<",
"K",
">",
",",
"T",
">",
"(",
"retval",
")",
";",
"}"
] | Return a new Streamlet accumulating tuples of this streamlet over a Window defined by
windowCfg and applying reduceFn on those tuples.
@param keyExtractor The function applied to a tuple of this streamlet to get the key
@param valueExtractor The function applied to a tuple of this streamlet to extract the value
to be reduced on
@param windowCfg This is a specification of what kind of windowing strategy you like to have.
Typical windowing strategies are sliding windows and tumbling windows
@param reduceFn The reduce function that you want to apply to all the values of a key. | [
"Return",
"a",
"new",
"Streamlet",
"accumulating",
"tuples",
"of",
"this",
"streamlet",
"over",
"a",
"Window",
"defined",
"by",
"windowCfg",
"and",
"applying",
"reduceFn",
"on",
"those",
"tuples",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L508-L522 |
27,977 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.reduceByKeyAndWindow | @Override
public <K, T> KVStreamlet<KeyedWindow<K>, T> reduceByKeyAndWindow(
SerializableFunction<R, K> keyExtractor, WindowConfig windowCfg,
T identity, SerializableBiFunction<T, R, ? extends T> reduceFn) {
checkNotNull(keyExtractor, "keyExtractor cannot be null");
checkNotNull(windowCfg, "windowCfg cannot be null");
checkNotNull(identity, "identity cannot be null");
checkNotNull(reduceFn, "reduceFn cannot be null");
GeneralReduceByKeyAndWindowStreamlet<R, K, T> retval =
new GeneralReduceByKeyAndWindowStreamlet<>(this, keyExtractor, windowCfg,
identity, reduceFn);
addChild(retval);
return new KVStreamletShadow<KeyedWindow<K>, T>(retval);
} | java | @Override
public <K, T> KVStreamlet<KeyedWindow<K>, T> reduceByKeyAndWindow(
SerializableFunction<R, K> keyExtractor, WindowConfig windowCfg,
T identity, SerializableBiFunction<T, R, ? extends T> reduceFn) {
checkNotNull(keyExtractor, "keyExtractor cannot be null");
checkNotNull(windowCfg, "windowCfg cannot be null");
checkNotNull(identity, "identity cannot be null");
checkNotNull(reduceFn, "reduceFn cannot be null");
GeneralReduceByKeyAndWindowStreamlet<R, K, T> retval =
new GeneralReduceByKeyAndWindowStreamlet<>(this, keyExtractor, windowCfg,
identity, reduceFn);
addChild(retval);
return new KVStreamletShadow<KeyedWindow<K>, T>(retval);
} | [
"@",
"Override",
"public",
"<",
"K",
",",
"T",
">",
"KVStreamlet",
"<",
"KeyedWindow",
"<",
"K",
">",
",",
"T",
">",
"reduceByKeyAndWindow",
"(",
"SerializableFunction",
"<",
"R",
",",
"K",
">",
"keyExtractor",
",",
"WindowConfig",
"windowCfg",
",",
"T",
"identity",
",",
"SerializableBiFunction",
"<",
"T",
",",
"R",
",",
"?",
"extends",
"T",
">",
"reduceFn",
")",
"{",
"checkNotNull",
"(",
"keyExtractor",
",",
"\"keyExtractor cannot be null\"",
")",
";",
"checkNotNull",
"(",
"windowCfg",
",",
"\"windowCfg cannot be null\"",
")",
";",
"checkNotNull",
"(",
"identity",
",",
"\"identity cannot be null\"",
")",
";",
"checkNotNull",
"(",
"reduceFn",
",",
"\"reduceFn cannot be null\"",
")",
";",
"GeneralReduceByKeyAndWindowStreamlet",
"<",
"R",
",",
"K",
",",
"T",
">",
"retval",
"=",
"new",
"GeneralReduceByKeyAndWindowStreamlet",
"<>",
"(",
"this",
",",
"keyExtractor",
",",
"windowCfg",
",",
"identity",
",",
"reduceFn",
")",
";",
"addChild",
"(",
"retval",
")",
";",
"return",
"new",
"KVStreamletShadow",
"<",
"KeyedWindow",
"<",
"K",
">",
",",
"T",
">",
"(",
"retval",
")",
";",
"}"
] | Return a new Streamlet accumulating tuples of this streamlet over a Window defined by
windowCfg and applying reduceFn on those tuples. For each window, the value identity is used
as a initial value. All the matching tuples are reduced using reduceFn starting from this
initial value.
@param keyExtractor The function applied to a tuple of this streamlet to get the key
@param windowCfg This is a specification of what kind of windowing strategy you like to have.
Typical windowing strategies are sliding windows and tumbling windows
@param identity The identity element is both the initial value inside the reduction window
and the default result if there are no elements in the window
@param reduceFn The reduce function takes two parameters: a partial result of the reduction
and the next element of the stream. It returns a new partial result. | [
"Return",
"a",
"new",
"Streamlet",
"accumulating",
"tuples",
"of",
"this",
"streamlet",
"over",
"a",
"Window",
"defined",
"by",
"windowCfg",
"and",
"applying",
"reduceFn",
"on",
"those",
"tuples",
".",
"For",
"each",
"window",
"the",
"value",
"identity",
"is",
"used",
"as",
"a",
"initial",
"value",
".",
"All",
"the",
"matching",
"tuples",
"are",
"reduced",
"using",
"reduceFn",
"starting",
"from",
"this",
"initial",
"value",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L537-L551 |
27,978 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.consume | @Override
public void consume(SerializableConsumer<R> consumer) {
checkNotNull(consumer, "consumer cannot be null");
ConsumerStreamlet<R> consumerStreamlet = new ConsumerStreamlet<>(this, consumer);
addChild(consumerStreamlet);
} | java | @Override
public void consume(SerializableConsumer<R> consumer) {
checkNotNull(consumer, "consumer cannot be null");
ConsumerStreamlet<R> consumerStreamlet = new ConsumerStreamlet<>(this, consumer);
addChild(consumerStreamlet);
} | [
"@",
"Override",
"public",
"void",
"consume",
"(",
"SerializableConsumer",
"<",
"R",
">",
"consumer",
")",
"{",
"checkNotNull",
"(",
"consumer",
",",
"\"consumer cannot be null\"",
")",
";",
"ConsumerStreamlet",
"<",
"R",
">",
"consumerStreamlet",
"=",
"new",
"ConsumerStreamlet",
"<>",
"(",
"this",
",",
"consumer",
")",
";",
"addChild",
"(",
"consumerStreamlet",
")",
";",
"}"
] | Applies the consumer function for every element of this streamlet
@param consumer The user supplied consumer function that is invoked for each element | [
"Applies",
"the",
"consumer",
"function",
"for",
"every",
"element",
"of",
"this",
"streamlet"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L583-L589 |
27,979 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.toSink | @Override
public void toSink(Sink<R> sink) {
checkNotNull(sink, "sink cannot be null");
SinkStreamlet<R> sinkStreamlet = new SinkStreamlet<>(this, sink);
addChild(sinkStreamlet);
} | java | @Override
public void toSink(Sink<R> sink) {
checkNotNull(sink, "sink cannot be null");
SinkStreamlet<R> sinkStreamlet = new SinkStreamlet<>(this, sink);
addChild(sinkStreamlet);
} | [
"@",
"Override",
"public",
"void",
"toSink",
"(",
"Sink",
"<",
"R",
">",
"sink",
")",
"{",
"checkNotNull",
"(",
"sink",
",",
"\"sink cannot be null\"",
")",
";",
"SinkStreamlet",
"<",
"R",
">",
"sinkStreamlet",
"=",
"new",
"SinkStreamlet",
"<>",
"(",
"this",
",",
"sink",
")",
";",
"addChild",
"(",
"sinkStreamlet",
")",
";",
"}"
] | Uses the sink to consume every element of this streamlet
@param sink The Sink that consumes | [
"Uses",
"the",
"sink",
"to",
"consume",
"every",
"element",
"of",
"this",
"streamlet"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L595-L601 |
27,980 | apache/incubator-heron | heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java | StreamletImpl.split | @Override
public Streamlet<R> split(Map<String, SerializablePredicate<R>> splitFns) {
// Make sure map and stream ids are not empty
require(splitFns.size() > 0, "At least one entry is required");
require(splitFns.keySet().stream().allMatch(stream -> StringUtils.isNotBlank(stream)),
"Stream Id can not be blank");
SplitStreamlet<R> splitStreamlet = new SplitStreamlet<R>(this, splitFns);
addChild(splitStreamlet);
return splitStreamlet;
} | java | @Override
public Streamlet<R> split(Map<String, SerializablePredicate<R>> splitFns) {
// Make sure map and stream ids are not empty
require(splitFns.size() > 0, "At least one entry is required");
require(splitFns.keySet().stream().allMatch(stream -> StringUtils.isNotBlank(stream)),
"Stream Id can not be blank");
SplitStreamlet<R> splitStreamlet = new SplitStreamlet<R>(this, splitFns);
addChild(splitStreamlet);
return splitStreamlet;
} | [
"@",
"Override",
"public",
"Streamlet",
"<",
"R",
">",
"split",
"(",
"Map",
"<",
"String",
",",
"SerializablePredicate",
"<",
"R",
">",
">",
"splitFns",
")",
"{",
"// Make sure map and stream ids are not empty",
"require",
"(",
"splitFns",
".",
"size",
"(",
")",
">",
"0",
",",
"\"At least one entry is required\"",
")",
";",
"require",
"(",
"splitFns",
".",
"keySet",
"(",
")",
".",
"stream",
"(",
")",
".",
"allMatch",
"(",
"stream",
"->",
"StringUtils",
".",
"isNotBlank",
"(",
"stream",
")",
")",
",",
"\"Stream Id can not be blank\"",
")",
";",
"SplitStreamlet",
"<",
"R",
">",
"splitStreamlet",
"=",
"new",
"SplitStreamlet",
"<",
"R",
">",
"(",
"this",
",",
"splitFns",
")",
";",
"addChild",
"(",
"splitStreamlet",
")",
";",
"return",
"splitStreamlet",
";",
"}"
] | Returns multiple streams by splitting incoming stream.
@param splitFns The Split Functions that test if the tuple should be emitted into each stream
Note that there could be 0 or multiple target stream ids | [
"Returns",
"multiple",
"streams",
"by",
"splitting",
"incoming",
"stream",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/streamlet/impl/StreamletImpl.java#L660-L670 |
27,981 | apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java | RotatingMap.rotate | public void rotate() {
Map<Long, Long> m = buckets.removeLast();
buckets.addFirst(new HashMap<Long, Long>());
} | java | public void rotate() {
Map<Long, Long> m = buckets.removeLast();
buckets.addFirst(new HashMap<Long, Long>());
} | [
"public",
"void",
"rotate",
"(",
")",
"{",
"Map",
"<",
"Long",
",",
"Long",
">",
"m",
"=",
"buckets",
".",
"removeLast",
"(",
")",
";",
"buckets",
".",
"addFirst",
"(",
"new",
"HashMap",
"<",
"Long",
",",
"Long",
">",
"(",
")",
")",
";",
"}"
] | instantiates a new map at the front of the list | [
"instantiates",
"a",
"new",
"map",
"at",
"the",
"front",
"of",
"the",
"list"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java#L49-L52 |
27,982 | apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java | RotatingMap.anchor | public boolean anchor(long key, long value) {
for (Map<Long, Long> m : buckets) {
if (m.containsKey(key)) {
long currentValue = m.get(key);
long newValue = currentValue ^ value;
m.put(key, newValue);
return newValue == 0;
}
}
return false;
} | java | public boolean anchor(long key, long value) {
for (Map<Long, Long> m : buckets) {
if (m.containsKey(key)) {
long currentValue = m.get(key);
long newValue = currentValue ^ value;
m.put(key, newValue);
return newValue == 0;
}
}
return false;
} | [
"public",
"boolean",
"anchor",
"(",
"long",
"key",
",",
"long",
"value",
")",
"{",
"for",
"(",
"Map",
"<",
"Long",
",",
"Long",
">",
"m",
":",
"buckets",
")",
"{",
"if",
"(",
"m",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"long",
"currentValue",
"=",
"m",
".",
"get",
"(",
"key",
")",
";",
"long",
"newValue",
"=",
"currentValue",
"^",
"value",
";",
"m",
".",
"put",
"(",
"key",
",",
"newValue",
")",
";",
"return",
"newValue",
"==",
"0",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | xor turns zero. False otherwise | [
"xor",
"turns",
"zero",
".",
"False",
"otherwise"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java#L63-L74 |
27,983 | apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java | RotatingMap.remove | public boolean remove(long key) {
for (Map<Long, Long> m : buckets) {
if (m.remove(key) != null) {
return true;
}
}
return false;
} | java | public boolean remove(long key) {
for (Map<Long, Long> m : buckets) {
if (m.remove(key) != null) {
return true;
}
}
return false;
} | [
"public",
"boolean",
"remove",
"(",
"long",
"key",
")",
"{",
"for",
"(",
"Map",
"<",
"Long",
",",
"Long",
">",
"m",
":",
"buckets",
")",
"{",
"if",
"(",
"m",
".",
"remove",
"(",
"key",
")",
"!=",
"null",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | from some map. False otherwise. | [
"from",
"some",
"map",
".",
"False",
"otherwise",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/utils/RotatingMap.java#L80-L87 |
27,984 | apache/incubator-heron | heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/AbstractWebSink.java | AbstractWebSink.startHttpServer | protected void startHttpServer(String path, int port) {
try {
httpServer = HttpServer.create(new InetSocketAddress(port), 0);
httpServer.createContext(path, httpExchange -> {
byte[] response = generateResponse();
httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length);
OutputStream os = httpExchange.getResponseBody();
os.write(response);
os.close();
LOG.log(Level.INFO, "Received metrics request.");
});
LOG.info("Starting web sink server on port: " + port);
httpServer.start();
} catch (IOException e) {
throw new RuntimeException("Failed to create Http server on port " + port, e);
}
} | java | protected void startHttpServer(String path, int port) {
try {
httpServer = HttpServer.create(new InetSocketAddress(port), 0);
httpServer.createContext(path, httpExchange -> {
byte[] response = generateResponse();
httpExchange.sendResponseHeaders(HTTP_STATUS_OK, response.length);
OutputStream os = httpExchange.getResponseBody();
os.write(response);
os.close();
LOG.log(Level.INFO, "Received metrics request.");
});
LOG.info("Starting web sink server on port: " + port);
httpServer.start();
} catch (IOException e) {
throw new RuntimeException("Failed to create Http server on port " + port, e);
}
} | [
"protected",
"void",
"startHttpServer",
"(",
"String",
"path",
",",
"int",
"port",
")",
"{",
"try",
"{",
"httpServer",
"=",
"HttpServer",
".",
"create",
"(",
"new",
"InetSocketAddress",
"(",
"port",
")",
",",
"0",
")",
";",
"httpServer",
".",
"createContext",
"(",
"path",
",",
"httpExchange",
"->",
"{",
"byte",
"[",
"]",
"response",
"=",
"generateResponse",
"(",
")",
";",
"httpExchange",
".",
"sendResponseHeaders",
"(",
"HTTP_STATUS_OK",
",",
"response",
".",
"length",
")",
";",
"OutputStream",
"os",
"=",
"httpExchange",
".",
"getResponseBody",
"(",
")",
";",
"os",
".",
"write",
"(",
"response",
")",
";",
"os",
".",
"close",
"(",
")",
";",
"LOG",
".",
"log",
"(",
"Level",
".",
"INFO",
",",
"\"Received metrics request.\"",
")",
";",
"}",
")",
";",
"LOG",
".",
"info",
"(",
"\"Starting web sink server on port: \"",
"+",
"port",
")",
";",
"httpServer",
".",
"start",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Failed to create Http server on port \"",
"+",
"port",
",",
"e",
")",
";",
"}",
"}"
] | Start a http server on supplied port that will serve the metrics, as json,
on the specified path.
@param path
@param port | [
"Start",
"a",
"http",
"server",
"on",
"supplied",
"port",
"that",
"will",
"serve",
"the",
"metrics",
"as",
"json",
"on",
"the",
"specified",
"path",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/AbstractWebSink.java#L129-L145 |
27,985 | apache/incubator-heron | heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/AbstractWebSink.java | AbstractWebSink.createCache | <K, V> Cache<K, V> createCache() {
return CacheBuilder.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(cacheTtlSeconds, TimeUnit.SECONDS)
.ticker(cacheTicker)
.build();
} | java | <K, V> Cache<K, V> createCache() {
return CacheBuilder.newBuilder()
.maximumSize(cacheMaxSize)
.expireAfterWrite(cacheTtlSeconds, TimeUnit.SECONDS)
.ticker(cacheTicker)
.build();
} | [
"<",
"K",
",",
"V",
">",
"Cache",
"<",
"K",
",",
"V",
">",
"createCache",
"(",
")",
"{",
"return",
"CacheBuilder",
".",
"newBuilder",
"(",
")",
".",
"maximumSize",
"(",
"cacheMaxSize",
")",
".",
"expireAfterWrite",
"(",
"cacheTtlSeconds",
",",
"TimeUnit",
".",
"SECONDS",
")",
".",
"ticker",
"(",
"cacheTicker",
")",
".",
"build",
"(",
")",
";",
"}"
] | a convenience method for creating a metrics cache | [
"a",
"convenience",
"method",
"for",
"creating",
"a",
"metrics",
"cache"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/AbstractWebSink.java#L148-L154 |
27,986 | apache/incubator-heron | heron/healthmgr/src/java/org/apache/heron/healthmgr/detectors/GrowingWaitQueueDetector.java | GrowingWaitQueueDetector.detect | @Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
Collection<Symptom> result = new ArrayList<>();
MeasurementsTable waitQueueMetrics
= MeasurementsTable.of(measurements).type(METRIC_WAIT_Q_SIZE.text());
for (String component : waitQueueMetrics.uniqueComponents()) {
double maxSlope = computeWaitQueueSizeTrend(waitQueueMetrics.component(component));
if (maxSlope > rateLimit) {
LOG.info(String.format("Detected growing wait queues for %s, max rate %f",
component, maxSlope));
Collection<String> addresses = Collections.singletonList(component);
result.add(new Symptom(SYMPTOM_GROWING_WAIT_Q.text(), context.checkpoint(), addresses));
}
}
return result;
} | java | @Override
public Collection<Symptom> detect(Collection<Measurement> measurements) {
Collection<Symptom> result = new ArrayList<>();
MeasurementsTable waitQueueMetrics
= MeasurementsTable.of(measurements).type(METRIC_WAIT_Q_SIZE.text());
for (String component : waitQueueMetrics.uniqueComponents()) {
double maxSlope = computeWaitQueueSizeTrend(waitQueueMetrics.component(component));
if (maxSlope > rateLimit) {
LOG.info(String.format("Detected growing wait queues for %s, max rate %f",
component, maxSlope));
Collection<String> addresses = Collections.singletonList(component);
result.add(new Symptom(SYMPTOM_GROWING_WAIT_Q.text(), context.checkpoint(), addresses));
}
}
return result;
} | [
"@",
"Override",
"public",
"Collection",
"<",
"Symptom",
">",
"detect",
"(",
"Collection",
"<",
"Measurement",
">",
"measurements",
")",
"{",
"Collection",
"<",
"Symptom",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"MeasurementsTable",
"waitQueueMetrics",
"=",
"MeasurementsTable",
".",
"of",
"(",
"measurements",
")",
".",
"type",
"(",
"METRIC_WAIT_Q_SIZE",
".",
"text",
"(",
")",
")",
";",
"for",
"(",
"String",
"component",
":",
"waitQueueMetrics",
".",
"uniqueComponents",
"(",
")",
")",
"{",
"double",
"maxSlope",
"=",
"computeWaitQueueSizeTrend",
"(",
"waitQueueMetrics",
".",
"component",
"(",
"component",
")",
")",
";",
"if",
"(",
"maxSlope",
">",
"rateLimit",
")",
"{",
"LOG",
".",
"info",
"(",
"String",
".",
"format",
"(",
"\"Detected growing wait queues for %s, max rate %f\"",
",",
"component",
",",
"maxSlope",
")",
")",
";",
"Collection",
"<",
"String",
">",
"addresses",
"=",
"Collections",
".",
"singletonList",
"(",
"component",
")",
";",
"result",
".",
"add",
"(",
"new",
"Symptom",
"(",
"SYMPTOM_GROWING_WAIT_Q",
".",
"text",
"(",
")",
",",
"context",
".",
"checkpoint",
"(",
")",
",",
"addresses",
")",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Detects all components unable to keep up with input load, hence having a growing pending buffer
or wait queue
@return A collection of symptoms each one corresponding to a components executing slower
than input rate. | [
"Detects",
"all",
"components",
"unable",
"to",
"keep",
"up",
"with",
"input",
"load",
"hence",
"having",
"a",
"growing",
"pending",
"buffer",
"or",
"wait",
"queue"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/healthmgr/src/java/org/apache/heron/healthmgr/detectors/GrowingWaitQueueDetector.java#L60-L78 |
27,987 | apache/incubator-heron | heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/WebSink.java | WebSink.processMetrics | static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
Map<String, Double> map = new HashMap<>();
for (MetricsInfo r : metrics) {
try {
map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
} catch (NumberFormatException ne) {
LOG.log(Level.SEVERE, "Could not parse metric, Name: "
+ r.getName() + " Value: " + r.getValue(), ne);
}
}
return map;
} | java | static Map<String, Double> processMetrics(String prefix, Iterable<MetricsInfo> metrics) {
Map<String, Double> map = new HashMap<>();
for (MetricsInfo r : metrics) {
try {
map.put(prefix + r.getName(), Double.valueOf(r.getValue()));
} catch (NumberFormatException ne) {
LOG.log(Level.SEVERE, "Could not parse metric, Name: "
+ r.getName() + " Value: " + r.getValue(), ne);
}
}
return map;
} | [
"static",
"Map",
"<",
"String",
",",
"Double",
">",
"processMetrics",
"(",
"String",
"prefix",
",",
"Iterable",
"<",
"MetricsInfo",
">",
"metrics",
")",
"{",
"Map",
"<",
"String",
",",
"Double",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"for",
"(",
"MetricsInfo",
"r",
":",
"metrics",
")",
"{",
"try",
"{",
"map",
".",
"put",
"(",
"prefix",
"+",
"r",
".",
"getName",
"(",
")",
",",
"Double",
".",
"valueOf",
"(",
"r",
".",
"getValue",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"ne",
")",
"{",
"LOG",
".",
"log",
"(",
"Level",
".",
"SEVERE",
",",
"\"Could not parse metric, Name: \"",
"+",
"r",
".",
"getName",
"(",
")",
"+",
"\" Value: \"",
"+",
"r",
".",
"getValue",
"(",
")",
",",
"ne",
")",
";",
"}",
"}",
"return",
"map",
";",
"}"
] | Helper to prefix metric names, convert metric value to double and return as map
@param prefix
@param metrics
@return Map of metric name to metric value | [
"Helper",
"to",
"prefix",
"metric",
"names",
"convert",
"metric",
"value",
"to",
"double",
"and",
"return",
"as",
"map"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/metricsmgr/src/java/org/apache/heron/metricsmgr/sink/WebSink.java#L135-L146 |
27,988 | apache/incubator-heron | examples/src/java/org/apache/heron/examples/streamlet/WireRequestsTopology.java | WireRequestsTopology.fraudDetect | private static boolean fraudDetect(WireRequest request) {
String logMessage;
boolean fraudulent = FRAUDULENT_CUSTOMERS.contains(request.getCustomerId());
if (fraudulent) {
logMessage = String.format("Rejected fraudulent customer %s",
request.getCustomerId());
LOG.warning(logMessage);
} else {
logMessage = String.format("Accepted request for $%d from customer %s",
request.getAmount(),
request.getCustomerId());
LOG.info(logMessage);
}
return !fraudulent;
} | java | private static boolean fraudDetect(WireRequest request) {
String logMessage;
boolean fraudulent = FRAUDULENT_CUSTOMERS.contains(request.getCustomerId());
if (fraudulent) {
logMessage = String.format("Rejected fraudulent customer %s",
request.getCustomerId());
LOG.warning(logMessage);
} else {
logMessage = String.format("Accepted request for $%d from customer %s",
request.getAmount(),
request.getCustomerId());
LOG.info(logMessage);
}
return !fraudulent;
} | [
"private",
"static",
"boolean",
"fraudDetect",
"(",
"WireRequest",
"request",
")",
"{",
"String",
"logMessage",
";",
"boolean",
"fraudulent",
"=",
"FRAUDULENT_CUSTOMERS",
".",
"contains",
"(",
"request",
".",
"getCustomerId",
"(",
")",
")",
";",
"if",
"(",
"fraudulent",
")",
"{",
"logMessage",
"=",
"String",
".",
"format",
"(",
"\"Rejected fraudulent customer %s\"",
",",
"request",
".",
"getCustomerId",
"(",
")",
")",
";",
"LOG",
".",
"warning",
"(",
"logMessage",
")",
";",
"}",
"else",
"{",
"logMessage",
"=",
"String",
".",
"format",
"(",
"\"Accepted request for $%d from customer %s\"",
",",
"request",
".",
"getAmount",
"(",
")",
",",
"request",
".",
"getCustomerId",
"(",
")",
")",
";",
"LOG",
".",
"info",
"(",
"logMessage",
")",
";",
"}",
"return",
"!",
"fraudulent",
";",
"}"
] | Each request is checked to make sure that requests from untrustworthy customers
are rejected. | [
"Each",
"request",
"is",
"checked",
"to",
"make",
"sure",
"that",
"requests",
"from",
"untrustworthy",
"customers",
"are",
"rejected",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/examples/src/java/org/apache/heron/examples/streamlet/WireRequestsTopology.java#L112-L129 |
27,989 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.add | void add(PackingPlan.InstancePlan instancePlan) {
if (this.instances.contains(instancePlan)) {
throw new PackingException(String.format(
"Instance %s already exists in container %s", instancePlan, toString()));
}
this.instances.add(instancePlan);
} | java | void add(PackingPlan.InstancePlan instancePlan) {
if (this.instances.contains(instancePlan)) {
throw new PackingException(String.format(
"Instance %s already exists in container %s", instancePlan, toString()));
}
this.instances.add(instancePlan);
} | [
"void",
"add",
"(",
"PackingPlan",
".",
"InstancePlan",
"instancePlan",
")",
"{",
"if",
"(",
"this",
".",
"instances",
".",
"contains",
"(",
"instancePlan",
")",
")",
"{",
"throw",
"new",
"PackingException",
"(",
"String",
".",
"format",
"(",
"\"Instance %s already exists in container %s\"",
",",
"instancePlan",
",",
"toString",
"(",
")",
")",
")",
";",
"}",
"this",
".",
"instances",
".",
"add",
"(",
"instancePlan",
")",
";",
"}"
] | Update the resources currently used by the container, when a new instance with specific
resource requirements has been assigned to the container. | [
"Update",
"the",
"resources",
"currently",
"used",
"by",
"the",
"container",
"when",
"a",
"new",
"instance",
"with",
"specific",
"resource",
"requirements",
"has",
"been",
"assigned",
"to",
"the",
"container",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L75-L81 |
27,990 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.removeAnyInstanceOfComponent | Optional<PackingPlan.InstancePlan> removeAnyInstanceOfComponent(String component) {
Optional<PackingPlan.InstancePlan> instancePlan = getAnyInstanceOfComponent(component);
if (instancePlan.isPresent()) {
PackingPlan.InstancePlan plan = instancePlan.get();
this.instances.remove(plan);
return instancePlan;
}
return Optional.absent();
} | java | Optional<PackingPlan.InstancePlan> removeAnyInstanceOfComponent(String component) {
Optional<PackingPlan.InstancePlan> instancePlan = getAnyInstanceOfComponent(component);
if (instancePlan.isPresent()) {
PackingPlan.InstancePlan plan = instancePlan.get();
this.instances.remove(plan);
return instancePlan;
}
return Optional.absent();
} | [
"Optional",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"removeAnyInstanceOfComponent",
"(",
"String",
"component",
")",
"{",
"Optional",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"instancePlan",
"=",
"getAnyInstanceOfComponent",
"(",
"component",
")",
";",
"if",
"(",
"instancePlan",
".",
"isPresent",
"(",
")",
")",
"{",
"PackingPlan",
".",
"InstancePlan",
"plan",
"=",
"instancePlan",
".",
"get",
"(",
")",
";",
"this",
".",
"instances",
".",
"remove",
"(",
"plan",
")",
";",
"return",
"instancePlan",
";",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Remove an instance of a particular component from a container and update its
corresponding resources.
@return the corresponding instance plan if the instance is removed the container.
Return void if an instance is not found | [
"Remove",
"an",
"instance",
"of",
"a",
"particular",
"component",
"from",
"a",
"container",
"and",
"update",
"its",
"corresponding",
"resources",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L90-L98 |
27,991 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.getAnyInstanceOfComponent | private Optional<PackingPlan.InstancePlan> getAnyInstanceOfComponent(String componentName) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getComponentName().equals(componentName)) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | java | private Optional<PackingPlan.InstancePlan> getAnyInstanceOfComponent(String componentName) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getComponentName().equals(componentName)) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | [
"private",
"Optional",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"getAnyInstanceOfComponent",
"(",
"String",
"componentName",
")",
"{",
"for",
"(",
"PackingPlan",
".",
"InstancePlan",
"instancePlan",
":",
"this",
".",
"instances",
")",
"{",
"if",
"(",
"instancePlan",
".",
"getComponentName",
"(",
")",
".",
"equals",
"(",
"componentName",
")",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"instancePlan",
")",
";",
"}",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Find whether any instance of a particular component is assigned to the container
@return an optional including the InstancePlan if found | [
"Find",
"whether",
"any",
"instance",
"of",
"a",
"particular",
"component",
"is",
"assigned",
"to",
"the",
"container"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L111-L118 |
27,992 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.getInstance | Optional<PackingPlan.InstancePlan> getInstance(String componentName, int componentIndex) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getComponentName().equals(componentName)
&& instancePlan.getComponentIndex() == componentIndex) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | java | Optional<PackingPlan.InstancePlan> getInstance(String componentName, int componentIndex) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getComponentName().equals(componentName)
&& instancePlan.getComponentIndex() == componentIndex) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | [
"Optional",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"getInstance",
"(",
"String",
"componentName",
",",
"int",
"componentIndex",
")",
"{",
"for",
"(",
"PackingPlan",
".",
"InstancePlan",
"instancePlan",
":",
"this",
".",
"instances",
")",
"{",
"if",
"(",
"instancePlan",
".",
"getComponentName",
"(",
")",
".",
"equals",
"(",
"componentName",
")",
"&&",
"instancePlan",
".",
"getComponentIndex",
"(",
")",
"==",
"componentIndex",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"instancePlan",
")",
";",
"}",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Return the instance of componentName with a matching componentIndex if it exists
@return an optional including the InstancePlan if found | [
"Return",
"the",
"instance",
"of",
"componentName",
"with",
"a",
"matching",
"componentIndex",
"if",
"it",
"exists"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L125-L133 |
27,993 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.getInstance | Optional<PackingPlan.InstancePlan> getInstance(int taskId) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getTaskId() == taskId) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | java | Optional<PackingPlan.InstancePlan> getInstance(int taskId) {
for (PackingPlan.InstancePlan instancePlan : this.instances) {
if (instancePlan.getTaskId() == taskId) {
return Optional.of(instancePlan);
}
}
return Optional.absent();
} | [
"Optional",
"<",
"PackingPlan",
".",
"InstancePlan",
">",
"getInstance",
"(",
"int",
"taskId",
")",
"{",
"for",
"(",
"PackingPlan",
".",
"InstancePlan",
"instancePlan",
":",
"this",
".",
"instances",
")",
"{",
"if",
"(",
"instancePlan",
".",
"getTaskId",
"(",
")",
"==",
"taskId",
")",
"{",
"return",
"Optional",
".",
"of",
"(",
"instancePlan",
")",
";",
"}",
"}",
"return",
"Optional",
".",
"absent",
"(",
")",
";",
"}"
] | Return the instance of with a given taskId if it exists
@return an optional including the InstancePlan if found | [
"Return",
"the",
"instance",
"of",
"with",
"a",
"given",
"taskId",
"if",
"it",
"exists"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L140-L147 |
27,994 | apache/incubator-heron | heron/packing/src/java/org/apache/heron/packing/builder/Container.java | Container.getTotalUsedResources | public Resource getTotalUsedResources() {
return getInstances().stream()
.map(PackingPlan.InstancePlan::getResource)
.reduce(Resource.EMPTY_RESOURCE, Resource::plus)
.plus(getPadding());
} | java | public Resource getTotalUsedResources() {
return getInstances().stream()
.map(PackingPlan.InstancePlan::getResource)
.reduce(Resource.EMPTY_RESOURCE, Resource::plus)
.plus(getPadding());
} | [
"public",
"Resource",
"getTotalUsedResources",
"(",
")",
"{",
"return",
"getInstances",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"PackingPlan",
".",
"InstancePlan",
"::",
"getResource",
")",
".",
"reduce",
"(",
"Resource",
".",
"EMPTY_RESOURCE",
",",
"Resource",
"::",
"plus",
")",
".",
"plus",
"(",
"getPadding",
"(",
")",
")",
";",
"}"
] | Computes the used resources of the container by taking into account the resources
allocated for each instance.
@return a Resource object that describes the used CPU, RAM and disk in the container. | [
"Computes",
"the",
"used",
"resources",
"of",
"the",
"container",
"by",
"taking",
"into",
"account",
"the",
"resources",
"allocated",
"for",
"each",
"instance",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/packing/src/java/org/apache/heron/packing/builder/Container.java#L155-L160 |
27,995 | apache/incubator-heron | heron/healthmgr/src/java/org/apache/heron/healthmgr/sensors/BufferSizeSensor.java | BufferSizeSensor.fetch | @Override
public Collection<Measurement> fetch() {
Collection<Measurement> result = new ArrayList<>();
Instant now = context.checkpoint();
List<String> boltComponents = physicalPlanProvider.getBoltNames();
Duration duration = getDuration();
for (String component : boltComponents) {
String[] boltInstanceNames = packingPlanProvider.getBoltInstanceNames(component);
for (String instance : boltInstanceNames) {
String metric = getMetricName() + instance + MetricName.METRIC_WAIT_Q_SIZE_SUFFIX;
Collection<Measurement> stmgrResult
= metricsProvider.getMeasurements(now, duration, metric, COMPONENT_STMGR);
if (stmgrResult.isEmpty()) {
continue;
}
MeasurementsTable table = MeasurementsTable.of(stmgrResult).component(COMPONENT_STMGR);
if (table.size() == 0) {
continue;
}
double totalSize = table.type(metric).sum();
Measurement measurement
= new Measurement(component, instance, getMetricName(), now, totalSize);
result.add(measurement);
}
}
return result;
} | java | @Override
public Collection<Measurement> fetch() {
Collection<Measurement> result = new ArrayList<>();
Instant now = context.checkpoint();
List<String> boltComponents = physicalPlanProvider.getBoltNames();
Duration duration = getDuration();
for (String component : boltComponents) {
String[] boltInstanceNames = packingPlanProvider.getBoltInstanceNames(component);
for (String instance : boltInstanceNames) {
String metric = getMetricName() + instance + MetricName.METRIC_WAIT_Q_SIZE_SUFFIX;
Collection<Measurement> stmgrResult
= metricsProvider.getMeasurements(now, duration, metric, COMPONENT_STMGR);
if (stmgrResult.isEmpty()) {
continue;
}
MeasurementsTable table = MeasurementsTable.of(stmgrResult).component(COMPONENT_STMGR);
if (table.size() == 0) {
continue;
}
double totalSize = table.type(metric).sum();
Measurement measurement
= new Measurement(component, instance, getMetricName(), now, totalSize);
result.add(measurement);
}
}
return result;
} | [
"@",
"Override",
"public",
"Collection",
"<",
"Measurement",
">",
"fetch",
"(",
")",
"{",
"Collection",
"<",
"Measurement",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Instant",
"now",
"=",
"context",
".",
"checkpoint",
"(",
")",
";",
"List",
"<",
"String",
">",
"boltComponents",
"=",
"physicalPlanProvider",
".",
"getBoltNames",
"(",
")",
";",
"Duration",
"duration",
"=",
"getDuration",
"(",
")",
";",
"for",
"(",
"String",
"component",
":",
"boltComponents",
")",
"{",
"String",
"[",
"]",
"boltInstanceNames",
"=",
"packingPlanProvider",
".",
"getBoltInstanceNames",
"(",
"component",
")",
";",
"for",
"(",
"String",
"instance",
":",
"boltInstanceNames",
")",
"{",
"String",
"metric",
"=",
"getMetricName",
"(",
")",
"+",
"instance",
"+",
"MetricName",
".",
"METRIC_WAIT_Q_SIZE_SUFFIX",
";",
"Collection",
"<",
"Measurement",
">",
"stmgrResult",
"=",
"metricsProvider",
".",
"getMeasurements",
"(",
"now",
",",
"duration",
",",
"metric",
",",
"COMPONENT_STMGR",
")",
";",
"if",
"(",
"stmgrResult",
".",
"isEmpty",
"(",
")",
")",
"{",
"continue",
";",
"}",
"MeasurementsTable",
"table",
"=",
"MeasurementsTable",
".",
"of",
"(",
"stmgrResult",
")",
".",
"component",
"(",
"COMPONENT_STMGR",
")",
";",
"if",
"(",
"table",
".",
"size",
"(",
")",
"==",
"0",
")",
"{",
"continue",
";",
"}",
"double",
"totalSize",
"=",
"table",
".",
"type",
"(",
"metric",
")",
".",
"sum",
"(",
")",
";",
"Measurement",
"measurement",
"=",
"new",
"Measurement",
"(",
"component",
",",
"instance",
",",
"getMetricName",
"(",
")",
",",
"now",
",",
"totalSize",
")",
";",
"result",
".",
"add",
"(",
"measurement",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | The buffer size as provided by tracker
@return buffer size measurements | [
"The",
"buffer",
"size",
"as",
"provided",
"by",
"tracker"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/healthmgr/src/java/org/apache/heron/healthmgr/sensors/BufferSizeSensor.java#L61-L93 |
27,996 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/common/ConfigLoader.java | ConfigLoader.loadConfig | public static Config loadConfig(String heronHome, String configPath,
String releaseFile, String overrideConfigFile) {
Config defaultConfig = loadDefaults(heronHome, configPath);
Config localConfig = Config.toLocalMode(defaultConfig); //to token-substitute the conf paths
Config.Builder cb = Config.newBuilder()
.putAll(defaultConfig)
.putAll(loadConfig(Context.clusterFile(localConfig)))
.putAll(loadConfig(Context.clientFile(localConfig)))
.putAll(loadConfig(Context.healthmgrFile(localConfig)))
.putAll(loadConfig(Context.packingFile(localConfig)))
.putAll(loadConfig(Context.schedulerFile(localConfig)))
.putAll(loadConfig(Context.stateManagerFile(localConfig)))
.putAll(loadConfig(Context.uploaderFile(localConfig)))
.putAll(loadConfig(Context.downloaderFile(localConfig)))
.putAll(loadConfig(Context.statefulConfigFile(localConfig)))
.putAll(loadConfig(releaseFile))
.putAll(loadConfig(overrideConfigFile));
return cb.build();
} | java | public static Config loadConfig(String heronHome, String configPath,
String releaseFile, String overrideConfigFile) {
Config defaultConfig = loadDefaults(heronHome, configPath);
Config localConfig = Config.toLocalMode(defaultConfig); //to token-substitute the conf paths
Config.Builder cb = Config.newBuilder()
.putAll(defaultConfig)
.putAll(loadConfig(Context.clusterFile(localConfig)))
.putAll(loadConfig(Context.clientFile(localConfig)))
.putAll(loadConfig(Context.healthmgrFile(localConfig)))
.putAll(loadConfig(Context.packingFile(localConfig)))
.putAll(loadConfig(Context.schedulerFile(localConfig)))
.putAll(loadConfig(Context.stateManagerFile(localConfig)))
.putAll(loadConfig(Context.uploaderFile(localConfig)))
.putAll(loadConfig(Context.downloaderFile(localConfig)))
.putAll(loadConfig(Context.statefulConfigFile(localConfig)))
.putAll(loadConfig(releaseFile))
.putAll(loadConfig(overrideConfigFile));
return cb.build();
} | [
"public",
"static",
"Config",
"loadConfig",
"(",
"String",
"heronHome",
",",
"String",
"configPath",
",",
"String",
"releaseFile",
",",
"String",
"overrideConfigFile",
")",
"{",
"Config",
"defaultConfig",
"=",
"loadDefaults",
"(",
"heronHome",
",",
"configPath",
")",
";",
"Config",
"localConfig",
"=",
"Config",
".",
"toLocalMode",
"(",
"defaultConfig",
")",
";",
"//to token-substitute the conf paths",
"Config",
".",
"Builder",
"cb",
"=",
"Config",
".",
"newBuilder",
"(",
")",
".",
"putAll",
"(",
"defaultConfig",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"clusterFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"clientFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"healthmgrFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"packingFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"schedulerFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"stateManagerFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"uploaderFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"downloaderFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"statefulConfigFile",
"(",
"localConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"releaseFile",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"overrideConfigFile",
")",
")",
";",
"return",
"cb",
".",
"build",
"(",
")",
";",
"}"
] | Loads raw configurations from files under the heronHome and configPath. The returned config
must be converted to either local or cluster mode to trigger pattern substitution of wildcards
tokens. | [
"Loads",
"raw",
"configurations",
"from",
"files",
"under",
"the",
"heronHome",
"and",
"configPath",
".",
"The",
"returned",
"config",
"must",
"be",
"converted",
"to",
"either",
"local",
"or",
"cluster",
"mode",
"to",
"trigger",
"pattern",
"substitution",
"of",
"wildcards",
"tokens",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/common/ConfigLoader.java#L56-L75 |
27,997 | apache/incubator-heron | heron/spi/src/java/org/apache/heron/spi/common/ConfigLoader.java | ConfigLoader.loadClusterConfig | public static Config loadClusterConfig() {
Config defaultConfig = loadDefaults(
Key.HERON_CLUSTER_HOME.getDefaultString(), Key.HERON_CLUSTER_CONF.getDefaultString());
Config clusterConfig = Config.toClusterMode(defaultConfig); //to token-substitute the conf paths
Config.Builder cb = Config.newBuilder()
.putAll(defaultConfig)
.putAll(loadConfig(Context.packingFile(clusterConfig)))
.putAll(loadConfig(Context.healthmgrFile(clusterConfig)))
.putAll(loadConfig(Context.schedulerFile(clusterConfig)))
.putAll(loadConfig(Context.stateManagerFile(clusterConfig)))
.putAll(loadConfig(Context.uploaderFile(clusterConfig)))
.putAll(loadConfig(Context.downloaderFile(clusterConfig)))
.putAll(loadConfig(Context.statefulConfigFile(clusterConfig)));
// Add the override config at the end to replace any existing configs
cb.putAll(loadConfig(Context.overrideFile(clusterConfig)));
return cb.build();
} | java | public static Config loadClusterConfig() {
Config defaultConfig = loadDefaults(
Key.HERON_CLUSTER_HOME.getDefaultString(), Key.HERON_CLUSTER_CONF.getDefaultString());
Config clusterConfig = Config.toClusterMode(defaultConfig); //to token-substitute the conf paths
Config.Builder cb = Config.newBuilder()
.putAll(defaultConfig)
.putAll(loadConfig(Context.packingFile(clusterConfig)))
.putAll(loadConfig(Context.healthmgrFile(clusterConfig)))
.putAll(loadConfig(Context.schedulerFile(clusterConfig)))
.putAll(loadConfig(Context.stateManagerFile(clusterConfig)))
.putAll(loadConfig(Context.uploaderFile(clusterConfig)))
.putAll(loadConfig(Context.downloaderFile(clusterConfig)))
.putAll(loadConfig(Context.statefulConfigFile(clusterConfig)));
// Add the override config at the end to replace any existing configs
cb.putAll(loadConfig(Context.overrideFile(clusterConfig)));
return cb.build();
} | [
"public",
"static",
"Config",
"loadClusterConfig",
"(",
")",
"{",
"Config",
"defaultConfig",
"=",
"loadDefaults",
"(",
"Key",
".",
"HERON_CLUSTER_HOME",
".",
"getDefaultString",
"(",
")",
",",
"Key",
".",
"HERON_CLUSTER_CONF",
".",
"getDefaultString",
"(",
")",
")",
";",
"Config",
"clusterConfig",
"=",
"Config",
".",
"toClusterMode",
"(",
"defaultConfig",
")",
";",
"//to token-substitute the conf paths",
"Config",
".",
"Builder",
"cb",
"=",
"Config",
".",
"newBuilder",
"(",
")",
".",
"putAll",
"(",
"defaultConfig",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"packingFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"healthmgrFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"schedulerFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"stateManagerFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"uploaderFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"downloaderFile",
"(",
"clusterConfig",
")",
")",
")",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"statefulConfigFile",
"(",
"clusterConfig",
")",
")",
")",
";",
"// Add the override config at the end to replace any existing configs",
"cb",
".",
"putAll",
"(",
"loadConfig",
"(",
"Context",
".",
"overrideFile",
"(",
"clusterConfig",
")",
")",
")",
";",
"return",
"cb",
".",
"build",
"(",
")",
";",
"}"
] | Loads raw configurations using the default configured heronHome and configPath on the cluster.
The returned config must be converted to either local or cluster mode to trigger pattern
substitution of wildcards tokens. | [
"Loads",
"raw",
"configurations",
"using",
"the",
"default",
"configured",
"heronHome",
"and",
"configPath",
"on",
"the",
"cluster",
".",
"The",
"returned",
"config",
"must",
"be",
"converted",
"to",
"either",
"local",
"or",
"cluster",
"mode",
"to",
"trigger",
"pattern",
"substitution",
"of",
"wildcards",
"tokens",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/common/ConfigLoader.java#L82-L101 |
27,998 | apache/incubator-heron | heron/api/src/java/org/apache/heron/api/bolt/StatefulWindowedBoltExecutor.java | StatefulWindowedBoltExecutor.initState | @Override
public void initState(State state) {
this.state = state;
// initalize internal windowing state
super.initState(this.state);
// initialize user defined state
if (!this.state.containsKey(USER_STATE)) {
this.state.put(USER_STATE, new HashMapState<K, V>());
}
this.statefulWindowedBolt.initState((State<K, V>) this.state.get(USER_STATE));
} | java | @Override
public void initState(State state) {
this.state = state;
// initalize internal windowing state
super.initState(this.state);
// initialize user defined state
if (!this.state.containsKey(USER_STATE)) {
this.state.put(USER_STATE, new HashMapState<K, V>());
}
this.statefulWindowedBolt.initState((State<K, V>) this.state.get(USER_STATE));
} | [
"@",
"Override",
"public",
"void",
"initState",
"(",
"State",
"state",
")",
"{",
"this",
".",
"state",
"=",
"state",
";",
"// initalize internal windowing state",
"super",
".",
"initState",
"(",
"this",
".",
"state",
")",
";",
"// initialize user defined state",
"if",
"(",
"!",
"this",
".",
"state",
".",
"containsKey",
"(",
"USER_STATE",
")",
")",
"{",
"this",
".",
"state",
".",
"put",
"(",
"USER_STATE",
",",
"new",
"HashMapState",
"<",
"K",
",",
"V",
">",
"(",
")",
")",
";",
"}",
"this",
".",
"statefulWindowedBolt",
".",
"initState",
"(",
"(",
"State",
"<",
"K",
",",
"V",
">",
")",
"this",
".",
"state",
".",
"get",
"(",
"USER_STATE",
")",
")",
";",
"}"
] | initalize state that is partitioned by window internal and user defined
@param state | [
"initalize",
"state",
"that",
"is",
"partitioned",
"by",
"window",
"internal",
"and",
"user",
"defined"
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/api/src/java/org/apache/heron/api/bolt/StatefulWindowedBoltExecutor.java#L46-L56 |
27,999 | apache/incubator-heron | heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java | ErrorReportLoggingHandler.publish | @Override
public void publish(LogRecord record) {
// Convert Log
Throwable throwable = record.getThrown();
if (throwable != null) {
synchronized (ExceptionRepositoryAsMetrics.INSTANCE) {
// We would not include the message if already exceeded the exceptions limit
if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) {
droppedExceptionsCount.incr();
return;
}
// Convert the record
StringWriter sink = new StringWriter();
throwable.printStackTrace(new PrintWriter(sink, true));
String trace = sink.toString();
Metrics.ExceptionData.Builder exceptionDataBuilder =
ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace);
exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1);
exceptionDataBuilder.setLasttime(new Date().toString());
exceptionDataBuilder.setStacktrace(trace);
// Can cause NPE and crash HI
//exceptionDataBuilder.setLogging(record.getMessage());
if (record.getMessage() == null) {
exceptionDataBuilder.setLogging("");
} else {
exceptionDataBuilder.setLogging(record.getMessage());
}
}
}
} | java | @Override
public void publish(LogRecord record) {
// Convert Log
Throwable throwable = record.getThrown();
if (throwable != null) {
synchronized (ExceptionRepositoryAsMetrics.INSTANCE) {
// We would not include the message if already exceeded the exceptions limit
if (ExceptionRepositoryAsMetrics.INSTANCE.getExceptionsCount() >= exceptionsLimit) {
droppedExceptionsCount.incr();
return;
}
// Convert the record
StringWriter sink = new StringWriter();
throwable.printStackTrace(new PrintWriter(sink, true));
String trace = sink.toString();
Metrics.ExceptionData.Builder exceptionDataBuilder =
ExceptionRepositoryAsMetrics.INSTANCE.getExceptionInfo(trace);
exceptionDataBuilder.setCount(exceptionDataBuilder.getCount() + 1);
exceptionDataBuilder.setLasttime(new Date().toString());
exceptionDataBuilder.setStacktrace(trace);
// Can cause NPE and crash HI
//exceptionDataBuilder.setLogging(record.getMessage());
if (record.getMessage() == null) {
exceptionDataBuilder.setLogging("");
} else {
exceptionDataBuilder.setLogging(record.getMessage());
}
}
}
} | [
"@",
"Override",
"public",
"void",
"publish",
"(",
"LogRecord",
"record",
")",
"{",
"// Convert Log",
"Throwable",
"throwable",
"=",
"record",
".",
"getThrown",
"(",
")",
";",
"if",
"(",
"throwable",
"!=",
"null",
")",
"{",
"synchronized",
"(",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
")",
"{",
"// We would not include the message if already exceeded the exceptions limit",
"if",
"(",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
".",
"getExceptionsCount",
"(",
")",
">=",
"exceptionsLimit",
")",
"{",
"droppedExceptionsCount",
".",
"incr",
"(",
")",
";",
"return",
";",
"}",
"// Convert the record",
"StringWriter",
"sink",
"=",
"new",
"StringWriter",
"(",
")",
";",
"throwable",
".",
"printStackTrace",
"(",
"new",
"PrintWriter",
"(",
"sink",
",",
"true",
")",
")",
";",
"String",
"trace",
"=",
"sink",
".",
"toString",
"(",
")",
";",
"Metrics",
".",
"ExceptionData",
".",
"Builder",
"exceptionDataBuilder",
"=",
"ExceptionRepositoryAsMetrics",
".",
"INSTANCE",
".",
"getExceptionInfo",
"(",
"trace",
")",
";",
"exceptionDataBuilder",
".",
"setCount",
"(",
"exceptionDataBuilder",
".",
"getCount",
"(",
")",
"+",
"1",
")",
";",
"exceptionDataBuilder",
".",
"setLasttime",
"(",
"new",
"Date",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"exceptionDataBuilder",
".",
"setStacktrace",
"(",
"trace",
")",
";",
"// Can cause NPE and crash HI",
"//exceptionDataBuilder.setLogging(record.getMessage());",
"if",
"(",
"record",
".",
"getMessage",
"(",
")",
"==",
"null",
")",
"{",
"exceptionDataBuilder",
".",
"setLogging",
"(",
"\"\"",
")",
";",
"}",
"else",
"{",
"exceptionDataBuilder",
".",
"setLogging",
"(",
"record",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] | will flush the exception to metrics manager during getValueAndReset call. | [
"will",
"flush",
"the",
"exception",
"to",
"metrics",
"manager",
"during",
"getValueAndReset",
"call",
"."
] | 776abe2b5a45b93a0eb957fd65cbc149d901a92a | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/common/src/java/org/apache/heron/common/utils/logging/ErrorReportLoggingHandler.java#L90-L123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.