Remove empty TLD parameter when fanning out without TLDs

TldFanoutAction fans out a given endpoint to all TLDs (either TEST, REAL, or
both).

However, it is also used to delegate a single endpoint request that we want set
in a specific queue (so we can control retries). We do that by setting the TLD
list to "runInEmpty" rather than "forEachRealTld" or "forEachTestTld".

Currently, using "runInEmpty" would still specify a TLD - but that TLD would be
the empty string. This is a bug: it sets the TLD parameter to a bad value. It
worked only because none of the endpoints called with "runInEmpty" were using
the TLD parameter.

However, this will (and does) break if either (a) the endpoint accepts an
optional TLD parameter (like deleteProberData does), or (b) the given endpoint
already has a TLD parameter in it (we want to run the endpoint with a single
TLD, but still use the "fanout" to set the right queue).

This CL fixes several things:

- if runInEmpty is given, no TLD parameter is added
- 'runInEmpty' is now mutually exclusive with 'forEach*Tld' and 'excludes'
- we do some sanity checks and added logging
- removed the buggy and unused "':tld' in path is replaced by TLD"
- in the cron.xml, removed documentation for :tld and the broken :registrar

Note that none of the endpoints that were used with runInEmpty fanout had the TLD parameter prior to deleteProberData

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=189954585
This commit is contained in:
guyben 2018-03-21 13:07:55 -07:00 committed by jianglai
parent edcb725a18
commit 63785e5149
5 changed files with 111 additions and 69 deletions

View file

