use of com.facebook.buck.timing.DefaultClock in project buck by facebook.
the class CleanCommandTest method createCommandRunnerParams.
private CommandRunnerParams createCommandRunnerParams() throws InterruptedException, IOException {
projectFilesystem = new FakeProjectFilesystem();
Cell cell = new TestCellBuilder().setFilesystem(projectFilesystem).build();
Supplier<AndroidPlatformTarget> androidPlatformTargetSupplier = AndroidPlatformTarget.EXPLODING_ANDROID_PLATFORM_TARGET_SUPPLIER;
return CommandRunnerParams.builder().setConsole(new TestConsole()).setStdIn(new ByteArrayInputStream("".getBytes("UTF-8"))).setCell(cell).setAndroidPlatformTargetSupplier(androidPlatformTargetSupplier).setArtifactCacheFactory(new SingletonArtifactCacheFactory(new NoopArtifactCache())).setBuckEventBus(BuckEventBusFactory.newInstance()).setParser(createMock(Parser.class)).setPlatform(Platform.detect()).setEnvironment(ImmutableMap.copyOf(System.getenv())).setJavaPackageFinder(new FakeJavaPackageFinder()).setObjectMapper(ObjectMappers.newDefaultInstance()).setClock(new DefaultClock()).setProcessManager(Optional.empty()).setWebServer(Optional.empty()).setBuckConfig(FakeBuckConfig.builder().build()).setFileHashCache(new StackedFileHashCache(ImmutableList.of())).setExecutors(ImmutableMap.of()).setBuildEnvironmentDescription(CommandRunnerParamsForTesting.BUILD_ENVIRONMENT_DESCRIPTION).setVersionedTargetGraphCache(new VersionedTargetGraphCache()).setActionGraphCache(new ActionGraphCache(new BroadcastEventListener())).setKnownBuildRuleTypesFactory(new KnownBuildRuleTypesFactory(new FakeProcessExecutor(), new FakeAndroidDirectoryResolver())).build();
}
use of com.facebook.buck.timing.DefaultClock in project buck by facebook.
the class ArtifactCaches method createHttpArtifactCache.
private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
// Setup the default client to use.
OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
int timeoutSeconds = cacheDescription.getTimeoutSeconds();
setTimeouts(storeClientBuilder, timeoutSeconds);
storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
(int) config.getThreadPoolSize(), /* keepAliveDurationMs */
config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
// The artifact cache effectively only connects to a single host at a time. We should allow as
// many concurrent connections to that host as we allow threads.
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
storeClientBuilder.dispatcher(dispatcher);
final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
// If write headers are specified, add them to every default client request.
if (!writeHeaders.isEmpty()) {
storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
}
OkHttpClient storeClient = storeClientBuilder.build();
// For fetches, use a client with a read timeout.
OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
setTimeouts(fetchClientBuilder, timeoutSeconds);
// If read headers are specified, add them to every read client request.
if (!readHeaders.isEmpty()) {
fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
}
fetchClientBuilder.networkInterceptors().add((chain -> {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
}));
OkHttpClient fetchClient = fetchClientBuilder.build();
HttpService fetchService;
HttpService storeService;
switch(config.getLoadBalancingType()) {
case CLIENT_SLB:
HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
break;
case SINGLE_SERVER:
URI url = cacheDescription.getUrl();
fetchService = new SingleUriService(url, fetchClient);
storeService = new SingleUriService(url, storeClient);
break;
default:
throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
}
String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
use of com.facebook.buck.timing.DefaultClock in project buck by facebook.
the class BuckEventBusTest method testShutdownSuccess.
@Test
public void testShutdownSuccess() throws Exception {
BuckEventBus eb = new BuckEventBus(new DefaultClock(), false, BuckEventBusFactory.BUILD_ID_FOR_TEST, timeoutMillis);
eb.register(new SleepSubscriber());
eb.post(new SleepEvent(1));
long start = System.nanoTime();
eb.close();
long durationNanos = System.nanoTime() - start;
long durationMillis = TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS);
assertThat("Shutdown should not take a long time.", durationMillis, lessThanOrEqualTo((long) timeoutMillis));
}
use of com.facebook.buck.timing.DefaultClock in project buck by facebook.
the class BuckEventBusTest method whenEventTimestampedThenEventCannotBePosted.
@Test
public void whenEventTimestampedThenEventCannotBePosted() throws IOException {
BuckEventBus eb = new BuckEventBus(new DefaultClock(), false, BuckEventBusFactory.BUILD_ID_FOR_TEST, timeoutMillis);
TestEvent event = new TestEvent();
eb.timestamp(event);
try {
eb.post(event);
fail("Post should throw IllegalStateException.");
} catch (IllegalStateException e) {
assertThat("Exception should be due to double configuration.", e.getMessage(), containsString("Events can only be configured once."));
} finally {
eb.close();
}
}
use of com.facebook.buck.timing.DefaultClock in project buck by facebook.
the class PublicAnnouncementManagerIntegrationTest method testAnnouncementsWork.
@Test
public void testAnnouncementsWork() throws Exception {
final AtomicReference<byte[]> requestBody = new AtomicReference<>();
try (HttpdForTests httpd = new HttpdForTests()) {
httpd.addHandler(new AbstractHandler() {
@Override
public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
httpServletResponse.setStatus(200);
request.setHandled(true);
if (request.getUri().getPath().equals("/status.php")) {
return;
}
requestBody.set(ByteStreams.toByteArray(httpServletRequest.getInputStream()));
FrontendRequest thriftRequest = new FrontendRequest();
ThriftUtil.deserialize(ThriftProtocol.BINARY, requestBody.get(), thriftRequest);
assertTrue("Request should contain the repository.", thriftRequest.getAnnouncementRequest().getRepository().equals(REPOSITORY));
try (DataOutputStream out = new DataOutputStream(httpServletResponse.getOutputStream())) {
Announcement announcement = new Announcement();
announcement.setErrorMessage(ERROR_MSG);
announcement.setSolutionMessage(SOLUTION_MSG);
AnnouncementResponse announcementResponse = new AnnouncementResponse();
announcementResponse.setAnnouncements(ImmutableList.of(announcement));
FrontendResponse frontendResponse = new FrontendResponse();
frontendResponse.setType(FrontendRequestType.ANNOUNCEMENT);
frontendResponse.setAnnouncementResponse(announcementResponse);
out.write(ThriftUtil.serialize(ThriftProtocol.BINARY, frontendResponse));
}
}
});
httpd.start();
Clock clock = new DefaultClock();
BuckEventBus eventBus = BuckEventBusFactory.newInstance(clock);
ExecutionEnvironment executionEnvironment = new DefaultExecutionEnvironment(ImmutableMap.copyOf(System.getenv()), System.getProperties());
BuckConfig buckConfig = new FakeBuckConfig.Builder().setSections(ImmutableMap.of("log", ImmutableMap.of("slb_server_pool", "http://localhost:" + httpd.getRootUri().getPort()))).build();
TestConsole console = new TestConsole();
SuperConsoleEventBusListener listener = new SuperConsoleEventBusListener(new SuperConsoleConfig(FakeBuckConfig.builder().build()), console, clock, /* verbosity */
TestResultSummaryVerbosity.of(false, false), executionEnvironment, Optional.empty(), Locale.US, logPath, TimeZone.getTimeZone("UTC"));
eventBus.register(listener);
PublicAnnouncementManager manager = new PublicAnnouncementManager(clock, eventBus, listener, REPOSITORY, new RemoteLogBuckConfig(buckConfig), MoreExecutors.newDirectExecutorService());
manager.getAndPostAnnouncements();
Optional<String> announcements = listener.getPublicAnnouncements();
assertEquals("The header and the message", announcements.get(), "**-------------------------------**\n" + "**- Sticky Public Announcements -**\n" + "**-------------------------------**\n" + "** This is the error message. This is the solution message.");
}
}
Aggregations