@ -16,13 +16,13 @@ package google.registry.cron;
import static com.google.appengine.api.taskqueue.QueueFactory.getQueue; import static com.google.appengine.api.taskqueue.QueueFactory.getQueue;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not; import static com.google.common.base.Predicates.not;
import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Iterables.getFirst; import static com.google.common.collect.Iterables.getFirst;
import static com.google.common.collect.Multimaps.filterKeys; import static com.google.common.collect.Multimaps.filterKeys;
import static com.google.common.collect.Sets.difference;
import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8; import static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;
import static google.registry.model.registry.Registries.getTldsOfType; import static google.registry.model.registry.Registries.getTldsOfType;
import static google.registry.model.registry.Registry.TldType.REAL; import static google.registry.model.registry.Registry.TldType.REAL;
@ -42,10 +42,11 @@ import google.registry.request.ParameterMap;
import google.registry.request.RequestParameters; import google.registry.request.RequestParameters;
import google.registry.request.Response; import google.registry.request.Response;
import google.registry.request.auth.Auth; import google.registry.request.auth.Auth;
import google.registry.util.FormattingLogger;
import google.registry.util.TaskEnqueuer; import google.registry.util.TaskEnqueuer;
import java.util.Optional; import java.util.Optional;
import java.util.Random; import java.util.Random;
import java.util.Set; import java.util.stream.Stream;
import javax.inject.Inject; import javax.inject.Inject;
/** /**
@ -58,10 +59,10 @@ import javax.inject.Inject;
* <li>{@code queue} (Required) Name of the App Engine push queue to which this task should be sent. * <li>{@code queue} (Required) Name of the App Engine push queue to which this task should be sent.
* <li>{@code forEachRealTld} Launch the task in each real TLD namespace. * <li>{@code forEachRealTld} Launch the task in each real TLD namespace.
* <li>{@code forEachTestTld} Launch the task in each test TLD namespace. * <li>{@code forEachTestTld} Launch the task in each test TLD namespace.
* <li>{@code runInEmpty} Launch the task in the empty namespace. * <li>{@code runInEmpty} Launch the task once, without the TLD argument.
* <li>{@code exclude} TLDs to exclude. * <li>{@code exclude} TLDs to exclude.
* <li>{@code jitterSeconds} Randomly delay each task by up to this many seconds. * <li>{@code jitterSeconds} Randomly delay each task by up to this many seconds.
* <li>Any other parameters specified will be passed through as POST parameters to the called task. * <li>Any other parameters specified will be passed through as POST parameters to the called task.
* </ul> * </ul>
* *
* <h3>Patharg Reference</h3> * <h3>Patharg Reference</h3>
@ -98,9 +99,10 @@ public final class TldFanoutAction implements Runnable {
EXCLUDE_PARAM, EXCLUDE_PARAM,
JITTER_SECONDS_PARAM); JITTER_SECONDS_PARAM);
private static final String TLD_PATHARG = ":tld";
private static final Random random = new Random(); private static final Random random = new Random();
private static final FormattingLogger logger = FormattingLogger.getLoggerForCallerClass();
@Inject TaskEnqueuer taskEnqueuer; @Inject TaskEnqueuer taskEnqueuer;
@Inject Response response; @Inject Response response;
@Inject @Parameter(ENDPOINT_PARAM) String endpoint; @Inject @Parameter(ENDPOINT_PARAM) String endpoint;
@ -115,28 +117,40 @@ public final class TldFanoutAction implements Runnable {
@Override @Override
public void run() { public void run() {
Set<String> tlds = checkArgument(
difference( !(runInEmpty && (forEachTestTld || forEachRealTld)),
Streams.concat( "runInEmpty and forEach*Tld are mutually exclusive");
Streams.stream(runInEmpty ? ImmutableSet.of("") : ImmutableSet.of()), checkArgument(
Streams.stream( runInEmpty || forEachTestTld || forEachRealTld,
forEachRealTld ? getTldsOfType(REAL) : ImmutableSet.of()), "At least one of runInEmpty, forEachTestTld, forEachRealTld must be given");
Streams.stream( checkArgument(
forEachTestTld ? getTldsOfType(TEST) : ImmutableSet.of())) !(runInEmpty && !excludes.isEmpty()),
.collect(toImmutableSet()), "Can't specify 'exclude' with 'runInEmpty'");
excludes); ImmutableSet<String> tlds =
Streams.concat(
runInEmpty ? Stream.of("") : Stream.of(),
forEachRealTld ? getTldsOfType(REAL).stream() : Stream.of(),
forEachTestTld ? getTldsOfType(TEST).stream() : Stream.of())
.filter(tld -> !excludes.contains(tld))
.collect(toImmutableSet());
Multimap<String, String> flowThruParams = filterKeys(params, not(in(CONTROL_PARAMS))); Multimap<String, String> flowThruParams = filterKeys(params, not(in(CONTROL_PARAMS)));
Queue taskQueue = getQueue(queue); Queue taskQueue = getQueue(queue);
StringBuilder outputPayload = StringBuilder outputPayload =
new StringBuilder( new StringBuilder(
String.format("OK: Launched the following %d tasks in queue %s\n", tlds.size(), queue)); String.format("OK: Launched the following %d tasks in queue %s\n", tlds.size(), queue));
logger.infofmt("Launching %d tasks in queue %s", tlds.size(), queue);
if (tlds.isEmpty()) {
logger.warning("No TLDs to fan-out!");
}
for (String tld : tlds) { for (String tld : tlds) {
TaskOptions taskOptions = createTaskOptions(tld, flowThruParams); TaskOptions taskOptions = createTaskOptions(tld, flowThruParams);
TaskHandle taskHandle = taskEnqueuer.enqueue(taskQueue, taskOptions); TaskHandle taskHandle = taskEnqueuer.enqueue(taskQueue, taskOptions);
outputPayload.append( outputPayload.append(
String.format( String.format(
"- Task: %s, tld: %s, endpoint: %s\n", "- Task: '%s', tld: '%s', endpoint: '%s'\n",
taskHandle.getName(), tld, taskOptions.getUrl())); taskHandle.getName(), tld, taskOptions.getUrl()));
logger.infofmt("Task: '%s', tld: '%s', endpoint: '%s'",
taskHandle.getName(), tld, taskOptions.getUrl());
} }
response.setContentType(PLAIN_TEXT_UTF_8); response.setContentType(PLAIN_TEXT_UTF_8);
response.setPayload(outputPayload.toString()); response.setPayload(outputPayload.toString());
@ -144,12 +158,14 @@ public final class TldFanoutAction implements Runnable {
private TaskOptions createTaskOptions(String tld, Multimap<String, String> params) { private TaskOptions createTaskOptions(String tld, Multimap<String, String> params) {
TaskOptions options = TaskOptions options =
withUrl(endpoint.replace(TLD_PATHARG, String.valueOf(tld))) withUrl(endpoint)
.countdownMillis( .countdownMillis(
jitterSeconds.isPresent() jitterSeconds
? random.nextInt((int) SECONDS.toMillis(jitterSeconds.get())) .map(seconds -> random.nextInt((int) SECONDS.toMillis(seconds)))
: 0); .orElse(0));
options.param(RequestParameters.PARAM_TLD, tld); if (!tld.isEmpty()) {
options.param(RequestParameters.PARAM_TLD, tld);
}
for (String param : params.keySet()) { for (String param : params.keySet()) {
// TaskOptions.param() does not accept null values. // TaskOptions.param() does not accept null values.
options.param(param, nullToEmpty((getFirst(params.get(param), null)))); options.param(param, nullToEmpty((getFirst(params.get(param), null))));

View file

@ -5,9 +5,7 @@
/cron/fanout params: /cron/fanout params:
queue=<QUEUE_NAME> queue=<QUEUE_NAME>
endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders: endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders:
// :tld - Replaced with the TLD, e.g. foo, soy runInEmpty // Run once, with no tld parameter
// :registrar - Replaced with registrar clientId
runInEmpty // Run in the empty namespace
forEachRealTld // Run for tlds with getTldType() == TldType.REAL forEachRealTld // Run for tlds with getTldType() == TldType.REAL
forEachTestTld // Run for tlds with getTldType() == TldType.TEST forEachTestTld // Run for tlds with getTldType() == TldType.TEST
exclude=TLD1[&exclude=TLD2] // exclude something otherwise included exclude=TLD1[&exclude=TLD2] // exclude something otherwise included

View file

@ -5,9 +5,7 @@
/cron/fanout params: /cron/fanout params:
queue=<QUEUE_NAME> queue=<QUEUE_NAME>
endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders: endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders:
// :tld - Replaced with the TLD, e.g. foo, soy runInEmpty // Run once, with no tld parameter
// :registrar - Replaced with registrar clientId
runInEmpty // Run in the empty namespace
forEachRealTld // Run for tlds with getTldType() == TldType.REAL forEachRealTld // Run for tlds with getTldType() == TldType.REAL
forEachTestTld // Run for tlds with getTldType() == TldType.TEST forEachTestTld // Run for tlds with getTldType() == TldType.TEST
exclude=TLD1[&exclude=TLD2] // exclude something otherwise included exclude=TLD1[&exclude=TLD2] // exclude something otherwise included

View file

@ -5,9 +5,7 @@
/cron/fanout params: /cron/fanout params:
queue=<QUEUE_NAME> queue=<QUEUE_NAME>
endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders: endpoint=<ENDPOINT_NAME> // URL Path of servlet, which may contain placeholders:
// :tld - Replaced with the TLD, e.g. foo, soy runInEmpty // Run once, with no tld parameter
// :registrar - Replaced with registrar clientId
runInEmpty // Run in the empty namespace
forEachRealTld // Run for tlds with getTldType() == TldType.REAL forEachRealTld // Run for tlds with getTldType() == TldType.REAL
forEachTestTld // Run for tlds with getTldType() == TldType.TEST forEachTestTld // Run for tlds with getTldType() == TldType.TEST
exclude=TLD1[&exclude=TLD2] // exclude something otherwise included exclude=TLD1[&exclude=TLD2] // exclude something otherwise included

View file

@ -14,14 +14,14 @@
package google.registry.cron; package google.registry.cron;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Lists.transform;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static google.registry.testing.DatastoreHelper.createTlds; import static google.registry.testing.DatastoreHelper.createTlds;
import static google.registry.testing.DatastoreHelper.persistResource; import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.testing.JUnitBackports.assertThrows;
import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertNoTasksEnqueued;
import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued; import static google.registry.testing.TaskQueueHelper.assertTasksEnqueued;
import static java.util.Arrays.asList;
import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo; import com.google.appengine.api.taskqueue.dev.QueueStateInfo.TaskStateInfo;
import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig; import com.google.appengine.tools.development.testing.LocalTaskQueueTestConfig;
@ -38,6 +38,7 @@ import google.registry.util.Retrier;
import google.registry.util.TaskEnqueuer; import google.registry.util.TaskEnqueuer;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Stream;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
@ -101,24 +102,21 @@ public class TldFanoutActionTest {
private static void assertTasks(String... tasks) throws Exception { private static void assertTasks(String... tasks) throws Exception {
assertTasksEnqueued( assertTasksEnqueued(
QUEUE, QUEUE,
transform( Stream.of(tasks).map(
asList(tasks), namespace ->
(String namespace) ->
new TaskMatcher() new TaskMatcher()
.url(ENDPOINT) .url(ENDPOINT)
.header("content-type", "application/x-www-form-urlencoded") .header("content-type", "application/x-www-form-urlencoded")
.param("tld", namespace))); .param("tld", namespace))
.collect(toImmutableList()));
} }
@Test private static void assertTaskWithoutTld() throws Exception {
public void testSuccess_pathargTld() throws Exception { assertTasksEnqueued(
run(getParamsMap( QUEUE,
"forEachRealTld", "", new TaskMatcher()
"endpoint", "/the/servlet/:tld")); .url(ENDPOINT)
assertTasksEnqueued(QUEUE, .header("content-type", "application/x-www-form-urlencoded"));
new TaskMatcher().url("/the/servlet/com"),
new TaskMatcher().url("/the/servlet/net"),
new TaskMatcher().url("/the/servlet/org"));
} }
@Test @Test
@ -128,15 +126,14 @@ public class TldFanoutActionTest {
} }
@Test @Test
public void testSuccess_noTlds() throws Exception { public void testFailure_noTlds() throws Exception {
run(getParamsMap()); assertThrows(IllegalArgumentException.class, () -> run(getParamsMap()));
assertNoTasksEnqueued(QUEUE);
} }
@Test @Test
public void testSuccess_runInEmpty() throws Exception { public void testSuccess_runInEmpty() throws Exception {
run(getParamsMap("runInEmpty", "")); run(getParamsMap("runInEmpty", ""));
assertTasks(""); assertTaskWithoutTld();
} }
@Test @Test
@ -151,12 +148,6 @@ public class TldFanoutActionTest {
assertTasks("example"); assertTasks("example");
} }
@Test
public void testSuccess_runInEmptyAndRunInRealTld() throws Exception {
run(getParamsMap("runInEmpty", "", "forEachRealTld", ""));
assertTasks("", "com", "net", "org");
}
@Test @Test
public void testSuccess_forEachTestTldAndForEachRealTld() throws Exception { public void testSuccess_forEachTestTldAndForEachRealTld() throws Exception {
run(getParamsMap( run(getParamsMap(
@ -165,16 +156,10 @@ public class TldFanoutActionTest {
assertTasks("com", "net", "org", "example"); assertTasks("com", "net", "org", "example");
} }
@Test
public void testSuccess_runInEmptyAndForEachTestTld() throws Exception {
run(getParamsMap("runInEmpty", "", "forEachTestTld", ""));
assertTasks("", "example");
}
@Test @Test
public void testSuccess_runEverywhere() throws Exception { public void testSuccess_runEverywhere() throws Exception {
run(getParamsMap("runInEmpty", "", "forEachTestTld", "", "forEachRealTld", "")); run(getParamsMap("forEachTestTld", "", "forEachRealTld", ""));
assertTasks("", "com", "net", "org", "example"); assertTasks("com", "net", "org", "example");
} }
@Test @Test
@ -196,11 +181,43 @@ public class TldFanoutActionTest {
@Test @Test
public void testSuccess_excludeNonexistentTlds() throws Exception { public void testSuccess_excludeNonexistentTlds() throws Exception {
run(getParamsMap( run(getParamsMap(
"runInEmpty", "",
"forEachTestTld", "", "forEachTestTld", "",
"forEachRealTld", "", "forEachRealTld", "",
"exclude", "foo")); "exclude", "foo"));
assertTasks("", "com", "net", "org", "example"); assertTasks("com", "net", "org", "example");
}
@Test
public void testFailure_runInEmptyAndTest() throws Exception {
assertThrows(
IllegalArgumentException.class,
() ->
run(
getParamsMap(
"runInEmpty", "",
"forEachTestTld", "")));
}
@Test
public void testFailure_runInEmptyAndReal() throws Exception {
assertThrows(
IllegalArgumentException.class,
() ->
run(
getParamsMap(
"runInEmpty", "",
"forEachRealTld", "")));
}
@Test
public void testFailure_runInEmptyAndExclude() throws Exception {
assertThrows(
IllegalArgumentException.class,
() ->
run(
getParamsMap(
"runInEmpty", "",
"exclude", "foo")));
} }
@Test @Test
@ -212,7 +229,7 @@ public class TldFanoutActionTest {
@Test @Test
public void testSuccess_returnHttpResponse() throws Exception { public void testSuccess_returnHttpResponse() throws Exception {
run(getParamsMap("forEachRealTld", "", "endpoint", "/the/servlet/:tld")); run(getParamsMap("forEachRealTld", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList = List<TaskStateInfo> taskList =
LocalTaskQueueTestConfig.getLocalTaskQueue().getQueueStateInfo().get(QUEUE).getTaskInfo(); LocalTaskQueueTestConfig.getLocalTaskQueue().getQueueStateInfo().get(QUEUE).getTaskInfo();
@ -220,12 +237,27 @@ public class TldFanoutActionTest {
assertThat(taskList).hasSize(3); assertThat(taskList).hasSize(3);
String expectedResponse = String.format( String expectedResponse = String.format(
"OK: Launched the following 3 tasks in queue the-queue\n" "OK: Launched the following 3 tasks in queue the-queue\n"
+ "- Task: %s, tld: com, endpoint: /the/servlet/com\n" + "- Task: '%s', tld: 'com', endpoint: '/the/servlet'\n"
+ "- Task: %s, tld: net, endpoint: /the/servlet/net\n" + "- Task: '%s', tld: 'net', endpoint: '/the/servlet'\n"
+ "- Task: %s, tld: org, endpoint: /the/servlet/org\n", + "- Task: '%s', tld: 'org', endpoint: '/the/servlet'\n",
taskList.get(0).getTaskName(), taskList.get(0).getTaskName(),
taskList.get(1).getTaskName(), taskList.get(1).getTaskName(),
taskList.get(2).getTaskName()); taskList.get(2).getTaskName());
assertThat(response.getPayload()).isEqualTo(expectedResponse); assertThat(response.getPayload()).isEqualTo(expectedResponse);
} }
@Test
public void testSuccess_returnHttpResponse_runInEmpty() throws Exception {
run(getParamsMap("runInEmpty", "", "endpoint", "/the/servlet"));
List<TaskStateInfo> taskList =
LocalTaskQueueTestConfig.getLocalTaskQueue().getQueueStateInfo().get(QUEUE).getTaskInfo();
assertThat(taskList).hasSize(1);
String expectedResponse = String.format(
"OK: Launched the following 1 tasks in queue the-queue\n"
+ "- Task: '%s', tld: '', endpoint: '/the/servlet'\n",
taskList.get(0).getTaskName());
assertThat(response.getPayload()).isEqualTo(expectedResponse);
}
} }